0 Replies - 357 Views - Last Post: 24 March 2019 - 08:38 AM Rate Topic: -----

#1 Addie Astra   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-March 19

Pygame: Blitted surface only shows up once

Posted 24 March 2019 - 08:38 AM

Hello everyone.
I'm new to programming, so to get my code to work I followed the code of Al Sweigart to program a match-3-game into the game I'm making. (http://inventwithpython.com/makinggames.pdf page 435 and following)
I'm expecting that every time the display is updated, everything I blitted on it before will show up in exactly the order I blitted it onto my surface. That means, the background, the dragon and then the board with the gems. What I am seeing is that the first time the surface is updated, everything shows up more or less how I expect it, but every following time the gems aren't drawn on the surface. The grid doesn't seem to appear at all, not even the first time. (the function drawBoard is responsible for these actions.) I don't get any errors.
I've tried googling for reasons this could be and debugged the code, stepping through everything the code does while drawing the gems. I cannot spot a difference between the first and the following times. I'm at a loss and would be happy if anyone can help me get this to work.
Here is my class:

  

import pygame, sys
from pygame.locals import *
import random
from os import path
import copy
import configparser

from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import func
from sqlalchemy import select

Base = declarative_base()

config = configparser.ConfigParser()
config.read('config.ini')  #filename
config = config['DEFAULT']  #section

[...]

class IslandDB(Base):
    __tablename__ = 'island'
    id = Column(Integer, primary_key=True)
    name = Column(String)  #  name of the island
    commondragon = Column(String)  #  dragon species that is common there, rare, special etc.
    rareDragon = Column(String)
    specialDragon = Column(String)
    mysteriousDragon = Column(String)
    legendaryDragon = Column(String)
    distance = Column(Integer)
    discovered = Column(Integer) #  0 for undiscovered, 1 for discovered

    def connectToDB(self):
        engine = create_engine('sqlite:///httydrefugedatabase')
        session = sessionmaker()
        session.configure(bind=engine)
        Base.metadata.create_all(engine)
        return session

class Island:

    def __init__(self, DISPLAYSURF):
        self.id = 0
        self.name = 'testName'
        self.commondragon = 'TestDragon'
        self.rareDragon = 'TestDragon'
        self.specialDragon = 'TestDragon'
        self.mysteriousDragon = 'TestDragon'
        self.legendaryDragon = 'TestDragon'
        self.DISPLAYSURF = DISPLAYSURF
        self.width, self.height = DISPLAYSURF.get_size()
        self.initGame()  # sets up gem image list and board


    def newIsland(self, id):
        self.id = id
        s = IslandDB().connectToDB()
        session = s()
        islands = list(session.execute(session.query(IslandDB).filter(IslandDB.id == self.id)))
        self.name = islands[0][1]
        self.commondragon = islands[0][2]
        self.rareDragon = islands[0][3]
        self.specialDragon = islands[0][4]
        self.mysteriousDragon = islands[0][5]
        self.legendaryDragon = islands[0][6]
        self.makeDragon()
        self.lastMouseDownX = 0
        self.lastMouseDownY = 0
        self.firstSelectedGem = None
        self.clickedSpace = None
        self.randomizeBoard()

    def islandGame(self, events):
        self.drawBackground()
        self.drawDragon()
        self.handleEvent(events)  # handles mouse drags and clicks, sets some variables
        self.swapGems() # swaps gems adjacent to each other when clicked or dragged and animates it
        self.findMatchingGems()  # see if this was a matching move and removes matched gems, writes in gemsToRemove
        self.removeMatchingGems()  # removes the matching gems
        if not self.canMakeMove():  # looks if there are matching possibilities
            self.randomizeBoard()
        self.fillBoardAndAnimate(self.BOARD)  # fills the empty fields, bringing gems to the top if possible, and calls the function that draws the dropping gems
        self.drawBoard(self.BOARD) # draws everything on the board that is not moving

    def initGame(self):
        self.BOARDWIDTH = 10  # how many columns in the board
        self.BOARDHEIGHT = 8  # how many rows in the board
        self.GEMIMAGESIZE = 50  # width & height of each space in pixels

        # The amount of space to the sides of the board to the edge of the window
        self.XMARGIN = int((self.width - self.GEMIMAGESIZE * self.BOARDWIDTH) / 2)
        self.YMARGIN = int((self.height - self.GEMIMAGESIZE * self.BOARDHEIGHT) / 1.3)

        self.progress = 0  # progress at 0 represents beginning, 100 means finished (dropping gem animation)

        # constants for direction values
        self.UP = 'up'
        self.DOWN = 'down'
        self.LEFT = 'left'
        self.RIGHT = 'right'

        self.EMPTY_SPACE = -1
        self.ROWABOVEBOARD = 'row above board'

        self.MOVERATE = 10  # 1 to 100, larger num means faster animations TODO: config

        if float(config['difficulty']) >= 1:
            self.NUMGEMIMAGES = 7
        elif float(config['difficulty']) >= 0.7:
            self.NUMGEMIMAGES = 6
        else:
            self.NUMGEMIMAGES = 5

        self.GEMIMAGES = []
        for i in range(1, self.NUMGEMIMAGES + 1):
            gemImage = pygame.image.load(path.join(path.dirname(__file__), 'images', 'gems', 'gem%s.png' % i))
            if gemImage.get_size() != (self.GEMIMAGESIZE, self.GEMIMAGESIZE):
                gemImage = pygame.transform.smoothscale(gemImage, (self.GEMIMAGESIZE, self.GEMIMAGESIZE))
            self.GEMIMAGES.append(gemImage)

        self.BOARD = self.createNewBoard()

        self.gemsToRemove = []

    def createNewBoard(self):
        self.BOARDRECTS = []  # [ [rect, rect, ...],[rect, rect, ...], ... ]
        for x in range(self.BOARDWIDTH):
            self.BOARDRECTS.append([])
            for y in range(self.BOARDHEIGHT):
                r = pygame.Rect((self.XMARGIN + (x * self.GEMIMAGESIZE),
                                 self.BOARDHEIGHT - self.YMARGIN - (y * self.GEMIMAGESIZE),
                                 self.GEMIMAGESIZE,
                                 self.GEMIMAGESIZE))
                self.BOARDRECTS[x].append(r)
        BOARD = []
        for x in range(self.BOARDWIDTH):
            BOARD.append([self.EMPTY_SPACE] * self.BOARDHEIGHT)

        return BOARD

    def handleEvent(self, events):
        for event in events:
            if event != None:
                if event.type == MOUSEBUTTONUP:
                    if event.pos == (self.lastMouseDownX, self.lastMouseDownY): #  This event is a mouse click, not the end of a mouse drag.
                        self.clickedSpace = self.checkForGemClick(event.pos)
                    else: #  this is the end of a mouse drag
                        self.clickedSpace = self.checkForGemClick(event.pos)
                        self.firstSelectedGem = self.checkForGemClick((self.lastMouseDownX, self.lastMouseDownY))
                        if not self.firstSelectedGem or not self.clickedSpace: # if not part of a valid drag, deselect both
                            self.firstSelectedGem = None
                            self.clickedSpace = None
                elif event.type == MOUSEBUTTONDOWN:  # this is the start of a mouse click or mouse drag
                    self.lastMouseDownX, self.lastMouseDownY = event.pos

    def checkForGemClick(self, pos):
        # See if the mouse click was on the board
        for x in range(self.BOARDWIDTH):
            for y in range(self.BOARDHEIGHT):
                if self.BOARDRECTS[x][y].collidepoint(pos[0], pos[1]):
                    return {'x': x, 'y': y}
        return None  # Click was not on the board.

    def swapGems(self):
        if self.clickedSpace and not self.firstSelectedGem:
            # This was the first gem clicked on.
            self.firstSelectedGem = self.clickedSpace
        elif self.clickedSpace and self.firstSelectedGem:
            # Two gems have been clicked on and selected. Swap the gems.
            firstSwappingGem, secondSwappingGem = self.getSwappingGems()
            if firstSwappingGem == None and secondSwappingGem == None:
                # If both are None, then the gems were not adjacent
                self.firstSelectedGem = None # deselect the first gem

            else:
                # Show the swap animation on the screen.
                boardCopy = self.getBoardCopyMinusGems(self.BOARD, (firstSwappingGem, secondSwappingGem))
                self.animateMovingGems(boardCopy, [firstSwappingGem, secondSwappingGem])

                # Swap the gems in the board data structure.
                self.BOARD[firstSwappingGem['x']][firstSwappingGem['y']] = secondSwappingGem['imageNum']
                self.BOARD[secondSwappingGem['x']][secondSwappingGem['y']] = firstSwappingGem['imageNum']

    def getSwappingGems(self):
        # If the gems at the (X, Y) coordinates of the two gems are adjacent,
        # then their 'direction' keys are set to the appropriate direction
        # value to be swapped with each other.
        # Otherwise, (None, None) is returned.
        firstGem = {'imageNum': self.BOARD[self.firstSelectedGem['x']][self.firstSelectedGem['y']],
                    'x': self.firstSelectedGem['x'],
                    'y': self.firstSelectedGem['y']}
        secondGem = {'imageNum': self.BOARD[self.clickedSpace['x']][self.clickedSpace['y']],
                     'x': self.clickedSpace['x'],
                     'y': self.clickedSpace['y']}
        highlightedGem = None
        if firstGem['x'] == secondGem['x'] + 1 and firstGem['y'] == secondGem['y']:
            firstGem['direction'] = self.LEFT
            secondGem['direction'] = self.RIGHT
        elif firstGem['x'] == secondGem['x'] - 1 and firstGem['y'] == secondGem['y']:
            firstGem['direction'] = self.RIGHT
            secondGem['direction'] = self.LEFT
        elif firstGem['y'] == secondGem['y'] + 1 and firstGem['x'] == secondGem['x']:
            firstGem['direction'] = self.UP
            secondGem['direction'] = self.DOWN
        elif firstGem['y'] == secondGem['y'] - 1 and firstGem['x'] == secondGem['x']:
            firstGem['direction'] = self.DOWN
            secondGem['direction'] = self.UP
        else:
            # These gems are not adjacent and can't be swapped.
            return None, None
        return firstGem, secondGem

    def getGemAt(self, boardCopy, x, y):
        if x < 0 or y < 0 or x >= self.BOARDWIDTH or y >= self.BOARDHEIGHT:
            return None
        else:
            return boardCopy[x][y]

    def randomizeBoard(self):
        newBoard = self.createNewBoard()
        for x in range(self.BOARDWIDTH):
            for y in range(self.BOARDHEIGHT):
                newBoard[x][y] = self.EMPTY_SPACE
        self.BOARD = newBoard


    def getDropSlots(self, board):
        # Creates a "drop slot" for each column and fills the slot with a
        # number of gems that that column is lacking.
        boardCopy = copy.deepcopy(board)
        boardCopy = self.pullUpAllGems(boardCopy)

        dropSlots = []
        for i in range(self.BOARDWIDTH):
            dropSlots.append([])

        # count the number of empty spaces in each column on the board
        for x in range(self.BOARDWIDTH):
            for y in range(self.BOARDHEIGHT - 1, -1, -1):  # start from bottom, going up
                if boardCopy[x][y] == self.EMPTY_SPACE:
                    possibleGems = list(range(len(self.GEMIMAGES)))
                    for offsetX, offsetY in ((0, -1), (1, 0), (0, 1), (-1, 0)):
                        # Narrow down the possible gems we should put in the
                        # blank space so we don't end up putting an two of
                        # the same gems next to each other when they drop.
                        neighborGem = self.getGemAt(boardCopy, x + offsetX, y + offsetY)
                        if neighborGem != None and neighborGem in possibleGems:
                            possibleGems.remove(neighborGem)

                    newGem = random.choice(possibleGems)
                    boardCopy[x][y] = newGem
                    dropSlots[x].append(newGem)
        return dropSlots

    def pullUpAllGems(self, board):
        # pulls down gems on the board to the bottom to fill in any gaps
        for x in range(self.BOARDWIDTH):
            gemsInColumn = []
            for y in range(self.BOARDHEIGHT):
                if board[x][y] != self.EMPTY_SPACE:
                    gemsInColumn.append(board[x][y])
            # board[x] has an EMPTY_SPACE as often as there are missing gems
            board[x] = ([self.EMPTY_SPACE] * (self.BOARDHEIGHT - len(gemsInColumn))) + gemsInColumn
        return board

    def fillBoardAndAnimate(self, board):
        dropSlots = self.getDropSlots(board)
        while dropSlots != [[]] * self.BOARDWIDTH:
            # do the dropping animation as long as there are more gems to drop
            movingGems = self.getDroppingGems(board)
            for x in range(len(dropSlots)):
                if len(dropSlots[x]) != 0:
                    # cause the lowest gem in each slot to begin moving in the DOWN direction
                    movingGems.append({'imageNum': dropSlots[x][0], 'x': x, 'y': self.ROWABOVEBOARD, 'direction': self.DOWN})

            boardCopy = self.getBoardCopyMinusGems(board, movingGems)
            self.animateMovingGems(boardCopy, movingGems)
            self.moveGems(board, movingGems)

            # Make the next row of gems from the drop slots
            # the lowest by deleting the previous lowest gems.
            for x in range(len(dropSlots)):
                if len(dropSlots[x]) == 0:
                    continue
                self.BOARD[x][0] = dropSlots[x][0]
                del dropSlots[x][0]

    def getDroppingGems(self, board):
        # Find all the gems that have an empty space below them
        boardCopy = copy.deepcopy(board)
        droppingGems = []
        for x in range(self.BOARDWIDTH):
            for y in range(self.BOARDHEIGHT - 2, -1, -1):
                if boardCopy[x][y + 1] == self.EMPTY_SPACE and boardCopy[x][y] != self.EMPTY_SPACE:
                    # This space drops if not empty but the space below it is
                    droppingGems.append({'imageNum': boardCopy[x][y], 'x': x, 'y': y, 'direction': self.DOWN})
                    boardCopy[x][y] = self.EMPTY_SPACE
        return droppingGems

    def getBoardCopyMinusGems(self, board, gems):
        # Creates and returns a copy of the passed board data structure,
        # with the gems in the "gems" list removed from it.
        #
        # Gems is a list of dicts, with keys x, y, direction, imageNum

        boardCopy = copy.deepcopy(board)

        # Remove some of the gems from this board data structure copy.
        for gem in gems:
            if gem['y'] != self.ROWABOVEBOARD:
                boardCopy[gem['x']][gem['y']] = self.EMPTY_SPACE
        return boardCopy

    def animateMovingGems(self, board, gems):
        # pointsText is a dictionary with keys 'x', 'y', and 'points'

        if self.progress < 100:  # animation loop
            self.drawBoard(board)
            for gem in gems:  # Draw each gem.
                self.drawMovingGem(gem, self.progress)
            self.progress += self.MOVERATE  # progress the animation a little bit more for the next frame

        if self.progress == 100:
            self.progress = 0

    def moveGems(self, board, movingGems):
        # movingGems is a list of dicts with keys x, y, direction, imageNum
        for gem in movingGems:
            if gem['y'] != self.ROWABOVEBOARD:
                board[gem['x']][gem['y']] = self.EMPTY_SPACE
                movex = 0
                movey = 0
                if gem['direction'] == self.LEFT:
                    movex = -1
                elif gem['direction'] == self.RIGHT:
                    movex = 1
                elif gem['direction'] == self.DOWN:
                    movey = 1
                elif gem['direction'] == self.UP:
                    movey = -1
                board[gem['x'] + movex][gem['y'] + movey] = gem['imageNum']
            else:
                # gem is located where new gems come from
                board[gem['x']][0] = gem['imageNum']  # move to first row

    def drawBoard(self, board):
        for x in range(self.BOARDWIDTH):
            for y in range(self.BOARDHEIGHT):
                pygame.draw.rect(self.DISPLAYSURF, (0, 0, 0), self.BOARDRECTS[x][y], 2)
                gemToDraw = board[x][y]
                if gemToDraw != self.EMPTY_SPACE:
                    self.DISPLAYSURF.blit(self.GEMIMAGES[gemToDraw], self.BOARDRECTS[x][y])

    def drawMovingGem(self, gem, progress):
        # Draw a gem sliding in the direction that its 'direction' key
        # indicates. The progress parameter is a number from 0 (just
        # starting) to 100 (slide complete).
        movex = 0
        movey = 0
        progress *= 0.01

        if gem['direction'] == self.UP:
            movey = -int(progress * self.GEMIMAGESIZE)
        elif gem['direction'] == self.DOWN:
            movey = int(progress * self.GEMIMAGESIZE)
        elif gem['direction'] == self.RIGHT:
            movex = int(progress * self.GEMIMAGESIZE)
        elif gem['direction'] == self.LEFT:
            movex = -int(progress * self.GEMIMAGESIZE)

        basex = gem['x']
        basey = gem['y']
        if basey == self.ROWABOVEBOARD:
            basey = -1

        pixelx = self.XMARGIN + (basex * self.GEMIMAGESIZE)
        pixely = self.YMARGIN + (basey * self.GEMIMAGESIZE)
        r = pygame.Rect((pixelx + movex, pixely + movey, self.GEMIMAGESIZE, self.GEMIMAGESIZE))  # TODO: fix pixely if necessary
        self.DISPLAYSURF.blit(self.GEMIMAGES[gem['imageNum']], r)

    def drawBackground(self):
        background = pygame.image.load(path.join(path.dirname(__file__), 'images', "backgrounds", 'islands', '%s.jpg' % (self.id)))
        background = pygame.transform.smoothscale(background, (self.width, self.height))
        rect = background.get_rect()
        rect.center = (self.width / 2, self.height / 2)
        self.DISPLAYSURF.blit(background, rect)

    def makeDragon(self):
        randomNumber = random.randint(1, 101)
        if randomNumber < 70:
            self.dragon = self.commondragon
            self.rarity = 1
        elif randomNumber < 84:
            self.dragon = self.rareDragon
            self.rarity = 2
        elif randomNumber < 94:
            self.dragon = self.specialDragon
            self.rarity = 3
        elif randomNumber < 99:
            self.dragon = self.mysteriousDragon
            self.rarity = 4
        else:
            self.dragon = self.legendaryDragon
            self.rarity = 5

    def drawDragon(self):
        PATH = path.join(path.dirname(__file__), "images", "dragons")

        if self.dragon == "Deadly Nadder":
            PATH = path.join(PATH, "Deadly_Nadder")

        if self.dragon == "Monstrous Nightmare":
            PATH = path.join(PATH, "Monstrous_Nightmare")

        if self.dragon == "Night Fury":
            PATH = path.join(PATH, "Night_Fury")

        if self.dragon == "Gronckle":
            PATH = path.join(PATH, "Gronckle")

        if self.dragon == "Hideous Zippleback":
            PATH = path.join(PATH, "Hideous_Zippleback")

        if self.dragon == "Razorwhip":
            PATH = path.join(PATH, "Razorwhip")

        if self.dragon == "Rumblehorn":
            PATH = path.join(PATH, "Rumblehorn")

        if self.dragon == "Fireworm Queen":
            PATH = path.join(PATH, "Fireworm_Queen")

        # common
        if self.rarity == 1:
            PATH = path.join(PATH, "1.png")
        # rare
        if self.rarity == 2:
            PATH = path.join(PATH, "2.png")
        # special
        if self.rarity == 3:
            PATH = path.join(PATH, "3.png")
        # mysterious
        if self.rarity == 4:
            PATH = path.join(PATH, "4.png")
        # legendary
        if self.rarity == 5:
            PATH = path.join(PATH, "5.png")

        dragonImage = pygame.image.load(PATH)
        dragonImage = pygame.transform.smoothscale(dragonImage, (int(self.width/3), int(self.height/3)))
        dragonImageRect = dragonImage.get_rect()
        dragonImageRect.center = (self.width/2, self.height/2)
        dragonImageRect.top = 0
        self.DISPLAYSURF.blit(dragonImage, dragonImageRect)


    def findMatchingGems(self):
        gemsToRemove = []  # a list of lists of gems in matching triplets that should be removed
        boardCopy = copy.deepcopy(self.BOARD)

        # loop through each space, checking for 3 adjacent identical gems
        for x in range(self.BOARDWIDTH):
            for y in range(self.BOARDHEIGHT):
                # look for horizontal matches
                if self.getGemAt(boardCopy, x, y) == self.getGemAt(boardCopy, x + 1, y) == self.getGemAt(boardCopy, x + 2, y) and self.getGemAt(boardCopy, x, y) != self.EMPTY_SPACE:
                    targetGem = boardCopy[x][y]
                    offset = 0
                    removeSet = []
                    while self.getGemAt(boardCopy, x + offset, y) == targetGem:
                        # keep checking if there's more than 3 gems in a row
                        removeSet.append((x + offset, y))
                        boardCopy[x + offset][y] = self.EMPTY_SPACE
                        offset += 1
                    gemsToRemove.append(removeSet)

                # look for vertical matches
                if self.getGemAt(boardCopy, x, y) == self.getGemAt(boardCopy, x, y + 1) == self.getGemAt(boardCopy, x, y + 2) and self.getGemAt(boardCopy, x, y) != self.EMPTY_SPACE:
                    targetGem = boardCopy[x][y]
                    offset = 0
                    removeSet = []
                    while self.getGemAt(boardCopy, x, y + offset) == targetGem:
                        # keep checking, in case there's more than 3 gems in a row
                        removeSet.append((x, y + offset))
                        boardCopy[x][y + offset] = self.EMPTY_SPACE
                        offset += 1
                    gemsToRemove.append(removeSet)

        return gemsToRemove

    def removeMatchingGems(self):
        matchedGems = self.findMatchingGems()
        while matchedGems != []:
            # Remove matched gems, then pull down the board.

            for gemSet in matchedGems:
                for gem in gemSet:
                    self.BOARD[gem[0]][gem[1]] = self.EMPTY_SPACE
            # Drop the new gems.
            self.fillBoardAndAnimate(self.BOARD)

            # Check if there are any new matches.
            matchedGems = self.findMatchingGems()

    def canMakeMove(self):
        # Return True if the board is in a state where a matching
        # move can be made on it. Otherwise return False.

        # The patterns in oneOffPatterns represent gems that are configured
        # in a way where it only takes one move to make a triplet.
        oneOffPatterns = (((0, 1), (1, 0), (2, 0)),
                          ((0, 1), (1, 1), (2, 0)),
                          ((0, 0), (1, 1), (2, 0)),
                          ((0, 1), (1, 0), (2, 1)),
                          ((0, 0), (1, 0), (2, 1)),
                          ((0, 0), (1, 1), (2, 1)),
                          ((0, 0), (0, 2), (0, 3)),
                          ((0, 0), (0, 1), (0, 3)))

        # The x and y variables iterate over each space on the board.
        # If we use + to represent the currently iterated space on the
        # board, then this pattern: ((0,1), (1,0), (2,0))refers to identical
        # gems being set up like this:
        #
        #     +A
        #     B
        #     C
        #
        # That is, gem A is offset from the + by (0,1), gem B is offset
        # by (1,0), and gem C is offset by (2,0). In this case, gem A can
        # be swapped to the left to form a vertical three-in-a-row triplet.
        #
        # There are eight possible ways for the gems to be one move
        # away from forming a triple, hence oneOffPattern has 8 patterns.

        for x in range(self.BOARDWIDTH):
            for y in range(self.BOARDHEIGHT):
                for pat in oneOffPatterns:
                    # check each possible pattern of "match in next move" to
                    # see if a possible move can be made.
                    if (self.getGemAt(self.BOARD, x + pat[0][0], y + pat[0][1]) == \
                        self.getGemAt(self.BOARD, x + pat[1][0], y + pat[1][1]) == \
                        self.getGemAt(self.BOARD, x + pat[2][0], y + pat[2][1]) != None) or \
                            (self.getGemAt(self.BOARD, x + pat[0][1], y + pat[0][0]) == \
                             self.getGemAt(self.BOARD, x + pat[1][1], y + pat[1][0]) == \
                             self.getGemAt(self.BOARD, x + pat[2][1], y + pat[2][0]) != None):
                        return True  # return True the first time you find a pattern
        return False




If you need to see the main loop, here it is:

import pygame, sys
from pygame.locals import *
import Home, Menu, Dragon, Expedition, Island
import configparser

pygame.init()

config = configparser.ConfigParser()
config.read('config.ini')  #filename
config = config['DEFAULT']  #section

FPS = int(config['FPS'])
fpsClock = pygame.time.Clock()

DISPLAYSURF = pygame.display.set_mode((int(config['screen_width']), int(config['screen_height'])), 0, 32)  # Display Surface
pygame.display.set_caption('HTTYD: Refuge')

WHITE = (255, 255, 255)  # for filling DISPLAYSURF before drawing on it

PLACE = 'home' #variable to identify which part of the game we are playing right now

[...]

island = Island.Island(DISPLAYSURF)
EVENTS = []  # is set to the last events, so that game loops can also take place when the player doesn't do anything but still get the current events
islandListPage = 1
islandId = 0
islandDB = Island.IslandDB()

while True:
    DISPLAYSURF.fill(WHITE)

[...]

    if PLACE == 'newIsland':
        island.newIsland(islandId)
        PLACE = 'island'

    if PLACE == 'island':
        island.islandGame(EVENTS)

    EVENTS = []

    for event in pygame.event.get():
        EVENTS.append(event)
        if event.type == MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()

[...]

            if PLACE == 'chooseIsland':
                islandListPageClick, islandPageIdClick = expedition.clickButton(pos, islandListPage)
                if islandListPageClick != -1:
                    dragonListPage = islandListPageClick
                if islandPageIdClick != -1:
                    PLACE = 'expedition'
                    islandId = islandPageIdClick # to remember which island we travel to

                    # now we're setting the distance we travel to reach the island, stored in the DB
                    islandDBSession = islandDB.connectToDB()
                    islandSession = islandDBSession()
                    islands = list(islandSession.execute(islandSession.query(Island.IslandDB).filter(Island.IslandDB.id == islandId)))
                    islandDistance = islands[0][7]
                    expedition.setDistance(islandDistance)

        if event.type == QUIT or PLACE == 'quit':
            pygame.quit()
            sys.exit()



    pygame.display.update()
    fpsClock.tick(FPS)




I've tried to cut everything out so you don't need to read through the unnecessary stuff. I hope someone can spot it.
Thanks in advance!

Is This A Good Question/Topic? 0
  • +

Page 1 of 1