def create_level(self): """ Creates a new player and restarts level sprites. """ self._paused = False self._game.ui.clear() self._player = PlayerCtrl() self._level = Level('level_1.tmx', self._player, self) self._timer = Timer()
def __init__(self, hud): super(GameLayer, self).__init__() # 添加板子和球 self.is_on_exiting = True self.paddle = Paddle('images/paddle.png') self.add(self.paddle.sprite) self.ball = Ball('images/ball.png') self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height / 2) self.add(self.ball.sprite) # hud 用于记录,更新关卡,死亡,金币数据 self.hud = hud # 生成关卡 self.level = Level() self.level.levels = self.hud.levels self.add(self.hud.gold_hud) self.add(self.hud.level_hud) self.add(self.hud.death_hud) # 添加按键状态 self.key_pressed_left = False self.key_pressed_right = False self.key_pressed_up = False self.key_pressed_down = False self.reset() # 定期调用 self.update 函数 # FPS frame per second 每秒帧数 self.schedule(self.update)
def load_level(self, index): try: if self.level is not None: try: self.last_level_coins = self.get_player_coins() except: pass self.previous_level_index = int( self.level.config["General"]["index"]) self.level.clear() self.game_methods.last_level_time_left = self.game_methods.time_left self.game_methods.time_left = 0 self.level = Level.get_level_by_index(index) if self.level is None: if index != 0: self.load_level(0) else: raise NoLevelFoundException self.level.load() self.gui.clear_view() try: view_name = self.level.config["GUI"]["view"] self.gui.load_view(view_name, self.game_methods) except KeyError: pass self.camera.set_settings(self.level.config["Camera"]) self.camera.set_level(self.level) self.time = 0 self.time_at_last_fps_update = 0 self.frame_count = 0 except KeyError: pass return True
def test_move_entity(self): level = Level(self.config).create_empty_tiles() level.tiles[0][0].set_type('floor') level.tiles[1][0].set_type('floor') entity = Entity(0, 0) entity.move(1, 0, level) self.assertEqual((1, 0), (entity.x, entity.y))
def load_game(self, game_id): try: save = open(f"saves/save_{game_id}.xml", "r") # Test if there is a current saved game if save: tree_root = etree.parse(save).getroot() index = tree_root.find("level/index").text.strip() level_name = 'maps/level_' + index + '/' game_status = tree_root.find("level/phase").text.strip() turn_nb = 0 if game_status != 'I': turn_nb = int(tree_root.find("level/turn").text.strip()) # Load level with current game status, foes states, and team self.level_id = int(index) level = Level(level_name, self.level_id, game_status, turn_nb, tree_root.find("level/entities")) self.play(level) save.close() return except FileNotFoundError: # No saved game self.background_menus.append([self.active_menu, True]) name = "Load Game" entries = [[{'type': 'text', 'text': "No saved game.", 'font': fonts['MENU_SUB_TITLE_FONT']}]] width = self.screen.get_width() // 2 self.active_menu = InfoBox(name, "", "imgs/interface/PopUpMenu.png", entries, width, close_button=1)
def setup_level(self): level = Level(self.config).create_empty_tiles() for x in range(0, level.width): for y in range(0, level.height): level.tiles[x][y].set_type('floor') for column in level.tiles: level.flattened_tiles.extend(column) return level
def reset_blocks(self): level = Level() level.levels = self.save_as # 通过文件生成块 level.reset() # 删除已存在的块 for b in self.blocks: self.remove(b.sprite) # 清空存储的块和坐标 self.blocks.clear() # self.props.clear() # 添加新的块 for b in level.blocks: self.add(b.sprite) self.blocks.append(b)
def __init__(self) -> None: """ Creates a data model which is used for a graphic representation of Sokoban level (QGraphics View framework). QGraphicsScene.keyPressEvent() is implemented to process various player input. """ super().__init__() self._level = Level("levels/01/01") self.setSceneRect( QRectF(QPointF(0, 0), QPointF(self._level.width, self._level.height))) [ self.addItem(item) for item in self._level.tiles + self._level.boxes + tuple([self._level.player]) ] self._level.player.moveFinished.connect(self.unlockGame) self._gameLock = False
def enter(self, app): self.app = app self.view = app.view self.palette = [] for name in get_all('entities'): newtype = entities.get(name) self.palette.append(newtype) self.level = Level(app) self.mode = 't' self.mark = None self.delmark = None self.markmat = entities.get('mark') self.ground = entities.get('ground') print "CURRENT BRUSH:", self.brush
def __init__(self, game_info, sound_manager): GameState.__init__(self, GameState.STATE_GAME, GameState.STATE_LOAD) self.game_info = game_info self.sound_manager = sound_manager self.game_info.set_timer_in_seconds(300) self.mario_game_time = -1 self.world_shift = 0 self.player = Player(self.sound_manager, game_info) self.active_sprite_list = pygame.sprite.Group() self.active_sprite_list.add(self.player) self.level = Level(game_info, self.player, self.sound_manager) if constants.DEBUG: self.debug_overlay = DebugOverlay(self.game_info, self.player) self.sound_manager.play_music(constants.MUSIC_MAIN_THEME)
def enter(self, app): self.app = app self.view = app.view self.palette = [ ] for name in get_all('entities'): newtype = entities.get(name) self.palette.append(newtype) self.level = Level(app) self.mode = 't' self.mark = None self.delmark = None self.markmat = entities.get('mark') self.ground = entities.get('ground') print "CURRENT BRUSH:", self.brush
def __init__(self, levels=1, golds=0, deadcount=0): super(GameLayer, self).__init__() # 添加板子和球 self.paddle = Paddle('images/paddle.png') self.add(self.paddle.sprite) self.ball = Ball('images/ball.png') self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height/2) self.add(self.ball.sprite) # 生成关卡 self.level = Level() self.level.levels = levels # 添加标签用于记录金币和关卡。死亡次数 self.gold = golds self.deadcount = deadcount self.hud = Label('金币: '+str(golds)) self.level_hud = Label('关卡: '+str(levels)) self.deadstu = Label('死亡: '+str(deadcount)) self.hud.position = (0, 460) self.level_hud.position = (80, 460) self.deadstu.position = (160, 460) self.add(self.hud) self.add(self.level_hud) self.add(self.deadstu) # 添加按键状态 self.key_pressed_left = False self.key_pressed_right = False self.key_pressed_up = False self.key_pressed_down = False self.blocks = [] self.reset() # 定期调用 self.update 函数 # FPS frame per second 每秒帧数 self.schedule(self.update)
class TestGameplay(unittest.TestCase): app = None @classmethod def setUpClass(cls): global app app = QtGui.QApplication([]) def setUp(self): self.game = Game() self.level = Level("testUser", 1) self.board = Board(self.level, self.game) self.clearBricks() self.board.start() def tearDown(self): self.board.destroy() self.game.destroy() @classmethod def tearDownClass(cls): app.quit() def testInitializeBoardWithConcreteWalls(self): self.assertEqual(self.board.level.board[0][0].peek(), Tile.Concrete, "Corner tile should be Concrete, board not initialized properly") def testInitializeBoardWithExactlyOneBomberman(self): numberOfBombermanOnTheBoard = 0 board = self.board.level.board for i in range(len(board)): for j in range(len(board[i])): if board[i][j].peek() == Tile.Bomberman: numberOfBombermanOnTheBoard += 1 self.assertEqual(numberOfBombermanOnTheBoard, 1, "Did not see exactly one level on the board") def testSetTileAt(self): self.assertEqual(self.board.level.board[1][1].peek(), Tile.Empty) self.board.setTileAt(1, 1, Tile.Brick) self.assertEqual(self.board.level.board[1][1].peek(), Tile.Brick) def testTileAt(self): for i in range(len(self.board.level.board)): for j in range(len(self.board.level.board[i])): self.assertEqual(self.board.tileAt(j, i), self.board.level.board[i][j].peek()) def testSetBomberman(self): self.assertNotEqual(self.board.tileAt(1, 2), Tile.Bomberman) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 2 self.board.level.setBomberman() self.assertEqual(self.board.tileAt(1, 2), Tile.Bomberman) def testSetBomb(self): self.assertNotEqual(self.board.tileAt(1, 2), Tile.Bomb) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 2 self.board.level.setBomberman() #level should be here already self.board.level.setBomb() self.assertEqual(len(self.board.level.bombQueue), 1, "Bomb did not get enqueued") self.assertEqual(self.board.level.bombQueue.pop(), (1, 2, constant.TIME_BOMB), "Bomb's coordinates are wrong") self.assertEqual(self.board.tileAt(1, 2), Tile.Bomberman, "Bomberman is not on top of a bomb") self.board.popTileAt(1, 2) self.assertEqual(self.board.tileAt(1, 2), Tile.Bomb, "There is no bomb underneath Bomberman") def testDetonateBomb(self): self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.detonateBomb() self.board.popTileAt(1, 1) #pop Bomberman self.assertNotEqual(self.board.tileAt(1, 1), Tile.Bomb, "Bomb did not explode") def testDetonateBombHasNoEffectOnConcrete(self): self.board.curX = 1 self.board.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.detonateBomb() self.board.popTileAt(1, 1) #pop Bomberman self.assertEqual(self.board.tileAt(1, 0), Tile.Concrete, "Concrete got destroyed by bomb") def testDetonateBombDestroysBrick(self): self.board.setTileAt(1, 2, Tile.Brick) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.level.bomberman.rangeOfBombs = 3 self.board.detonateBomb() self.assertEqual(self.board.tileAt(1, 2), Tile.Empty, "Brick did not get destroyed by bomb") def testDetonateBombDestroysOnlyClosestBrickInTheSameDirection(self): self.board.setTileAt(1, 2, Tile.Brick) self.board.setTileAt(1, 3, Tile.Brick) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.level.bomberman.rangeOfBombs = 3 self.board.detonateBomb() self.assertEqual(self.board.tileAt(1, 2), Tile.Empty, "Closer Brick did not get destroyed by bomb") self.assertEqual(self.board.tileAt(1, 3), Tile.Brick, "Further Brick got destroyed by bomb") def testDetonateBombDestroysMultipleBricks(self): self.board.setTileAt(1, 2, Tile.Brick) self.board.setTileAt(2, 1, Tile.Brick) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.level.bomberman.rangeOfBombs = 3 self.board.detonateBomb() self.assertEqual(self.board.tileAt(1, 2), Tile.Empty, "One of the Bricks did not get destroyed by bomb") self.assertEqual(self.board.tileAt(2, 1), Tile.Empty, "One of the Bricks did not get destroyed by bomb") def testDetonateBombKillsEnemies(self): self.level.clearEnemies() self.board.setTileAt(2, 1, Tile.Balloom) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() tempList = [2, 1, constant.DIRECTION_WEST, Tile.Balloom] self.level.listEnemies.append(tempList) self.level.numberEnemies = 1 self.level.listTypeEnemies[0] = 1 self.board.level.bomberman.rangeOfBombs = 3 self.board.tryMove(1, 2) self.board.detonateBomb() self.assertEqual(self.board.tileAt(2, 1), Tile.Empty, "Bomb detonation did not kill enemy") self.assertEqual(0, self.level.numberEnemies, "Enemy was not removed from map") def testDetonateBombSpawnsEnemiesWhenExitIsHit(self): self.board.setTileAt(1, 2, Tile.Exit) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.level.bomberman.rangeOfBombs = 3 self.board.detonateBomb() count = 0 for i in range(self.level.numberEnemies): if (self.level.listTypeEnemies[i] != 0): count += 1 self.assertEqual(count, 1, "Not all enemies are the same type when the exit is hit") self.assertEqual(len(self.level.listEnemies), 8, "The number of enemies when the exit is hit is not 8") def testDetonateBombSpawnsEnemiesWhenPowerupIsHit(self): self.board.setTileAt(1, 2, Tile.Powerup) self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.level.bomberman.rangeOfBombs = 3 self.board.detonateBomb() count = 0 for i in range(self.level.numberEnemies): if (self.level.listTypeEnemies[i] != 0): count += 1 self.assertEqual(count, 1, "Not all enemies are the same type when the powerup is hit") self.assertEqual(len(self.level.listEnemies), 8, "The number of enemies when the powerup is hit is not 8") def testTimeRunsOut(self): self.level.timeLeft = 0 self.level.timeDone = False self.board.timeoutEvent() check = False for i in range(7): if (self.level.listTypeEnemies[i] != 0): check = True self.assertEqual(self.level.numberEnemies, 8, "Number of enemies is not equal to 8") self.assertFalse(check, "At least one enemy is not a Pontan") def testTryMoveToConcrete(self): self.board.setTileAt(0, 0, Tile.Concrete) self.assertFalse(self.board.tryMove(0, 0), "Was able to move to a concrete tile") def testTryMoveToBrick(self): self.board.setTileAt(1, 1, Tile.Brick) self.assertFalse(self.board.tryMove(1, 1), "Was able to move to a brick tile") def testTryMoveToBrick(self): self.board.setTileAt(2, 2, Tile.Empty) self.assertTrue(self.board.tryMove(2, 2), "Was not able to move to an empty tile") def testMoveEnemyWithIntelligence1(self): self.level.clearEnemies() self.board.setTileAt(2, 1, Tile.Balloom) self.board.setTileAt(1, 1, Tile.Empty) tempList = [2, 1, constant.DIRECTION_WEST, Tile.Balloom] self.level.listEnemies.append(tempList) self.level.numberEnemies = 1 self.level.listTypeEnemies[0] = 1 self.board.moveEnemy(constant.SPEED_SLOW) self.assertEqual(self.board.tileAt(1, 1), Tile.Balloom, "Enemy did not move") def testMoveEnemyWithIntelligence2(self): self.level.clearEnemies() self.board.setTileAt(2, 1, Tile.Oneal) self.board.setTileAt(1, 1, Tile.Empty) self.board.setTileAt(3, 1, Tile.Empty) self.board.setTileAt(2, 0, Tile.Empty) self.board.setTileAt(2, 2, Tile.Empty) tempList = [2, 1, constant.DIRECTION_WEST, Tile.Oneal] self.level.listEnemies.append(tempList) self.level.numberEnemies = 1 self.level.listTypeEnemies[0] = 1 self.board.moveEnemy(constant.SPEED_NORMAL) check = False if (self.board.tileAt(1, 1) == Tile.Oneal or self.board.tileAt(3, 1) == Tile.Oneal or self.board.tileAt(2, 0) == Tile.Oneal or self.board.tileAt(2, 2) == Tile.Oneal): check = True self.assertTrue(check, "Enemy did not move") def testMoveEnemyWithIntelligence3(self): self.level.clearEnemies() self.board.setTileAt(2, 1, Tile.Kondoria) self.board.setTileAt(1, 1, Tile.Empty) self.board.setTileAt(3, 1, Tile.Empty) self.board.setTileAt(2, 0, Tile.Empty) self.board.setTileAt(2, 2, Tile.Empty) tempList = [2, 1, constant.DIRECTION_WEST, Tile.Kondoria] self.level.listEnemies.append(tempList) self.level.numberEnemies = 1 self.level.listTypeEnemies[0] = 1 self.board.moveEnemy(constant.SPEED_SLOWEST) check = False if (self.board.tileAt(1, 1) == Tile.Kondoria or self.board.tileAt(3, 1) == Tile.Kondoria or self.board.tileAt(2, 0) == Tile.Kondoria or self.board.tileAt(2, 2) == Tile.Kondoria): check = True self.assertTrue(check, "Enemy did not move") def testDetonateBombKillsBomberman(self): self.level.lives = 3 self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.level.setBomb() self.board.tryMove(1, 2) self.board.detonateBomb() self.assertEqual(2, self.level.bomberman.lives, "Bomberman did not lose a life when hit by a bomb") def testDeathWhenEnemyMovesToBomberman(self): self.level.lives = 3 self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.level.clearEnemies() self.board.setTileAt(2, 1, Tile.Balloom) self.level.numberEnemies = 1 tempList = [2, 1, constant.DIRECTION_WEST, Tile.Balloom] self.level.listEnemies.append(tempList) self.level.listTypeEnemies[0] = 1 self.board.moveEnemy(constant.SPEED_SLOW) self.assertEqual(2, self.level.bomberman.lives, "Bomberman did not lose a life when an enemy moves into him") def testDeathWhenBombermanMovesToEnemy(self): self.level.lives = 3 self.board.level.bomberman.curX = 1 self.board.level.bomberman.curY = 1 self.board.level.setBomberman() self.board.setTileAt(1, 2, Tile.Balloom) self.board.tryMove(1, 2) self.assertEqual(2, self.level.bomberman.lives, "Bomberman did not lose a life when he moves into an enemy") def testGetScoreOfKilledEnemies(self): # No enemies: enemies = [[], [], []] self.assertEquals(self.board.getScoreOfKilledEnemies(enemies), 0) # 1 enemy at distance 1, with bomb range 1 enemies = [[Tile.Balloom]] self.assertEqual(self.board.getScoreOfKilledEnemies(enemies), Enemy.getEnemy(Tile.Balloom)['points']) # 1 enemy at distance 1, with bomb range >1 enemies = [[Tile.Balloom], [], []] self.assertEqual(self.board.getScoreOfKilledEnemies(enemies), Enemy.getEnemy(Tile.Balloom)['points']) # 1 enemy at distance >1 enemies = [[], [Tile.Balloom], []] self.assertEqual(self.board.getScoreOfKilledEnemies(enemies), Enemy.getEnemy(Tile.Balloom)['points']) # 2 enemies at different distance enemies = [[Tile.Balloom], [], [Tile.Doll]] self.assertEqual(self.board.getScoreOfKilledEnemies(enemies), Enemy.getEnemy(Tile.Balloom)['points'] + 2*Enemy.getEnemy(Tile.Doll)['points']) # 2 enemies at same distance enemies = [[Tile.Doll, Tile.Balloom], [], []] self.assertEqual(self.board.getScoreOfKilledEnemies(enemies), Enemy.getEnemy(Tile.Balloom)['points'] + 2*Enemy.getEnemy(Tile.Doll)['points']) # multiple enemies at multiple distances enemies = [[Tile.Doll, Tile.Balloom, Tile.Doll], [], [Tile.Ovapi, Tile.Ovapi], [Tile.Pontan]] self.assertEqual(self.board.getScoreOfKilledEnemies(enemies), Enemy.getEnemy(Tile.Balloom)['points'] + 2*Enemy.getEnemy(Tile.Doll)['points'] + 4*Enemy.getEnemy(Tile.Doll)['points'] + 8*Enemy.getEnemy(Tile.Ovapi)['points'] + 16*Enemy.getEnemy(Tile.Ovapi)['points'] + 32*Enemy.getEnemy(Tile.Pontan)['points']) def clearBricks(self): for x in range(constant.BOARD_WIDTH): for y in range(constant.BOARD_HEIGHT): if self.board.tileAt(x, y) == Tile.Brick: self.board.popTileAt(x, y)
class GameLayer(Layer): is_event_handler = True def __init__(self, levels=1, golds=0, deadcount=0): super(GameLayer, self).__init__() # 添加板子和球 self.paddle = Paddle('images/paddle.png') self.add(self.paddle.sprite) self.ball = Ball('images/ball.png') self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height/2) self.add(self.ball.sprite) # 生成关卡 self.level = Level() self.level.levels = levels # 添加标签用于记录金币和关卡。死亡次数 self.gold = golds self.deadcount = deadcount self.hud = Label('金币: '+str(golds)) self.level_hud = Label('关卡: '+str(levels)) self.deadstu = Label('死亡: '+str(deadcount)) self.hud.position = (0, 460) self.level_hud.position = (80, 460) self.deadstu.position = (160, 460) self.add(self.hud) self.add(self.level_hud) self.add(self.deadstu) # 添加按键状态 self.key_pressed_left = False self.key_pressed_right = False self.key_pressed_up = False self.key_pressed_down = False self.blocks = [] self.reset() # 定期调用 self.update 函数 # FPS frame per second 每秒帧数 self.schedule(self.update) # def on_enter(self): # self.visible = True def reset(self): self.paddle.reset() self.ball.reset() # 清空界面上的block for b in self.blocks: self.remove(b) # 再初始化新的砖块 self.blocks = [] positions = self.level.blocks_pos number_of_blocks = len(positions) for i in range(number_of_blocks): b = Sprite('images/block.png') b.position = positions[i] self.add(b) self.blocks.append(b) def game_over(self): self.deadcount += 1 scene = Scene(GameOver(self.level.levels, self.gold, self.deadcount)) director.replace(scene) def update_hud(self): self.hud.element.text = '金币: ' + str(self.gold) self.level_hud.element.text = '关卡: ' + str(self.level.levels) def update_blocks(self): for b in self.blocks: if collision(b, self.ball.sprite): self.ball.hit() self.blocks.remove(b) self.remove(b) self.gold += 1 self.update_hud() print('金币:', self.gold) break def update_ball(self): if self.ball.fired: self.ball.update() else: bx, by = self.ball.sprite.position px, py = self.paddle.sprite.position self.ball.sprite.position = (px, by) collide = collision(self.ball.sprite, self.paddle.sprite) if collide: self.ball.hit() if self.ball.dead(): self.game_over() def update_paddle(self): self.paddle.update() def update_input(self): self.paddle.move_right = self.key_pressed_right self.paddle.move_left = self.key_pressed_left if self.key_pressed_up: self.ball.fire() def update_newlevel(self): if len(self.blocks) == 0: self.level.next() print(self.level.levels) # self.reset() scene = Scene(GuoCangDongHua(self.level.levels, self.gold, self.deadcount)) director.replace(scene) # director.replace(FadeTransition(Scene(GameLayer(self.level.levels, self.gold)))) def update(self, dt): self.update_newlevel() self.update_ball() self.update_paddle() self.update_input() self.update_blocks() self.update_hud() def on_key_press(self, key, modifiers): k = symbol_string(key) status = True if k == 'LEFT': self.key_pressed_left = status elif k == 'RIGHT': self.key_pressed_right = status elif k == 'UP': self.key_pressed_up = status def on_key_release(self, key, modifiers): k = symbol_string(key) status = False if k == 'LEFT': self.key_pressed_left = status elif k == 'RIGHT': self.key_pressed_right = status elif k == 'UP': self.key_pressed_up = status
def load_level(level, team=None): if team is None: team = [] return Level('maps/level_' + str(level) + '/', level, players=team)
def setUp(self): self.game = Game() self.level = Level("testUser", 1) self.board = Board(self.level, self.game) self.clearBricks() self.board.start()
Including my hygienic proclivities.''') hallway = Room( 'hallway', '''I stepped out of my house, and... what's this??? Instead of my front yard, I walk into a hallway that seems to extend forever. Each side of the hallway is lined with room doors just like mine! My hangover suddenly gave way to a sick stomach and wobbly knees. ... What's going on here??? To the west, I spotted an elevator that looks too old to function. But it seemed to be the only thing that would get me out of this nightmare.''') elevator = Room( 'elevator', '''This elevator is operated with a steel lever.\nQuite old school.''') spa = Room( 'spa', '''I pulled the lever and headed down. The counter kept counting, counting, counting down. In God-knows-how-long, I exit the elevator, and I'm greeted by a friendly Velociraptor in a tuxedo and a bow-tie. "Welcome, Sirmadam!"''') bedRoom.set_east(kitchen) bedRoom.set_south(living) bedRoom.set_north(hallway) hallway.set_west(elevator) elevator.set_south(spa) level_one = Level(bedRoom)
class MarioGame(GameState): def __init__(self, game_info, sound_manager): GameState.__init__(self, GameState.STATE_GAME, GameState.STATE_LOAD) self.game_info = game_info self.sound_manager = sound_manager self.game_info.set_timer_in_seconds(300) self.mario_game_time = -1 self.world_shift = 0 self.player = Player(self.sound_manager, game_info) self.active_sprite_list = pygame.sprite.Group() self.active_sprite_list.add(self.player) self.level = Level(game_info, self.player, self.sound_manager) if constants.DEBUG: self.debug_overlay = DebugOverlay(self.game_info, self.player) self.sound_manager.play_music(constants.MUSIC_MAIN_THEME) def process_events(self, events): for event in events: if event.type == pygame.KEYDOWN: key = event.key if key == pygame.K_LEFT: self.player.go_left() if key == pygame.K_RIGHT: self.player.go_right() if key == pygame.K_UP: self.player.jump() if key == pygame.K_DOWN: self.player.crouch() if key == pygame.K_a: self.player.transition(constants.POWER_LARGE) if key == pygame.K_s: self.player.transition(constants.POWER_SMALL) if key == pygame.K_t: self.player.start_death_sequence() if key == pygame.K_ESCAPE or key == pygame.K_q: # TODO should be pause pass if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and self.player.x_vel < 0: self.player.stop() if event.key == pygame.K_RIGHT and self.player.x_vel > 0: self.player.stop() if event.key == pygame.K_DOWN: self.player.stop() def update(self, game_time): if self.mario_game_time == -1: self.mario_game_time = game_time else: self.game_info.timer -= (game_time - self.mario_game_time) self.mario_game_time = game_time if self.player.rect.bottom > constants.SCREEN_HEIGHT and self.player.transition_state is not constants.TRANSITION_DEATH_SEQUENCE: self.player.start_death_sequence() if self.player.state == constants.STATE_DEAD: self.switch = True self.game_info.num_lives -= 1 if self.game_info.num_lives < 0: self.set_next_state(GameState.STATE_GAME_OVER) self.level.update(game_time) def draw(self, screen): self.level.draw(screen) self.active_sprite_list.draw(screen) if constants.DEBUG: self.debug_overlay.draw(screen)
def test_default_update_just_returns_true(self): self.assertTrue(Entity(0, 0).update(Level(self.config)))
class GamePlayingState: def __init__(self, game): self._game = game self._paused = False self._game_over = False def enter(self): self.create_level() def create_level(self): """ Creates a new player and restarts level sprites. """ self._paused = False self._game.ui.clear() self._player = PlayerCtrl() self._level = Level('level_1.tmx', self._player, self) self._timer = Timer() def exit(self): # Save score or something self._game.ui.clear() def process_events(self, event): if not self._game_over: if event.type == pg.KEYDOWN: if event.key == pg.K_p: self.pause() def pause(self): if self._paused: self._game.ui.pop_menu() Timer.unpause_timers() else: actions = [{ 'action': self.pause, 'text': 'Resume' }, { 'action': self.create_level, 'text': 'Restart' }, { 'action': lambda: self._game.set_state(GameNotPlayingState), 'text': 'Main Menu' }] self._game.ui.make_menu("Game Paused", actions, 24, cfg.WHITE) Timer.pause_timers() self._paused = not self._paused def game_over(self): actions = [{ 'action': lambda: self._game.set_state(GamePlayingState), 'text': 'Play Again' }, { 'action': lambda: self._game.set_state(GameNotPlayingState), 'text': 'Main Menu' }, { 'action': self._game.quit, 'text': 'Quit' }] if self._player.alive(): title = "You win!" else: title = "Game Over!" self._game.ui.make_menu(title, actions, 24, cfg.WHITE) self._timer.pause() self._game_over = True def handle_input(self, active_bindings, mouse_state, mouse_x, mouse_y): if not (self._paused or self._game_over): self._player.handle_keys(active_bindings) self._player.handle_mouse(mouse_state, mouse_x, mouse_y) def update(self, dt): if not self._paused: self._level.update(dt) def draw(self): self._level.draw(self._game.screen) self._game.ui.draw(self._game.screen) total_secs = self._timer.elapsed_time() // 1000 mins = total_secs // 60 secs = total_secs % 60 gtext.render(self._game.screen, f"{mins:02d}:{secs:02d}", 24, cfg.WHITE, location='n')
def on_click(self): self.window.show_view(Level(1))
class GameLayer(Layer): is_event_handler = True def __init__(self, hud): super(GameLayer, self).__init__() # 添加板子和球 self.is_on_exiting = True self.paddle = Paddle('images/paddle.png') self.add(self.paddle.sprite) self.ball = Ball('images/ball.png') self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height / 2) self.add(self.ball.sprite) # hud 用于记录,更新关卡,死亡,金币数据 self.hud = hud # 生成关卡 self.level = Level() self.level.levels = self.hud.levels self.add(self.hud.gold_hud) self.add(self.hud.level_hud) self.add(self.hud.death_hud) # 添加按键状态 self.key_pressed_left = False self.key_pressed_right = False self.key_pressed_up = False self.key_pressed_down = False self.reset() # 定期调用 self.update 函数 # FPS frame per second 每秒帧数 self.schedule(self.update) def reset(self): self.paddle.reset() self.ball.reset() # 清空界面上的block for b in self.level.blocks: self.remove(b.sprite) # 再初始化新的砖块 self.level.reset() for b in self.level.blocks: self.add(b.sprite) def game_over(self): self.hud.death += 1 self.is_on_exiting = False scene = create_scene(GameOver(self.hud)) director.replace(scene) def update_hud(self): self.hud.update() def update_blocks(self): for b in self.level.blocks: if collised(b.sprite, self.ball.sprite): print(1) self.ball.hit() b.live -= 1 if b.live < 0: self.level.blocks.remove(b) self.remove(b.sprite) else: b.reset() self.hud.gold += 1 self.update_hud() print('金币:', self.hud.gold) break def update_ball(self): if self.ball.fired: self.ball.update() else: bx, by = self.ball.sprite.position px, py = self.paddle.sprite.position self.ball.sprite.position = (px, by) collide = collised(self.ball.sprite, self.paddle.sprite) if collide: xisu = 1 bx, by = self.ball.sprite.position px, py = self.paddle.sprite.position offect_scale = (bx - px) / (self.paddle.sprite.width / 2) ball_speedx_change = offect_scale * xisu self.ball.speedx += ball_speedx_change self.ball.hit() if self.ball.dead(): self.game_over() def update_paddle(self): self.paddle.update() def update_input(self): self.paddle.move_right = self.key_pressed_right self.paddle.move_left = self.key_pressed_left if self.key_pressed_up: self.ball.fire() def update_newlevel(self): if len(self.level.blocks) == 0: self.is_on_exiting = False if self.level.next(): print(self.level.levels) self.hud.levels += 1 scene = create_scene(GuoCangDongHua(self.hud)) else: scene = create_scene(GameComplite(self.hud)) director.replace(scene) def update(self, dt): if self.is_on_exiting: self.update_newlevel() self.update_ball() self.update_paddle() self.update_input() self.update_blocks() self.update_hud() def on_key_press(self, key, modifiers): k = symbol_string(key) status = True if k == 'LEFT': self.key_pressed_left = status elif k == 'RIGHT': self.key_pressed_right = status elif k == 'UP': self.key_pressed_up = status def on_key_release(self, key, modifiers): k = symbol_string(key) status = False if k == 'LEFT': self.key_pressed_left = status elif k == 'RIGHT': self.key_pressed_right = status elif k == 'UP': self.key_pressed_up = status
pg.init() # Load fonts fonts.init_fonts() # Window parameters pg.display.set_caption("In the name of the Five Cats") screen = pg.display.set_mode((MAIN_WIN_WIDTH, MAIN_WIN_HEIGHT)) # Load constant sprites Destroyable.init_constant_sprites() Breakable.init_constant_sprites() Movable.init_constant_sprites() Sidebar.init_constant_sprites() Level.init_constant_sprites() # Load some data races = Loader.load_races() classes = Loader.load_classes() Character.init_data(races, classes) clock = pg.time.Clock() start_screen = StartScreen(screen) quit_game = False while not quit_game: for e in pg.event.get(): if e.type == pg.QUIT: quit_game = True
class EditorScene(Scene): def __init__(self): self.dirty = True def enter(self, app): self.app = app self.view = app.view self.palette = [ ] for name in get_all('entities'): newtype = entities.get(name) self.palette.append(newtype) self.level = Level(app) self.mode = 't' self.mark = None self.delmark = None self.markmat = entities.get('mark') self.ground = entities.get('ground') print "CURRENT BRUSH:", self.brush def build(self, x, y, etype, *args, **kwargs): ct = self.level.tile_at(x, y) if ct: self.destroy(ct) self.level.tiles.append(etype(x, y, *args, **kwargs)) def place(self, x, y, etype, *args, **kwargs): ce = self.level.ent_at(x, y) if ce: self.remove(ce) self.level.entities.append(etype(x, y, *args, **kwargs)) def destroy(self, entity): if entity in self.level.tiles: self.level.tiles.remove(entity) def remove(self, entity): if entity in self.level.entities: self.level.entities.remove(entity) def reset_editor(self): self.mode = 't' self.mark = None self.delmark = None def next_brush(self): self.palette.append(self.palette.pop(0)) def prev_brush(self): self.palette.insert(0, self.palette.pop()) def _getbrush(self): return self.palette[0] brush = property(_getbrush) def save(self, filename): filename = filename.strip() print os.getcwd() fobj = open(os.path.join("data/levels", filename + '.lvl'), 'w') pickle.dump(self.level, fobj) print "Level '{0}' saved".format(filename) def load(self, filename): try: fobj = open(os.path.join("data/levels", filename + '.lvl'), 'r') self.level = pickle.load(fobj) self.reset_editor() self.dirty = True print "Level '{0}' loaded".format(filename) except Exception, e: raise e print "Unable to load '{0}'".format(filename)
class EditorScene(Scene): def __init__(self): self.dirty = True def enter(self, app): self.app = app self.view = app.view self.palette = [] for name in get_all('entities'): newtype = entities.get(name) self.palette.append(newtype) self.level = Level(app) self.mode = 't' self.mark = None self.delmark = None self.markmat = entities.get('mark') self.ground = entities.get('ground') print "CURRENT BRUSH:", self.brush def build(self, x, y, etype, *args, **kwargs): ct = self.level.tile_at(x, y) if ct: self.destroy(ct) self.level.tiles.append(etype(x, y, *args, **kwargs)) def place(self, x, y, etype, *args, **kwargs): ce = self.level.ent_at(x, y) if ce: self.remove(ce) self.level.entities.append(etype(x, y, *args, **kwargs)) def destroy(self, entity): if entity in self.level.tiles: self.level.tiles.remove(entity) def remove(self, entity): if entity in self.level.entities: self.level.entities.remove(entity) def reset_editor(self): self.mode = 't' self.mark = None self.delmark = None def next_brush(self): self.palette.append(self.palette.pop(0)) def prev_brush(self): self.palette.insert(0, self.palette.pop()) def _getbrush(self): return self.palette[0] brush = property(_getbrush) def save(self, filename): filename = filename.strip() print os.getcwd() fobj = open(os.path.join("data/levels", filename + '.lvl'), 'w') pickle.dump(self.level, fobj) print "Level '{0}' saved".format(filename) def load(self, filename): try: fobj = open(os.path.join("data/levels", filename + '.lvl'), 'r') self.level = pickle.load(fobj) self.reset_editor() self.dirty = True print "Level '{0}' loaded".format(filename) except Exception, e: raise e print "Unable to load '{0}'".format(filename)
class DataModel(QGraphicsScene): ################################################################################ def __init__(self) -> None: """ Creates a data model which is used for a graphic representation of Sokoban level (QGraphics View framework). QGraphicsScene.keyPressEvent() is implemented to process various player input. """ super().__init__() self._level = Level("levels/01/01") self.setSceneRect( QRectF(QPointF(0, 0), QPointF(self._level.width, self._level.height))) [ self.addItem(item) for item in self._level.tiles + self._level.boxes + tuple([self._level.player]) ] self._level.player.moveFinished.connect(self.unlockGame) self._gameLock = False ################################################################################ @property def level(self) -> Level: """ :return: current level object """ return self._level ################################################################################ def lockGame(self) -> None: """ Locks the game to deny the player any input. :return: None """ self._gameLock = True ################################################################################ def unlockGame(self) -> None: """ Unlocks the game to allow the player any input. :return: None """ self._gameLock = False ################################################################################ def keyPressEvent(self, event: QKeyEvent) -> None: """ Handles the player's keyboard input. Possible actions: -move player up, down, left, right -reset level to the initial state -start bfs algorithm (deterministic) -start bfs algorithm (non-deterministic) -start dfs algorithm (deterministic) -start dfs algorithm (non-deterministic) :param event: QKeyEvent to be handled :return: None """ if not self._gameLock: key = event.key() if key in self._level.DIRECTIONS: dRow = self._level.DIRECTIONS[key][0] dColumn = self._level.DIRECTIONS[key][1] self._level.movePlayer(dRow, dColumn, animated=True) elif key == Qt.Key_R: self._level.reset() elif key == Qt.Key_B: if event.modifiers() == Qt.ShiftModifier: self._level.bfs(deterministic=False) else: self._level.bfs() elif key == Qt.Key_D: if event.modifiers() == Qt.ShiftModifier: self._level.dfs(deterministic=False) else: self._level.dfs() super().keyPressEvent(event)
def debug(): cwd = os.getcwd() level1 = Level('../levels/007.xml') start(level1) print('stop')
def setUp(self): self.level = Level({'width': 10, 'height': 10}) self.collision_controller = CollisionController(self.level)
def test_move_entity_gets_stuck_on_unwalkable_tile(self): level = Level(self.config).create_empty_tiles() level.tiles[0][0].set_type('floor') entity = Entity(0, 0) entity.move(1, 0, level) self.assertEqual((0, 0), (entity.x, entity.y))