def play_games(self): """Give game options to play, and fill up the happiness level by tamagotchi's happiness rate.""" t = self._tamagotchi self.update_status() if self.is_tamagotchi_alive(): # Game Controller prompts user with a mini game list. game_controller = GameController() game = game_controller.give_game_option() # Print out the selected game's output, and adjust happiness level based on its level of fun. print(f"[{t.name}] {game.output}") increment = t.status.increase_happiness(game.level_of_fun / t.adjust_rate.happiness) print(f">> Happiness meter increased by {round(increment, 0)}!\n{t.status}")
def main(): firstGame = Game() secondGame = Game() thirdGame = Game() fourthGame = Game() #create players print("Creating Players") playerOne = Player(playerOneVal, strategy='random') playerTwo = Player(playerTwoVal, strategy='random') playerThree = Player(playerOneVal, strategy='random') playerFour = Player(playerTwoVal, strategy='random') #get training data print("Creating Training Data") gameControllerNN = GameController(firstGame, playerOne, playerTwo) gameControllerNN.simulateManyGames(14500) gameControllerRNN = GameController(secondGame, playerThree, playerFour) gameControllerRNN.simulateManyGames(13000) NNmodel = ConnectFourModelNN(42, 3, 50, 100) NNmodel.train(gameControllerNN.getTrainingHistory()) RNNmodel = ConnectFourModelRNN(42, 3, 50, 100) RNNmodel.train(gameControllerRNN.getTrainingHistory()) #Create the Deep Q-Learning Agents print("Creating Agents") playerOneNeural = Player(playerOneVal, strategy='model', model = NNmodel,predicting = True) playerTwoRNN = Player(playerTwoVal, strategy='model', model = RNNmodel, predicting = True) #Play the game gameControllerFinal = GameController(thirdGame,playerOneNeural,playerTwoRNN) print("Playing 500 Games: Deep Q-Learrning with MLP as first player and Deep Q-Learning with RNN as second player") gameControllerFinal.simulateManyGames(500) gameControllerFinal = GameController(fourthGame, playerTwoRNN, playerOneNeural) print("Playing 500 Games: Deep Q-Learrning with RNN as first player and Deep Q-Learning with MLP as second player") gameControllerFinal.simulateManyGames(500)
class GameObject(pygame.sprite.Sprite): #reference to our game info singleton game = GameController() def __init__(this, name, image, posX, posY, sizeX, sizeY): this.__name = name this.rect = pygame.Rect(posX, posY, sizeX, sizeY) super().__init__() this.image = image.convert_alpha() #------------------------------------------------------------------------------# # Accessors # #------------------------------------------------------------------------------# def getName(this): return this.__name def getRect(this): return this.rect def getImage(this): return this.image #------------------------------------------------------------------------------# # Mutators # #------------------------------------------------------------------------------# def setName(this, text): this.__name = text def setRect(this, obj): this.rect = obj def setImage(this, obj): this.image = obj #------------------------------------------------------------------------------# # # # Class Methods # # # #------------------------------------------------------------------------------# #shift an object a certain number of x and y coordinates specified by the moveX and moveY arguments def move(this, moveX, moveY): this.getRect().move_ip(moveX, moveY) def shift(this, moveX, moveY): this.getRect().move_ip(moveX, moveY) def draw(this, screen): screen.blit(this.getImage(), this.getRect()) def checkGrounded(this): groundChecker = this.getRect().move(0, 1) groundChecker.inflate_ip(-1, 0) for ground in this.game.getTerrainSprites(): if groundChecker.colliderect( ground.getRect()) and ground.density > 0: return True return False
class __impl: """This implementation hides the singleton interface\ in an inner class and creates exactly one instance of\ the inner class. The outer class is a handle to the inner\ class and delegates any requests to it. While the id() of\ the handle objects changes, the id() of the inner class which\ implements the singleton behaviour is constant.""" #reference to our game info singleton game = GameController() #Nothing is in the initlizer, may add more at some point def __init__(this): pass #------------------------------------------------------------------------------# # # # Class Attributes # # # #------------------------------------------------------------------------------# #Game Camera Variable __moveX = 0 __moveY = 0 __offsetX = 0 __offsetY = 0 __scrollSpeed = game.getBlockScale( ) #how fast the camera scrolls if the player is not pushing it __blockEdgeX = 20 # how far the player needs to be to the edge of the screen before the camera moves __blockEdgeY = 5 # how far the player needs to be to the edge of the screen before the camera moves __scrollThreshold = 2 #how many blocks the player needs to be in so the camera scrolls smoothly #------------------------------------------------------------------------------# # Accessors # #------------------------------------------------------------------------------# def getMoveX(this): return this.__moveX def getMoveY(this): return this.__moveY def getOffsetX(this): return this.__offsetX def getOffsetY(this): return this.__offsetY def getScrollSpeed(this): return this.__scrollSpeed def getBlockEdgeX(this): return this.__blockEdgeX def getBlockEdgeY(this): return this.__blockEdgeY def getScrollThreshold(this): return this.__scrollThreshold #------------------------------------------------------------------------------# # Mutators # #------------------------------------------------------------------------------# def setMoveX(this, num): this.__moveX = num def setMoveY(this, num): this.__moveY = num def setOffsetX(this, num): this.__offsetX = num def setOffsetY(this, num): this.__offsetY = num def setScrollSpeed(this, num): this.__scrollSpeed = num def setBlockEdgeX(this, num): this.__blockEdgeX = num def setScrollThreshold(this, num): this.__scrollThreshold = num #------------------------------------------------------------------------------# # # # Class Methods # # # #------------------------------------------------------------------------------# def checkMove(this): #setup player variable to reduce code bloat player = this.game.getPlayer() block = this.game.getBlockScale() pixelsX = this.game.getResolution()[0] pixelsY = this.game.getResolution()[1] #If the player is facing the right side of the screen if player.isFacing == "right": #the player goes past the camera's distance flag if player.getRect().right + this.getOffsetX() > \ (((pixelsX / block) - this.getBlockEdgeX())\ * block) + this.getOffsetX(): #If the player is traveling faster than the camera scrolls normally if player.speedX * this.game.deltaTime > this.getScrollSpeed( ): #tell the camera to move as fast as the player this.setMoveX(player.speedX * this.game.deltaTime) #if the player is not moving as fast as the camera scrolls normally elif player.speedX * this.game.deltaTime <= this.getScrollSpeed( ): #the player is within a set number of blocks of the movement barrier... if player.getRect().right + this.getOffsetX() < \ (((pixelsX / block) \ - (this.getBlockEdgeX() - this.getScrollThreshold())) \ * block) + this.getOffsetX(): #tell the camera to move as fast as the player this.setMoveX(player.speedX * this.game.deltaTime) else: #tell the camera to move as fast as it nomrally scrolls this.setMoveX(this.getScrollSpeed()) else: this.setMoveX(0) #If the player is facing the left side of the screen elif player.isFacing == "left": #the player goes past the camera's distance flag if player.getRect().left + this.getOffsetX() < \ (this.getBlockEdgeX() * block) + this.getOffsetX(): #If the player is traveling faster than the camera scrolls normally if player.speedX * this.game.deltaTime < -this.getScrollSpeed( ): #tell the camera to move as fast as the player this.setMoveX(player.speedX * this.game.deltaTime) #if the player is not moving as fast as the camera scrolls normally elif player.speedX * this.game.deltaTime >= -this.getScrollSpeed( ): #the player is within a set number of blocks of the movement barrier... if player.getRect().left + this.getOffsetX() > \ ((this.getBlockEdgeX() - this.getScrollThreshold()) \ * block) + this.getOffsetX(): #tell the camera to move as fast as the player this.setMoveX(player.speedX * this.game.deltaTime) else: #tell the camera to move as fast as it nomrally scrolls this.setMoveX(-this.getScrollSpeed()) else: this.setMoveX(0) #vertical movement #the player goes above the camera's distance flag if player.getRect().top + this.getOffsetY() > \ (((pixelsY / block) - this.getBlockEdgeY()) * block) + this.getOffsetY(): #If the player is traveling faster than the camera scrolls normally if player.speedY * this.game.deltaTime > this.getScrollSpeed(): #tell the camera to move as fast as the player this.setMoveY(player.speedY * this.game.deltaTime) #if the player is not moving as fast as the camera scrolls normally elif player.speedY * this.game.deltaTime <= this.getScrollSpeed( ): #the player is within a set number of blocks of the movement barrier... if player.getRect().top + this.getOffsetY() < \ (((pixelsY / block) \ - (this.getBlockEdgeY() - this.getScrollThreshold())) \ * block) + this.getOffsetY(): #tell the camera to move as fast as the player this.setMoveY(player.speedX * this.game.deltaTime) else: #tell the camera to move as fast as it nomrally scrolls this.setMoveY(this.getScrollSpeed()) #the player goes above the camera's distance flag elif player.getRect().bottom + this.getOffsetY() < \ (this.getBlockEdgeY() * block) + this.getOffsetY(): #If the player is traveling faster than the camera scrolls normally if player.speedY * this.game.deltaTime < -this.getScrollSpeed( ): #tell the camera to move as fast as the player this.setMoveY(player.speedY * this.game.deltaTime) #if the player is not moving as fast as the camera scrolls normally elif player.speedY * this.game.deltaTime >= -this.getScrollSpeed( ): #the player is within a set number of blocks of the movement barrier... if player.getRect().bottom + this.getOffsetX() > \ ((this.getBlockEdgeY() - this.getScrollThreshold()) \ * block) + this.getOffsetY(): #tell the camera to move as fast as the player this.setMoveY(player.speedY * this.game.deltaTime) else: #tell the camera to move as fast as it nomrally scrolls this.setMoveY(-this.getScrollSpeed()) else: this.setMoveY(0) def update(this, sObject): """ The camera is an illusion, you think that the camera is shifting to the right... in reality all of the on screen objects are moving to the left""" #if we are refering to the player if sObject == this.game.getPlayer(): #if we are moving the camera on the X axis if not this.getMoveX() == 0: this.game.getPlayer().shift(-this.getMoveX(), 0) this.setOffsetX(-this.getMoveX() + this.getOffsetX()) #set camera X move to 0 after all objects have been moved this.setMoveX(0) #if we are moving the camera on the Y axis if not this.getMoveY() == 0: this.game.getPlayer().shift(0, -this.getMoveY()) this.setOffsetY(-this.getMoveY() + this.getOffsetY()) #set camera Y move to 0 after all objects have been moved this.setMoveY(0) #if we are refering to a single Rect if isinstance(sObject, pygame.Rect): #if we are moving the camera on the X axis if not this.getMoveX() == 0: sObject.move_ip(-this.getMoveX(), 0) #if we are moving the camera on the Y axis if not this.getMoveY() == 0: sObject.move_ip(0, -this.getMoveY()) #if we are refering to a dictonary if isinstance(sObject, dict): block = this.game.getBlockScale() loadRect = pygame.Rect((0, 0), (this.game.getResolution())) #expand the rect to account for the loading buffer loadRect.inflate_ip(block * this.game.loadingBuffer,\ block * this.game.loadingBuffer) #loop through each sprite in the sprite buffer for key, value in sObject.items(): if not loadRect.contains(value.getRect()): #if we are moving the camera on the X axis if not this.getMoveX() == 0: value.shift(-this.getMoveX(), 0) #if we are moving the camera on the Y axis if not this.getMoveY() == 0: value.shift(0, -this.getMoveY()) #if we are refering to a sprite group if isinstance(sObject, pygame.sprite.Group): #loop through each sprite in the sprite group for sprite in sObject: #if the sprite is not an NPC if not isinstance(sprite, NPC): #if we are moving the camera on the X axis if not this.getMoveX() == 0: sprite.shift(-this.getMoveX(), 0) #if we are moving the camera on the Y axis if not this.getMoveY() == 0: sprite.shift(0, -this.getMoveY()) #if the sprite is an NPC if isinstance(sprite, NPC): #if we are moving the camera on the X axis if not this.getMoveX() == 0: sprite.shift(-this.getMoveX(), 0) sprite.AIDesiredLocation.move_ip( -this.getMoveX(), 0) sprite.AILastSpotted.move_ip(-this.getMoveX(), 0) #if we are debugging the game if this.game.debugMode: if not sprite.testRect == None: sprite.testRect.move_ip( -this.getMoveX(), 0) #if we are moving the camera on the Y axis if not this.getMoveY() == 0: sprite.shift(0, -this.getMoveY()) sprite.AIDesiredLocation.move_ip( 0, -this.getMoveY()) sprite.AILastSpotted.move_ip(0, -this.getMoveY()) #if we are debugging the game if this.game.debugMode: if not sprite.testRect == None: sprite.testRect.move_ip( 0, -this.getMoveY()) #resets the camera's move and offset positions #mainly used when going back to main menu def reset(this): this.setMoveX(0) this.setMoveY(0) this.setOffsetX(0) this.setOffsetY(0)
from game import Game from player import Player from gameController import GameController if __name__ == "__main__": # simulates an arbitrary number of games between a random player and a player using our model game = Game() redPlayer = Player(1, strategy='random') yellowPlayer = Player(2, strategy='model') gameController = GameController(game, redPlayer, yellowPlayer) print("Playing with one random player and one neural player") gameController.playManyGames(100)
class __impl: """This implementation hides the singleton interface\ in an inner class and creates exactly one instance of\ the inner class. The outer class is a handle to the inner\ class and delegates any requests to it. While the id() of\ the handle objects changes, the id() of the inner class which\ implements the singleton behaviour is constant.""" #------------------------------------------------------------------------------# # # # Class Attributes # # # #------------------------------------------------------------------------------# #reference to our game singletons __game = GameController() __camera = Camera() __hud = HUD() #reference to game timers timers = {} #------------------------------------------------------------------------------# # Accessors # #------------------------------------------------------------------------------# #get the game controller instance def getGame(this): return this.__game #get the camera instance def getCamera(this): return this.__camera #get the hud instance def getHud(this): return this.__hud #------------------------------------------------------------------------------# # Mutators # #------------------------------------------------------------------------------# #no mutators in here #------------------------------------------------------------------------------# # # # Class Methods # # # #------------------------------------------------------------------------------# #------------------------------------------------------------------------------# # Initilization # #------------------------------------------------------------------------------# #Initlize our single instance def __init__(this): #Ninja Game constructor methods this.initGame() this.runGame() #loads any pygame functions or objects before the user gets a chance to act def initGame(this): #initilize pygame's sound component #frequency, size, channels, buffersize pygame.mixer.pre_init(44100, 16, 2, 4096) #boot up pygame and print boot info message = pygame.init() print("Successes, Failures\n", message) #set the resolution of the game display this.getGame().setDisplay( pygame.display.set_mode(this.getGame().getResolution())) #set the name of the game pygame.display.set_caption(this.getGame().getGameName()) this.getGame().setTimer(this, "quitTimer", 10) this.getGame().setTimer(this, "spaceTimer", 5) #------------------------------------------------------------------------------# # Game Processes # #------------------------------------------------------------------------------# def runGame(this): #the game loop to keep the game running while this.getGame().getGameRunning(): #If we are in the menu if this.getGame().getAtMainMenu(): this.runMainMenu() #If we are in the options menu elif this.getGame().getAtOptionsMenu(): this.runOptionsMenu() #If we are in the game... elif this.getGame().getAtGame(): this.startGameplay() #if we manage to break out of the loop without quitting... #automatically call the quit method this.quitGame() #this is where the actual game gets played def startGameplay(this): pygame.mixer.music.load('sounds/music/level.wav') pygame.mixer.music.play(-1) #load the map and all of the objects this.loadMap() this.getHud().initGameHUD() #reset the game over flag so this does not repeat this.getGame().setGameOver(False) this.getGame().setVictory(False) this.getGame().setGameOverPlayed(False) #------------------ Game Loop Begin ------------------- #setup the event timer so that the game does not freeze by itself #set the event ID to be Uservent + 1 (25) timer_event = pygame.USEREVENT + 1 #set up the timer event to occur every set of miliseconds determined by the second argument pygame.time.set_timer(timer_event, 1) #while we are considered in the game while (this.getGame().getAtGame()): #------------ Event Processes ------------ #check to see if the player has a game over and if has been played yet if this.getGame().getGameOver()\ and not this.getGame().getGameOverPlayed(): #use the game over method if this is the case this.gameOver() #checks to see if the player is trying to use input and assigns the action #takes the pygame event argument that was created from the for loop command = this.processInput() #as long as the game isnt over... #player selects the new action and the player procces it if not this.getGame().getGameOver(): this.getGame().getPlayer().recieveCommand(command) else: this.getGame().getPlayer().recieveCommand("idle") #AI selects the new action and the AI processes it this.checkAIStates(this.getGame().getNPCSprites()) #check to see if all characters are in the middle of an action #finishes the action if the chracters are in the middle of one this.checkStates(this.getGame().getNPCSprites()) this.checkStates(this.getGame().getPlayer()) #add forces (including gravity) to all object lists, then the player this.addForces(this.getGame().getTerrainSprites()) this.addForces(this.getGame().getItemSprites()) this.addForces(this.getGame().getNPCSprites()) this.addForces(this.getGame().getPlayer()) #check to see if any triggers have been activated this.checkTriggers() #---------- Camera Update ---------------- #check to see if the camera needs to move this.getCamera().checkMove() #update the position of all sprites according to how the camera is shifting this.getCamera().update(this.getGame().getTerrainSprites()) this.getCamera().update(this.getGame().getItemSprites()) this.getCamera().update(this.getGame().getNPCSprites()) this.getCamera().update(this.getGame().getTriggerSprites()) this.getCamera().update(this.getHud().getMovingHUDSprites()) """ #update the position of all sprite buffers this.getCamera().update(this.getGame().terrainSpriteBuffer) this.getCamera().update(this.getGame().itemSpriteBuffer) this.getCamera().update(this.getGame().NPCSpriteBuffer) this.getCamera().update(this.getGame().triggerSpriteBuffer) """ this.getCamera().update(this.getGame().getPlayer()) #----------- Graphics Rendering ----------- #run the render graphics method this.renderGraphics() #----------- Graphics Update Process -------------- #updates all sprites to their proper positions this.getGame().getTerrainSprites().update() this.getGame().getItemSprites().update() this.getGame().getNPCSprites().update() this.getGame().getTriggerSprites().update() this.getGame().getPlayer().update() this.getHud().getHUDSprites().update() #update the display outside of the update loop to reflect any changes pygame.display.update() """ buffering methods to be added in at a later date #---------- Appearing and Vanishing ---------- #a method that removes all sprites out of view this.vanish(this.getGame().getTerrainSprites()) this.vanish(this.getGame().getItemSprites()) this.vanish(this.getGame().getNPCSprites()) this.vanish(this.getGame().getTriggerSprites()) this.vanish(this.getHud().getMovingHUDSprites()) this.appear(this.getGame().terrainSpriteBuffer) this.appear(this.getGame().itemSpriteBuffer) this.appear(this.getGame().NPCSpriteBuffer) this.appear(this.getGame().triggerSpriteBuffer) """ #---------- Game Timers ---------------- this.getGame().countdownTimers(this) #---------- Update Process --------------- #update frames per second outside fo the update loop and set the delta time to the variable this.getGame().deltaTime = ( this.getGame().clock.tick(this.getGame().gameFPS) / 4) #ensure the pygame event system is still working properly pygame.event.pump() #-------------------- Game Loop End ------------------------ def loadMap(this): this.loadMapLayer('map1/', 'terrain.txt', "terrain") this.loadMapLayer('map1/', 'character.txt', "character") this.loadMapLayer('map1/', 'item.txt', "item") this.loadMapLayer('map1/', 'triggers.txt', "trigger") def loadMapLayer(this, mapPath, filename, objectType): path1 = 'maps/' filepath = path1 + mapPath + filename mapfile = open(filepath, 'r') idxX = 0 idxY = 1 #loop through the map file to find the dimmensions of the map with open(filepath, 'r') as mapfile: while True: block = mapfile.read(1) if not block: break elif block == '\n': idxY += 1 idxX = 0 else: idxX += 1 mapfile.close() #reset the coordinate index values idxX = 0 idxY = 0 #loop through the map file to turn the character array into an objects array with open(filepath, 'r') as mapfile: while True: block = mapfile.read(1) if not block: break elif block == '\n': idxY += 1 idxX = 0 else: this.loadObject(block, objectType, idxX, idxY) idxX += 1 mapfile.close() def loadObject(this, block, objectType, idxX, idxY): blockScale = this.getGame().getBlockScale() tBuffer = this.getGame().terrainSpriteBuffer iBuffer = this.getGame().itemSpriteBuffer nBuffer = this.getGame().NPCSpriteBuffer if objectType == "terrain": #match the character with the object and add it to the map array if block == 'b': tBuffer[str(idxX) + "," + str(idxY)] = Brick( (idxX * blockScale), (idxY * blockScale)) elif block == 'w': tBuffer[str(idxX) + "," + str(idxY)] = Wall( (idxX * blockScale), (idxY * blockScale)) elif block == 's': tBuffer[str(idxX) + "," + str(idxY)] = Sky( (idxX * blockScale), (idxY * blockScale)) elif block == 'd': tBuffer[str(idxX) + "," + str(idxY)] = Door( (idxX * blockScale), (idxY * blockScale)) elif block == 'g': tBuffer[str(idxX) + "," + str(idxY)] = Ground( (idxX * blockScale), (idxY * blockScale)) #if it is a character type object elif objectType == "character": #match the character with the object and add it to the map array if block == 'r': nBuffer[str(idxX) + "," + str(idxY)] = Gaurd( "Standing Gaurd", (idxX * blockScale), (idxY * blockScale)) elif block == 'p': Player((idxX * blockScale), (idxY * blockScale)) #if it is an item type object elif objectType == "item": pass #if it is a trigger type object elif objectType == "trigger": #match the character with the object and add it to the map array if block == 'm': tBuffer[str(idxX) + "," + str(idxY)] = Trigger( "howToMoveMessage", (idxX * blockScale), (idxY * blockScale), blockScale, (blockScale * 2)) elif block == 'a': tBuffer[str(idxX) + "," + str(idxY)] = Trigger( "howToAttackMessage", (idxX * blockScale), (idxY * blockScale), blockScale, (blockScale * 2)) elif block == 'e': tBuffer[str(idxX) + "," + str(idxY)] = Trigger( "enemyInfoMessage", (idxX * blockScale), (idxY * blockScale), blockScale, (blockScale * 2)) elif block == 'r': tBuffer[str(idxX) + "," + str(idxY)] = Trigger( "enemyBroadcastMessage", (idxX * blockScale), (idxY * blockScale), blockScale, (blockScale * 2)) elif block == 'v': tBuffer[str(idxX) + "," + str(idxY)] = Trigger( "victory", (idxX * blockScale), (idxY * blockScale), blockScale, (blockScale * 2)) elif block == 'c': tBuffer[str(idxX) + "," + str(idxY)] = Trigger( "clearMessages", (idxX * blockScale), (idxY * blockScale), blockScale, (blockScale * 2)) def renderGraphics(this): """ The way this works, is that it builds the display in layers based on what comes first and the last thing that gets drawn is the sprite/shape on the bottom of the graphics rendering code block """ #wipe the slate clean this.getGame().getDisplay().fill(this.getGame().getColor("black")) #add all sprites to the game display this.getGame().getTerrainSprites().draw( this.getGame().getDisplay()) this.getGame().getItemSprites().draw(this.getGame().getDisplay()) this.customDraw(this.getGame().getNPCSprites()) this.customDraw(this.getGame().getPlayer()) this.getHud().getHUDSprites().draw(this.getGame().getDisplay()) #function for using the custome draw function for a sprite group def customDraw(this, sObject): #if the object instance is a single sprite if isinstance(sObject, pygame.sprite.Sprite): #use the custom-made draw function sObject.draw(this.getGame().getDisplay()) #if the object instance is a sprite group if isinstance(sObject, pygame.sprite.Group): #loop through the sprite group for sprite in sObject: #use the custom-made draw function sprite.draw(this.getGame().getDisplay()) """ functions to be added in at a later date def vanish(this, spriteGroup): block = this.getGame().getBlockScale() vanishRect = pygame.Rect((0,0),(this.getGame().getResolution())) #expand the rect to account for the loading buffer vanishRect.inflate_ip(block * this.getGame().loadingBuffer,\ block * this.getGame().loadingBuffer) #loop through the sprite group for sprite in spriteGroup: #if the sprite is not within the load rect... if not vanishRect.contains(sprite.getRect()): #remove the sprite sprite.remove() def appear(this, spriteList): block = this.getGame().getBlockScale() vanishRect = pygame.Rect((0,0),(this.getGame().getResolution())) #expand the rect to account for the loading buffer loadRect = vanishRect.inflate(block * (this.getGame().loadingBuffer + 2),\ block * (this.getGame().loadingBuffer + 2)) #expand the vanishing buffer vanishRect.inflate_ip(block * (this.getGame().loadingBuffer + 2),\ block * (this.getGame().loadingBuffer)) #loop through each sprite in the sprite buffer for key, value in spriteList.items(): #if the sprite is not within the vanish rect #but is within the load rect.... if not vanishRect.contains(value.getRect())\ and loadRect.contains(value.getRect()): #ensure the item gets added to the correct list if isinstance(value, Block): this.getGame().getTerrainSprites().add(value) elif isinstance(value, Item): this.getGame().getItemSprites().add(value) elif isinstance(value, NPC): this.getGame().getNPCSprites().add(value) elif isinstance(value, Trigger): this.getGame().getTriggerSprites().add(value) """ def processInput(this): """Will go back and change jump to a MOD key to try to fix jumping issue""" #assign the reference to the game keys list keys = this.getGame().keys mods = pygame.key.get_mods() #keysPressed = this.getGame().noKeysPressed keysPressed = pygame.key.get_pressed() #reset all the keys that are pressed for idx in range(0, len(keys)): keys[idx] = False #if the keys that are pressed = the boolean tuple if keysPressed == this.getGame().wPressed: keys[0] = True elif keysPressed == this.getGame().sPressed: keys[1] = True elif keysPressed == this.getGame().aPressed: keys[2] = True elif keysPressed == this.getGame().dPressed: keys[3] = True elif keysPressed == this.getGame().upPressed: keys[4] = True elif keysPressed == this.getGame().downPressed: keys[5] = True elif keysPressed == this.getGame().leftPressed: keys[6] = True elif keysPressed == this.getGame().rightPressed: keys[7] = True elif keysPressed == this.getGame().spacePressed: keys[8] = True elif keysPressed == this.getGame().escPressed: keys[9] = True #if the mods are pressed = one number for a specific key if mods == this.getGame().rCtrlPressed: keys[10] = True #print(keysPressed) #print(keys) #print (mods) if keysPressed == this.getGame().noKeysPressed: return "idle" #return a command based on which keys are pressed if keys[8]: if this.getGame().checkTimer(this, "spaceTimer"): #ensure we dont press the button twice this.getGame().setTimer(this, "spaceTimer", 5) return "jump" elif keys[9]: if this.getGame().checkTimer(this, "quitTimer"): if not this.getGame().getAtMainMenu(): this.quitLevel() #ensure we dont press the button twice this.getGame().setTimer(this, "quitTimer", 10) else: return this.quitGame() elif keys[10]: return "attack" elif keys[0] or keys[4]: return "goUp" elif keys[1] or keys[5]: return "goDown" elif keys[2] or keys[6]: return "goLeft" elif keys[3] or keys[7]: return "goRight" #if no actions are being taken or no keys are being pressed... return idle return "idle" #function for using the check AI state function for a group of sprites def checkAIStates(this, sObject): #loop through the sprite group for sprite in sObject: #use the checkState function sprite.checkAIState() #function for using the check state function for a sprite or group def checkStates(this, sObject): #if the object instance is a single sprite if isinstance(sObject, pygame.sprite.Sprite): #use the checkState function sObject.checkState() #if the object instance is a sprite group if isinstance(sObject, pygame.sprite.Group): #loop through the sprite group for sprite in sObject: #use the checkState function sprite.checkState() #add gravity to an object array or just the player def addForces(this, sObject): #if the object instance is a single sprite if isinstance(sObject, pygame.sprite.Sprite): #add force to a single object this.addSingleForce(sObject) #if the object instance is a sprite group elif isinstance(sObject, pygame.sprite.Group): #loop through the sprite group for sprite in sObject: #add force to a single object this.addSingleForce(sprite) def addSingleForce(this, sObject): #if the object instance is a character or NPC sprite if isinstance(sObject, Character)\ or isinstance(sObject, NPC): #have gravity affect the object if they are in the air if sObject.mass > 0: sObject.addForce(0, (this.getGame().gravity / 2)) #implement speed loss over time if sObject.getState("isIdle"): if not sObject.speedX == 0: if sObject.speedX > 0: sObject.addForce(-this.getGame().speedLoss, 0) elif sObject.speedX < 0: sObject.addForce(this.getGame().speedLoss, 0) #if there is less than 1 unit of force if abs(sObject.speedX) < 1: #set the speed to 0 sObject.speedX = 0 # if the object is in the middle of moving left or right... if sObject.speedX > 0 or sObject.speedX < 0: #move the object and see if they collides with another object if not sObject.move( sObject.speedX * this.getGame().deltaTime, 0): if not sObject.getState("isJumping"): #if they collide, then set the x speed to 0 sObject.speedX = 0 #if the object is in the air if sObject.speedY > 0 or sObject.speedY < 0: #move the object and see if he collides with another object if not sObject.move( 0, (sObject.speedY * this.getGame().deltaTime)): #if they collides, set the y speed to 0 sObject.speedY = 0 #if the object is not a character sprite else: #if the object has mass if sObject.mass > 0: #make the object fall sObject.move(0, (this.getGame().deltaTime / 2) * this.getGame().gravity) def checkTriggers(this): #loop through each trigger for trigger in this.getGame().getTriggerSprites(): #check to see if the trigger is colliding with the player if this.getGame().getPlayer().getRect().colliderect( trigger.getRect()): #trigger the event trigger.event() #countdown the timers on the triggers Trigger.game.countdownTimers(Trigger) #a method to run if the player has a game over def gameOver(this): #if it is not a victorious game over if not this.getGame().getVictory(): pygame.mixer.music.load('sounds/music/gameOver.wav') pygame.mixer.music.play(-1) #remove any text box elements (if there is any) this.getHud().removeTextBox() #Create a text box with a message this.getHud().createBoxWithMessage( "*-----------------------------------------------*"\ +"| _____ ____ |"\ +"| / ___/__ ___ _ ___ / __ \_ _____ ____ |"\ +"| / (_ / _ `/ ` \/ -_) / /_/ / |/ / -_) __/ |"\ +"| \___/\_,_/_/_/_/\__/ \____/|___/\__/_/ |"\ +"| |"\ +"| |"\ +"| Press ESC key to go back to the main menu |"\ +"*-----------------------------------------------*",\ this.getHud().getTextBoxLocX(), this.getHud().getTextBoxLocY(),\ this.getHud().getTextBoxSizeX(), this.getHud().getTextBoxSizeY() + 2,\ False) #if it is a victorious game over elif this.getGame().getVictory(): pygame.mixer.music.load('sounds/music/victory.wav') pygame.mixer.music.play(-1) #remove any text box elements (if there is any) this.getHud().removeTextBox() #Create a text box with a message this.getHud().createBoxWithMessage(" _ ___ __ "\ +" | | / (_)____/ /_____ _______ __ "\ +" | | / / / ___/ __/ __ \/ ___/ / / / "\ +" | |/ / / /__/ /_/ /_/ / / / /_/ / "\ +" |___/_/\___/\__/\____/_/ \__, / "\ +" /____/ "\ +" "\ +" "\ +" Press ESC to return to the main menu ",\ 128,212,43,13, False) #reset the game over flag so this does not repeat this.getGame().setGameOverPlayed(True) #----------------------------- Main Menu Method ------------------------- def runMainMenu(this): pygame.mixer.music.load('sounds/music/title.wav') pygame.mixer.music.play(-1) #Create a main menu and while bool to store selection this.getHud().createBoxWithMessage("*-----------------------------------------------------*"\ +"| |"\ +"| |"\ +"| P r e s s S P A C E |"\ +"| |"\ +"| |"\ +"| |"\ +"| S T A R T G A M E |"\ +"| |"\ +"| |"\ +"| |"\ +"| |"\ +"| |"\ +"| |"\ +"*-----------------------------------------------------*",\ 8,8,58,18, False) this.getHud().createBoxWithMessage("*-----------------------------------------------------*"\ +"| |"\ +"| |"\ +"| |"\ +"| |"\ +"| |"\ +"| |"\ +"| Q U I T G A M E |"\ +"| |"\ +"| |"\ +"| |"\ +"| P r e s s E S C |"\ +"| |"\ +"| |"\ +"*-----------------------------------------------------*",\ 8,328,58,18, False) this.getHud().createBoxWithMessage(" ______ _ __ _ "\ +" / __/ / (_)__ ___ / / (_) "\ +" _\ \/ _ \/ / _ \/ _ \/ _ \/ / "\ +" /___/_//_/_/_//_/\___/_.__/_/ "\ +" "\ +" ___ _ "\ +" / _ | ___ ___ ___ ____ ___ (_)__ "\ +" / __ |(_-<(_-</ _ `(_-<(_-</ / _ \ "\ +" /_/ |_/___/___/\_,_/___/___/_/_//_/ ",\ 128,212,43,13, False) mainMenu = Menu("Main") mainMenu.addMenuItem("Start", this.getGame().imgBlank, 0, 0, 960, 320) #mainMenu.addMenuItem("Start", this.getGame().startImage, 0,0,480,320) #mainMenu.addMenuItem("Options", this.getGame().optionsImage, 480,0,480,320) mainMenu.addMenuItem("Quit", this.getGame().imgBlank, 0, 320, 960, 320) #------------------ Main Menu Loop Begin ------------------- #while we are considered in the main menu while (this.getGame().getAtMainMenu()): #for event in pygame.event.get(): #------------ Event Processes ------------ #a method that checks to see if a menu item get pressed #and assigns the process name to a process variable #process = mainMenu.selectOption(this.getGame().getDisplay(), event) process = this.processInput() this.runSelectedProcess(process) #----------- Graphics Rendering ----------- """ The way this works, is that it builds the display in layers based on what comes first and the last thing that gets drawn is the sprite/shape on the bottom of the graphics rendering code block """ #draw the HUD sprites on the screen this.getHud().getHUDSprites().update() #run the render graphics method this.renderGraphics() #update the screen pygame.display.update() #Run the display menu items method #mainMenu.displayMenuItems(this.getGame().getDisplay()) #------------ Game Timers ---------------- this.getGame().countdownTimers(this) #----------- Update Process -------------- #update the display outside of the event loop to reflect any changes pygame.display.update() #update frames per second outside fo the update loop and set the delta time to the variable this.getGame().deltaTime = ( this.getGame().clock.tick(this.getGame().gameFPS) / 4) #ensure the pygame event system is still working properly pygame.event.pump() #-------------------- Main Menu Loop End ------------------------ def runOptionsMenu(this): print("You are in the options menu, nothing here yet...") this.runSelectedProcess("Main Menu") def runSelectedProcess(this, process): if process == "jump": print("Starting Start Process...") this.getGame().setAtMainMenu(False) this.getGame().setAtOptionsMenu(False) this.getGame().setAtGame(True) elif process == "Main Menu": print("Returning to the Main Menu...") this.getGame().setAtMainMenu(True) this.getGame().setAtOptionsMenu(False) this.getGame().setAtGame(False) elif process == "Options": print("Starting Options Process...") this.getGame().setAtMainMenu(False) this.getGame().setAtOptionsMenu(True) this.getGame().setAtGame(False) elif process == "Quit": print("Continuing Quit Process...") this.getGame().setGameRunning(False) this.getGame().setAtMainMenu(False) this.getGame().setAtOptionsMenu(False) this.getGame().setAtGame(False) this.quitGame() elif process == "Invalid": print( "You have selected an invalid proceess... please try again" ) else: pass def quitLevel(this): #Clear out all sprite groups this.getGame().getTerrainSprites().empty() this.getGame().getItemSprites().empty() this.getGame().getNPCSprites().empty() this.getGame().getTriggerSprites().empty() this.getHud().getHUDSprites().empty() #Remove the player this.getGame().getPlayer().kill() #reset the camera this.getCamera().reset() #reset the game over flag this.getGame().setGameOver(False) #reset the victory flag this.getGame().setVictory(False) #remove the game over text Box this.getHud().removeTextBox() #run the main menu process this.runSelectedProcess("Main Menu") def quitGame(this): pygame.quit() quit()
from framerate import Framerate from screen import Screen from gameController import GameController width = 20#60 height = 20#35 screen = Screen(width,height) gameController = GameController(screen) framerate = Framerate() while True: screen.clear() gameController.update() framerate.render() screen.render()
from spaceShip import SpaceShip from gameController import GameController from setHighScore import setHighScore from random import randint ''' Run program with pgzrun main.py ''' WIDTH = 800 HEIGHT = 600 # Setup game = GameController(WIDTH, HEIGHT) gameOver = False haveTestedForHighScore = False # Global variable newHighScoreEvent = False # Global variable # Pygame Zero Functions - Game Loops def draw(): if not gameOver: inGameGraphics() else: gameOverScreen() def update(): if not gameOver: inGameUpdate()
from randomComputerPlayer import RandomComputerPlayer from ticTacToe import TicTacToe from humanPlayer import HumanPlayer from gameController import GameController if __name__ == "__main__": x_player = RandomComputerPlayer("X") o_player = HumanPlayer("O") tic = TicTacToe() GameController.play(tic, x_player, o_player, print_game=True)
import sys import copy from PyQt5.Qt import QApplication from gameController import GameController app = QApplication(sys.argv) gameControl = GameController() sys.exit(app.exec_())
from framerate import Framerate from screen import Screen from gameController import GameController width = 20 #60 height = 20 #35 screen = Screen(width, height) gameController = GameController(screen) framerate = Framerate() while True: screen.clear() gameController.update() framerate.render() screen.render()
class __impl: """This implementation hides the singleton interface\ in an inner class and creates exactly one instance of\ the inner class. The outer class is a handle to the inner\ class and delegates any requests to it. While the id() of\ the handle objects changes, the id() of the inner class which\ implements the singleton behaviour is constant.""" #reference to our game info singleton game = GameController() #Nothing is in the initlizer, may add more at some point def __init__(this): pass #------------------------------------------------------------------------------# # HUD Text Images # #------------------------------------------------------------------------------# #Capital Letter Images capA = pygame.image.load("sprites/hud/text/capA.png") capB = pygame.image.load("sprites/hud/text/capB.png") capC = pygame.image.load("sprites/hud/text/capC.png") capD = pygame.image.load("sprites/hud/text/capD.png") capE = pygame.image.load("sprites/hud/text/capE.png") capF = pygame.image.load("sprites/hud/text/capF.png") capG = pygame.image.load("sprites/hud/text/capG.png") capH = pygame.image.load("sprites/hud/text/capH.png") capI = pygame.image.load("sprites/hud/text/capI.png") capJ = pygame.image.load("sprites/hud/text/capJ.png") capK = pygame.image.load("sprites/hud/text/capK.png") capL = pygame.image.load("sprites/hud/text/capL.png") capM = pygame.image.load("sprites/hud/text/capM.png") capN = pygame.image.load("sprites/hud/text/capN.png") capO = pygame.image.load("sprites/hud/text/capO.png") capP = pygame.image.load("sprites/hud/text/capP.png") capQ = pygame.image.load("sprites/hud/text/capQ.png") capR = pygame.image.load("sprites/hud/text/capR.png") capS = pygame.image.load("sprites/hud/text/capS.png") capT = pygame.image.load("sprites/hud/text/capT.png") capU = pygame.image.load("sprites/hud/text/capU.png") capV = pygame.image.load("sprites/hud/text/capV.png") capW = pygame.image.load("sprites/hud/text/capW.png") capX = pygame.image.load("sprites/hud/text/capX.png") capY = pygame.image.load("sprites/hud/text/capY.png") capZ = pygame.image.load("sprites/hud/text/capZ.png") #Lowercase Letter Images lowA = pygame.image.load("sprites/hud/text/lowA.png") lowB = pygame.image.load("sprites/hud/text/lowB.png") lowC = pygame.image.load("sprites/hud/text/lowC.png") lowD = pygame.image.load("sprites/hud/text/lowD.png") lowE = pygame.image.load("sprites/hud/text/lowE.png") lowF = pygame.image.load("sprites/hud/text/lowF.png") lowG = pygame.image.load("sprites/hud/text/lowG.png") lowH = pygame.image.load("sprites/hud/text/lowH.png") lowI = pygame.image.load("sprites/hud/text/lowI.png") lowJ = pygame.image.load("sprites/hud/text/lowJ.png") lowK = pygame.image.load("sprites/hud/text/lowK.png") lowL = pygame.image.load("sprites/hud/text/lowL.png") lowM = pygame.image.load("sprites/hud/text/lowM.png") lowN = pygame.image.load("sprites/hud/text/lowN.png") lowO = pygame.image.load("sprites/hud/text/lowO.png") lowP = pygame.image.load("sprites/hud/text/lowP.png") lowQ = pygame.image.load("sprites/hud/text/lowQ.png") lowR = pygame.image.load("sprites/hud/text/lowR.png") lowS = pygame.image.load("sprites/hud/text/lowS.png") lowT = pygame.image.load("sprites/hud/text/lowT.png") lowU = pygame.image.load("sprites/hud/text/lowU.png") lowV = pygame.image.load("sprites/hud/text/lowV.png") lowW = pygame.image.load("sprites/hud/text/lowW.png") lowX = pygame.image.load("sprites/hud/text/lowX.png") lowY = pygame.image.load("sprites/hud/text/lowY.png") lowZ = pygame.image.load("sprites/hud/text/lowZ.png") #Number Images num0 = pygame.image.load("sprites/hud/text/num0.png") num1 = pygame.image.load("sprites/hud/text/num1.png") num2 = pygame.image.load("sprites/hud/text/num2.png") num3 = pygame.image.load("sprites/hud/text/num3.png") num4 = pygame.image.load("sprites/hud/text/num4.png") num5 = pygame.image.load("sprites/hud/text/num5.png") num6 = pygame.image.load("sprites/hud/text/num6.png") num7 = pygame.image.load("sprites/hud/text/num7.png") num8 = pygame.image.load("sprites/hud/text/num8.png") num9 = pygame.image.load("sprites/hud/text/num9.png") #Misc Text Images txtAnd = pygame.image.load("sprites/hud/text/txtAnd.png") txtArrowLeft = pygame.image.load("sprites/hud/text/txtArrowLeft.png") txtArrowRight = pygame.image.load("sprites/hud/text/txtArrowRight.png") txtAsterisk = pygame.image.load("sprites/hud/text/txtAsterisk.png") txtAt = pygame.image.load("sprites/hud/text/txtAt.png") txtBackSlash = pygame.image.load("sprites/hud/text/txtBackSlash.png") txtCarrot = pygame.image.load("sprites/hud/text/txtCarrot.png") txtColon = pygame.image.load("sprites/hud/text/txtColon.png") txtComma = pygame.image.load("sprites/hud/text/txtComma.png") txtCurlyLeft = pygame.image.load("sprites/hud/text/txtCurlyLeft.png") txtCurlyRight = pygame.image.load("sprites/hud/text/txtCurlyRight.png") txtDoubleQuote = pygame.image.load("sprites/hud/text/txtDblQuote.png") txtDollar = pygame.image.load("sprites/hud/text/txtDollar.png") txtEqual = pygame.image.load("sprites/hud/text/txtEqual.png") txtExclaim = pygame.image.load("sprites/hud/text/txtExclaim.png") txtForwardSlash = pygame.image.load("sprites/hud/text/txtFwdSlash.png") txtMinus = pygame.image.load("sprites/hud/text/txtMinus.png") txtPercent = pygame.image.load("sprites/hud/text/txtPercent.png") txtPeriod = pygame.image.load("sprites/hud/text/txtPeriod.png") txtPlus = pygame.image.load("sprites/hud/text/txtPlus.png") txtPound = pygame.image.load("sprites/hud/text/txtPound.png") txtQuestionMark = pygame.image.load("sprites/hud/text/txtQuesMark.png") txtRoundLeft = pygame.image.load("sprites/hud/text/txtRoundLeft.png") txtRoundRight = pygame.image.load("sprites/hud/text/txtRoundRight.png") txtSemiColon = pygame.image.load("sprites/hud/text/txtSemiColon.png") txtSingleQuote = pygame.image.load("sprites/hud/text/txtSnglQuote.png") txtSpace = pygame.image.load("sprites/hud/text/txtSpace.png") txtSpace2 = pygame.image.load("sprites/hud/text/txtSpace2.png") txtSquareLeft = pygame.image.load("sprites/hud/text/txtSquareLeft.png") txtSquareRight = pygame.image.load("sprites/hud/text/txtSquareRight.png") txtSquiggle = pygame.image.load("sprites/hud/text/txtSquiggle.png") txtStraightLine = pygame.image.load("sprites/hud/text/txtStraightLine.png") txtTilde = pygame.image.load("sprites/hud/text/txtTilde.png") txtUnderscore = pygame.image.load("sprites/hud/text/txtUnderscore.png") #Health Images heartFull = pygame.image.load("sprites/hud/health/hFull.png") heartEmpty = pygame.image.load("sprites/hud/health/hBack.png") #Character Image Dictionary __textImageDict ={ 'A' : capA, 'B' : capB, 'C' : capC, 'D' : capD, 'E' : capE, 'F' : capF, 'G' : capG, 'H' : capH, 'I' : capI, 'J' : capJ, 'K' : capK, 'L' : capL, 'M' : capM, 'N' : capN, 'O' : capO, 'P' : capP, 'Q' : capQ, 'R' : capR, 'S' : capS, 'T' : capT, 'U' : capU, 'V' : capV, 'W' : capW, 'X' : capX, 'Y' : capY, 'Z' : capZ, 'a' : lowA, 'b' : lowB, 'c' : lowC, 'd' : lowD, 'e' : lowE, 'f' : lowF, 'g' : lowG, 'h' : lowH, 'i' : lowI, 'j' : lowJ, 'k' : lowK, 'l' : lowL, 'm' : lowM, 'n' : lowN, 'o' : lowO, 'p' : lowP, 'q' : lowQ, 'r' : lowR, 's' : lowS, 't' : lowT, 'u' : lowU, 'v' : lowV, 'w' : lowW, 'x' : lowX, 'y' : lowY, 'z' : lowZ, '0' : num0, '1' : num1, '2' : num2, '3' : num3, '4' : num4, '5' : num5, '6' : num6, '7' : num7, '8' : num8, '9' : num9, '&' : txtAnd, '<' : txtArrowLeft, '>' : txtArrowRight, '*' : txtAsterisk, '@' : txtAt, '\\' : txtBackSlash, '^' : txtCarrot, ':' : txtColon, ',' : txtComma, '{' : txtCurlyLeft, '}' : txtCurlyRight, '"' : txtDoubleQuote, '$' : txtDollar, '=' : txtEqual, '!' : txtExclaim, '/' : txtForwardSlash, '-' : txtMinus, '%' : txtPercent, '.' : txtPeriod, '+' : txtPlus, '#' : txtPound, '?' : txtQuestionMark, '(' : txtRoundLeft, ')' : txtRoundRight, ';' : txtSemiColon, ' ' : txtSpace, '[' : txtSquareLeft, ']' : txtSquareRight, '~' : txtSquiggle, '|' : txtStraightLine, '`' : txtTilde, '_' : txtUnderscore } #------------------------------------------------------------------------------# # HUD Window Images # #------------------------------------------------------------------------------# #Text Window Images txtWinHorizontal = pygame.image.load("sprites/hud/window/horizontal.png") txtWinVertical = pygame.image.load("sprites/hud/window/vertical.png") txtWinTopLeft = pygame.image.load("sprites/hud/window/topLeft.png") txtWinTopRight = pygame.image.load("sprites/hud/window/topRight.png") txtWinBotLeft = pygame.image.load("sprites/hud/window/bottomLeft.png") txtWinBotRight = pygame.image.load("sprites/hud/window/bottomRight.png") txtWinSpaceGray = pygame.image.load("sprites/hud/window/spaceGray.png") txtWinSpaceBlack = pygame.image.load("sprites/hud/window/spaceBlack.png") #------------------------------------------------------------------------------# # # # Class Attributes # # # #------------------------------------------------------------------------------# #HUD Sprite Groups __HUDSprites = pygame.sprite.Group() #group of sprites in which all HUD elements appear __movingHUDSprites = pygame.sprite.Group() #group of sprites in which all moving hud elements appear __textBoxSprites = pygame.sprite.Group() #group of sprites in which all text box elements appear __heartSprites = pygame.sprite.Group() #group of sprites in which all Health elements appear #Default HUD Settings __textBoxBlock = int(game.getBlockScale() // 2) #the size of a text block __textBoxLocX = int(game.blockToPosX(2)) #the default location on the X axis of where a text box is placed __textBoxLocY = int(game.blockToPosY(1)) #the default location on the Y axis of where a text box is placed __textBoxSizeX = int(game.getScreenBlockLengthX() - 4) * 2 #the default width (in text blocks) of a text message block __textBoxSizeY = int(10) #the default length (in text blocks) of a text message block __textBoxMargin = int(2) #the default number of text blocks from the border of a text box in which messages may be written #------------------------------------------------------------------------------# # Accessors # #------------------------------------------------------------------------------# def getHUDSprites(this): return this.__HUDSprites def getMovingHUDSprites(this): return this.__movingHUDSprites def getTextBoxSprites(this): return this.__textBoxSprites def getHeartSprites(this): return this.__heartSprites def getTextBoxBlock(this): return this.__textBoxBlock def getTextBoxLocX(this): return this.__textBoxLocX def getTextBoxLocY(this): return this.__textBoxLocY def getTextBoxSizeX(this): return this.__textBoxSizeX def getTextBoxSizeY(this): return this.__textBoxSizeY def getTextBoxMargin(this): return this.__textBoxMargin #------------------------------------------------------------------------------# # Mutators # #------------------------------------------------------------------------------# def setHUDSprites(this, group): this.__HUDSprites = group def setHeartSprites(this, group): this.__heartSprites = group def setTextBoxBlock(this, num): this.__textBoxBlock = num def setTextBoxLocX(this, num): this.__textBoxLocX = num def setTextBoxLocY(this, num): this.__textBoxLocY = num def setTextBoxSizeX(this, num): this.__textBoxSizeX = num def setTextBoxSizeY(this, num): this.__textBoxSizeY = num def setTextBoxMargin(this, num): this.__textBoxMargin = num #------------------------------------------------------------------------------# # # # Class Methods # # # #------------------------------------------------------------------------------# #Note: 2 text window blocks = 1 text block def createTextBox(this, posX, posY, blockSizeX, blockSizeY, isMoving): #ensure the text box is not too small to display text if blockSizeX < 10 or blockSizeY < 5: print ("The text box was too small to be created") return #create loop variables idx = int(2) #create the top left corner obj = HUDObject("Box Top Left", this.txtWinTopLeft, posX, posY,\ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) #Create the top bar idx = 1 while idx <= (blockSizeX - 1): obj = HUDObject("Box Horizontal", this.txtWinHorizontal,\ posX + (this.getTextBoxBlock() * idx), posY, \ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) idx += 1 #Create the top right corner obj = HUDObject("Box Top Right", this.txtWinTopRight, \ posX + (this.getTextBoxBlock() * blockSizeX), posY, \ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) #Create the left bar idx = 1 while idx <= (blockSizeY - 1): obj = HUDObject("Box Vertical", this.txtWinVertical,\ posX, posY + (this.getTextBoxBlock() * idx), \ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) idx += 1 #Create the right bar idx = 1 while idx <= (blockSizeY - 1): obj = HUDObject("Box Vertical", this.txtWinVertical,\ posX + (this.getTextBoxBlock() * blockSizeX), \ posY + (this.getTextBoxBlock() * idx), \ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) idx += 1 #Create the bottom left corner obj = HUDObject("Box Bottom Left", this.txtWinBotLeft, \ posX, posY + (this.getTextBoxBlock() * blockSizeY) , \ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) #Create the bottom bar idx = 1 while idx <= (blockSizeX - 1): obj = HUDObject("Box Horizontal", this.txtWinHorizontal,\ posX + (this.getTextBoxBlock() * idx), \ posY + (this.getTextBoxBlock() * blockSizeY), \ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) idx += 1 #Create the bottom right corner obj = HUDObject("Box Bottom Right", this.txtWinBotRight,\ posX + (this.getTextBoxBlock() * blockSizeX), \ posY + (this.getTextBoxBlock() * blockSizeY) , \ this.getTextBoxBlock(), this.getTextBoxBlock()) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) #Fill the box with a space obj = HUDObject("Box Space Black", this.txtWinSpaceBlack, \ posX + this.getTextBoxBlock(), \ posY + this.getTextBoxBlock() , \ (int(this.getTextBoxBlock() * (blockSizeX - 1))), \ (int(this.getTextBoxBlock() * (blockSizeY - 1)))) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) def createTextMessage(this, text, posX, posY, blockSizeX, blockSizeY, isMoving): if len(text) > ((blockSizeX + 1) * (blockSizeY + 1)): print("The message is too big for the text box") else: idx = 0 idxX = 0 idxY = 0 allTextDisplayed = False while not allTextDisplayed: for idxY in range (0, blockSizeY + 1): for idxX in range (0, (blockSizeX + 1)): obj = HUDText(text[idx],\ posX + (idxX * this.getTextBoxBlock()),\ posY + (idxY * this.getTextBoxBlock())) #add it to the text box sprite list this.getTextBoxSprites().add(obj) #if it is supposed to be a moving object if isMoving: #add it to the moving sprite list this.getMovingHUDSprites().add(obj) idx += 1 #ensure we dont raise an our of bounds error if idx >= len(text): allTextDisplayed = True break if idx >= len(text): break def createBoxWithMessage(this, text, posX, posY, blockSizeX, blockSizeY, isMoving): this.createTextBox(posX, posY, blockSizeX, blockSizeY, isMoving) this.createTextMessage(text,\ posX + (this.getTextBoxBlock() * this.getTextBoxMargin()),\ posY + (this.getTextBoxBlock() * this.getTextBoxMargin()),\ blockSizeX - (this.getTextBoxMargin() * 2),\ blockSizeY - (this.getTextBoxMargin() * 2), isMoving) def removeTextBox(this): for sprite in this.getTextBoxSprites(): sprite.kill() #gets an image from the HUD text Dictionary def getTextImage(this, char): return this.__textImageDict[char] def initGameHUD(this): this.getHUDSprites().empty() this.addHearts() #add the player's hearts to the screen def addHearts(this): blockLenX = this.game.getScreenBlockLengthX() blockLenY = this.game.getScreenBlockLengthY() for idx in range(0, this.game.getPlayer().healthMax): this.getHeartSprites().add(\ HUDObject("Empty Heart " + str(idx), this.heartEmpty,\ this.game.blockToPosX(blockLenX - (1.25 + (idx * 1.25))),\ this.game.blockToPosY(0.25),\ this.game.getBlockScale(), this.game.getBlockScale())) this.syncHearts() def syncHearts(this): blockLenX = this.game.getScreenBlockLengthX() blockLenY = this.game.getScreenBlockLengthY() #loop through each sprite in the heart sprite group and remove #all full hearts for obj in this.getHeartSprites(): if "Full Heart" in obj.getName(): obj.kill() #add all full hearts again for idx in range(0, this.game.getPlayer().health): this.getHeartSprites().add(\ HUDObject("Full Heart " + str(idx), this.heartFull,\ this.game.blockToPosX(blockLenX - (1.25 + (idx * 1.25))),\ this.game.blockToPosY(0.25),\ this.game.getBlockScale(), this.game.getBlockScale())) def syncGameHUD(this): syncHearts()