def main(): try: pygame.init() disp = pygame.display.set_mode((800, 600), False, False) pygame.display.set_caption("rock, paper, and scissors") except pygame.error: print "Pygame failed to initialize" try: tiles = pygame.image.load(src + "images/ssp_trans.png") except pygame.error: print "Failed to read game data" clk = pygame.time.Clock() exit_game = False startscreen = StartScreen(disp, clk, tiles) gamescreen = GameScreen(disp, clk, tiles) while not exit_game: ret = startscreen.run() exit_game = ret[0] if exit_game: break exit_game = gamescreen.run(ret[1]) pygame.quit() return 1
def __init__(self): ''' Sets up the initial game board, with the player at a set position. Once everything is set up, starts the game. ''' # Set up the screen self.screen = GameScreen() self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png') # Set up some game components self.inventory = Inventory() self.map = Map() self.map.player = (1 * TILE_SIZE, 1 * TILE_SIZE) self.player_stats = Player() treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.clock = pygame.time.Clock() self.direction = 0 self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map) self.run()
def __init__(self, app): GameScreen.__init__(self, app) LoadFontFace("menus/Delicious-Roman.otf") self.region = RocketRegion.make('pandaRocket', self.app.win) self.region.setActive(1) context = self.region.getContext() self.menu = context.LoadDocument('menus/main_menu.rml') self.menu.hook = self
def __init__(self, control_manager, player): GameScreen.__init__(self, control_manager) self.width, self.height = WIN_WIDTH, WIN_HEIGHT self.bg = Surface((WIN_WIDTH, WIN_HEIGHT)) self.player = player self.ui_font = font.Font("./fonts/FreeSansBold.ttf", 16) self.small_font = font.Font("./fonts/FreeSansBold.ttf", 12) self.main_options_index = 0 self.equipment_party_index = 0 self.equipment_slot_index = 0 self.equipment_item_index = 0 self.equipment_page_index = 0 self.mode = MAIN
def soccer_screen(): soccer = GameScreen((1200, 900), colors.GREEN) soccer.create_sprites(colors.WHITE) soccer.position() soccer.draw_sprites() pygame.display.flip()
def black_red_screen(): black_red = GameScreen((1200, 900), colors.BLACK) black_red.create_sprites(colors.RED) black_red.position() black_red.draw_sprites() pygame.display.flip()
def classic_screen(): classic = GameScreen((1200, 900), colors.BLACK) classic.create_sprites(colors.WHITE) classic.position() classic.draw_sprites() pygame.display.flip()
def __init__(self): ''' Sets up the initial game board, with the player at a set position. Once everything is set up, starts the game. ''' # Set up the screen self.screen = GameScreen() self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png') # Set up some game components self.inventory = Inventory() self.map = Map() self.map.player = (1*TILE_SIZE, 1*TILE_SIZE) self.player_stats = Player() treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.clock = pygame.time.Clock() self.direction = 0 self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map) self.run()
def run_game(): pygame.init() cur_gamestate = GameState(1) new_gamestate = GameState( 0) # Used to track which game state we are switching to game_settings = Settings() clock = pygame.time.Clock() screen = pygame.display.set_mode( (game_settings.screen_w, game_settings.screen_h)) pygame.display.set_caption(game_settings.game_name) title_screen = TitleScreen(screen, game_settings) settings_screen = SettingsScreen(screen, game_settings) about_screen = AboutScreen(screen, game_settings) game_settings.initialize_settings() game_screen = GameScreen(screen, game_settings) highscores_screen = HighScoresScreen(screen, game_settings) screens = { GameState.TITLE: title_screen, GameState.SETTINGS: settings_screen, GameState.ABOUT: about_screen, GameState.PLAYING: game_screen, GameState.HIGHSCORES: highscores_screen } screen = title_screen while True: clock.tick(game_settings.clock_tick_interval) if new_gamestate is GameState.QUIT: game_settings.save_settings() pygame.quit() sys.exit() if cur_gamestate != new_gamestate: # Run screen start function cur_gamestate = new_gamestate screen = screens[cur_gamestate] screen.screen_start() new_gamestate = screen.check_events() screen.update() screen.blitme() if cur_gamestate != new_gamestate: # If gamestate has changed, run screen end function screen.screen_end() pygame.display.flip()
def __init__(self): #initialize GameScreen self.gamescreen = GameScreen() all_sprite_list = pygame.sprite.Group() wall_list = pygame.sprite.Group() myWall = Wall(0, 0, 10, 600) self.gamescreen.drawWall(myWall) self.runGame()
def __init__(self, window): super(WindowManager, self).__init__() self.window = window self.InputHandler = InputHandler(self.window) self.window.push_handlers(self.InputHandler.keys) self.stack = [] #self.cross = CrossHair() self.saved_mouse = (1280 / 2, 720 / 2) # set up main menu as starting screen self.current_screen = MainMenu(window=self.window) self.register_screen()
def __init__(self, player=None): director.init() self.main_layer = GameScreen(self) self.ball = Ball() self.main_layer.add(self.ball) self.bouncer = Bouncer() self.main_layer.add(self.bouncer) self.score = 0 self.score_label = Label("Score: 0", font_size=32) self.score_label.position = 20, 400 self.main_layer.add(self.score_label) self.main_scene = Scene(self.main_layer) self.collision_manager = CollisionManagerGrid(0, 640, 0, 400, 5, 5) self.collision_manager.add(self.ball) self.collision_manager.add(self.bouncer) self.player = player
def __init__(self, control_manager, player, monsters, tile, battle_data = None): GameScreen.__init__(self, control_manager) self.width, self.height = WIN_WIDTH, WIN_HEIGHT self.player = player self.monsters = monsters self.init_active_party() self.assign_monster_letters() self.generate_rewards() self.bg = self.generate_bg(tile) self.ui_font = font.Font("./fonts/FreeSansBold.ttf", 16) self.mode = SELECT_ACTION self.action_index = 0 self.target_index = 0 self.item_select_index = 0 self.spell_index_x, self.spell_index_y = 0, 0 self.pending_action = None self.spell_queue = [] self.turn_manager = TurnManager(self) self.misc_message = None self.victory_flag = False self.battle_data = battle_data
class Game(): def __init__(self, player=None): director.init() self.main_layer = GameScreen(self) self.ball = Ball() self.main_layer.add(self.ball) self.bouncer = Bouncer() self.main_layer.add(self.bouncer) self.score = 0 self.score_label = Label("Score: 0", font_size=32) self.score_label.position = 20, 400 self.main_layer.add(self.score_label) self.main_scene = Scene(self.main_layer) self.collision_manager = CollisionManagerGrid(0, 640, 0, 400, 5, 5) self.collision_manager.add(self.ball) self.collision_manager.add(self.bouncer) self.player = player def update(self, delta_t): self.ball.update(self) self.bouncer.update() if self.collision_manager.they_collide(self.ball, self.bouncer): print("collision") self.winPoint() self.ball.reset() if self.player: self.player.update(self.ball, self.bouncer) def loosePoint(self): print("-1 points") self.score -= 1 self.score_label.element.text = "Score: {}".format(self.score) def winPoint(self): print("+1 points") self.score += 1 self.score_label.element.text = "Score: {}".format(self.score) def start(self): self.main_layer.schedule(self.update) self.ball.doFall() director.run(self.main_scene)
def __init__(self, app): GameScreen.__init__(self, app) utilities.setApp(self.app) self.world = World(10) self.app.taskMgr.add(self.update, "update") self.app.accept("a", self.world.player.moveLeft, [True]) self.app.accept("a-up", self.world.player.moveLeft, [False]) self.app.accept("d", self.world.player.moveRight, [True]) self.app.accept("d-up", self.world.player.moveRight, [False]) self.app.accept("space", self.world.player.jump, [True]) self.app.accept("space-up", self.world.player.jump, [False]) self.app.accept("c", self.world.player.crouch, [True]) self.app.accept("c-up", self.world.player.crouch, [False]) self.app.accept("mouse1", self.world.player.activate, []) self.app.accept("escape", sys.exit, []) #self.app.accept("h", self.showDBG, [True]) #self.app.accept("h-up", self.showDBG, [False]) self.prevTime = 0 self.app.mousePos = Point2() self.app.disableMouse() self.app.rl = base.camLens.makeCopy()
def build(self): global DATABASE_LIST DATABASE_LIST = load_db() db_init() self.title = 'Flash Card App' self.sm = ScreenManager() self.sm.current_screen d = DataBaseScreen(DATABASE_LIST) self.sm.add_widget(d) self.sm.current = 'db screen' a = StackListScreen() b = WordListScreen() c = GameScreen() self.sm.add_widget(a) self.sm.add_widget(b) self.sm.add_widget(c) return self.sm
def __init__(self): self.screen = GameScreen() self.bg = pygame.image.load(IMG_DIR + 'background.png') death_sound = pygame.mixer.Sound(SFX_DIR + 'death.ogg') self.inventory = Inventory() self.map = Map() self.map.player = (1*TILE_SIZE, 1*TILE_SIZE) self.player_stats = Player() treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.clock = pygame.time.Clock() self.direction = 0 self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map) self.run()
def main(): gScreen = GameScreen()
def start_game(self): self.current_screen = GameScreen(self.window, self.InputHandler) self.register_screen() #get to load screen self.receive_events('menu_transition_+', (LoadScreen, False)) self.connect()
class Game(object): ''' The game object. Controls rendering the game and moving the player. ''' def __init__(self): ''' Sets up the initial game board, with the player at a set position. Once everything is set up, starts the game. ''' # Set up the screen self.screen = GameScreen() self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png') # Set up some game components self.inventory = Inventory() self.map = Map() self.map.player = (1*TILE_SIZE, 1*TILE_SIZE) self.player_stats = Player() treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.clock = pygame.time.Clock() self.direction = 0 self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map) self.run() def add_treasure(self, treasure): ''' Adds the treasure to the player's inventory ''' text = "You found a %s. %s" % (treasure.title, treasure.description) self.inventory.add_to_inventory(treasure, self.player_stats) self.screen.draw_alert(text) def move(self, hor, vert): ''' Moves the player, given a keypress. Also evaluates if the player needs to fight or pick up some treasure. ''' self.old_row, self.old_col = self.map.player row = self.old_row + hor col = self.old_col + vert if row > (ROWS-1) * TILE_SIZE or row < 0 or col > (COLUMNS-1) * TILE_SIZE or col < 0: return if self.map.has_wall(row, col): return if self.map.has_monster(row, col): Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]) if self.map.monsters[row/TILE_SIZE][col/TILE_SIZE].current_hp <= 0: pass #put death throes here if self.player_stats.current_hp <= 0: self.end_game() self.move(0,0) return self.map.player = (row, col) self.map.player = (row, col) self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.screen.draw_inventory(self.inventory) self.screen.draw_equipment(self.player_stats.equipped) def refresh_screen(self): self.screen.draw_player(self.map.player) self.screen.draw_screen_layers(self.map, self.player_stats) def end_game(self): ''' The exit screen for when the player has died, or completed the game. So far, all it does is exit the game. ''' sys.exit() def run(self): ''' The main loop of the game. ''' # Fix for double move from Joshua Grigonis! Thanks! hor = 0 vert = 0 while 1: self.clock.tick(30) for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit(0) if event.key == K_LEFT: hor = -TILE_SIZE vert = 0 if event.key == K_RIGHT: hor = TILE_SIZE vert = 0 if event.key == K_UP: vert = -TILE_SIZE hor = 0 if event.key == K_DOWN: vert = TILE_SIZE hor = 0 if event.type == KEYUP: # updates only occur is player has moved. if vert or hor: self.move(hor, vert) self.map.move_monsters() hor = 0 vert = 0 self.refresh_screen()
def receive_events(self, event, msg): if event == 'kill_self': from twisted.internet import reactor reactor.stop() elif event == 'start_game': self.stack = [] self.start_game() elif event == 'to_main': self.stack = [] self.current_screen = MainMenu(window=self.window) self.register_screen() self.disconnect() self.saved_mouse = (1280 / 2, 720 / 2) elif event == 'menu_transition_+': msg, arg = msg if isinstance(self.current_screen, GameScreen): self.saved_mouse = tuple(self.InputHandler.m_cam) #save aimpos, otherwise 0, 0 is sent to server #and viewed by specs inpt = proto.Input() inpt.mx = self.current_screen.player.input.mx inpt.my = self.current_screen.player.input.my self.current_screen.player.input = inpt try: self.InputHandler.unregister(self.current_screen.camera. receive_m_pos, 'mouse_cam') except KeyError: pass self.current_screen = msg(arg, window=self.window) self.register_screen() elif event == 'menu_transition_-': self.stack.pop() self.current_screen = self.stack[-1] if isinstance(self.current_screen, MainMenu): self.current_screen = MainMenu(window=self.window) self.register_screen() # input to client elif event == 'input': self.send_message('input', msg) elif event == 'other': self.send_message('other', msg) # server plaerdata elif event == 'serverdata': if isinstance(self.stack[0], GameScreen): self.stack[0].from_server(msg) elif event == 'on_connect': self.stack[0].on_connect(msg) self.current_screen.on_connect() elif event == 'try_join': self.stack[0].try_join() elif event == 'chat': self.stack[0].send_chat(msg) elif event == 'options': self.InputHandler.load_options() elif event == 'switch_to': msg, arg = msg self.stack.pop() self.current_screen = msg(arg, window=self.window) self.register_screen()
# class Pellet(FallingItem): # surf = pelletSurfaceObj # def giveBonus(self,p): # p.addScore(7) # p.pellets += 1 # #soundPickup.play() # # class FlowerItem(FallingItem): # surf = flowerSurfaceObj # def giveBonus(self,p): # p.addScore(50) # #soundPickup.play() # # class FlowerStalkItem(FallingItem): # surf = flowerstalkSurfaceObj # def giveBonus(self,p): # p.addScore(25) # #soundPickup.play() # while True: g = Game() gs = GameScreen(g, windowSurfaceObj) gs.showTitleScreen() while not g.isGameOver: g.update(fpsClock.tick_busy_loop()) gs.render() pygame.display.flip() gs.showGameOverScreen()
class WindowManager(Events): """docstring for WindowManager""" def __init__(self, window): super(WindowManager, self).__init__() self.window = window self.InputHandler = InputHandler(self.window) self.window.push_handlers(self.InputHandler.keys) self.stack = [] #self.cross = CrossHair() self.saved_mouse = (1280 / 2, 720 / 2) # set up main menu as starting screen self.current_screen = MainMenu(window=self.window) self.register_screen() def update(self, dt): self.InputHandler.process_keys(dt) if (self.stack[0] != self.current_screen and isinstance(self.stack[0], GameScreen)): self.stack[0].idle_update(dt) self.current_screen.update(dt) def draw(self): # stack[0] is gamescreen if self.stack[0] != self.current_screen: if isinstance(self.stack[0], GameScreen): self.stack[0].draw() self.current_screen.draw() # receive events, a lot of transitions will happen here def receive_events(self, event, msg): if event == 'kill_self': from twisted.internet import reactor reactor.stop() elif event == 'start_game': self.stack = [] self.start_game() elif event == 'to_main': self.stack = [] self.current_screen = MainMenu(window=self.window) self.register_screen() self.disconnect() self.saved_mouse = (1280 / 2, 720 / 2) elif event == 'menu_transition_+': msg, arg = msg if isinstance(self.current_screen, GameScreen): self.saved_mouse = tuple(self.InputHandler.m_cam) #save aimpos, otherwise 0, 0 is sent to server #and viewed by specs inpt = proto.Input() inpt.mx = self.current_screen.player.input.mx inpt.my = self.current_screen.player.input.my self.current_screen.player.input = inpt try: self.InputHandler.unregister(self.current_screen.camera. receive_m_pos, 'mouse_cam') except KeyError: pass self.current_screen = msg(arg, window=self.window) self.register_screen() elif event == 'menu_transition_-': self.stack.pop() self.current_screen = self.stack[-1] if isinstance(self.current_screen, MainMenu): self.current_screen = MainMenu(window=self.window) self.register_screen() # input to client elif event == 'input': self.send_message('input', msg) elif event == 'other': self.send_message('other', msg) # server plaerdata elif event == 'serverdata': if isinstance(self.stack[0], GameScreen): self.stack[0].from_server(msg) elif event == 'on_connect': self.stack[0].on_connect(msg) self.current_screen.on_connect() elif event == 'try_join': self.stack[0].try_join() elif event == 'chat': self.stack[0].send_chat(msg) elif event == 'options': self.InputHandler.load_options() elif event == 'switch_to': msg, arg = msg self.stack.pop() self.current_screen = msg(arg, window=self.window) self.register_screen() def start_game(self): self.current_screen = GameScreen(self.window, self.InputHandler) self.register_screen() #get to load screen self.receive_events('menu_transition_+', (LoadScreen, False)) self.connect() def register_screen(self): # menu screen if not isinstance(self.current_screen, GameScreen): self.InputHandler.register(self.current_screen.receive_event, events=('changed_mouse', 'all_input')) self.window.set_mouse_visible(True) self.window.set_exclusive_mouse(False) # game screen else: for i, j in enumerate(self.saved_mouse): self.InputHandler.m_cam[i] = j self.InputHandler.register(self.current_screen.camera. receive_m_pos, 'mouse_cam') # set mouse on same position as it was before opening menu self.InputHandler.send_message('mouse_cam', self.InputHandler.m_cam) #needed so player doesnt shoot when coming from a menu self.InputHandler.keys[1 + self.InputHandler.mouse_offset] = False # pass by ref bullshit self.current_screen.player.input = self.InputHandler.directns self.current_screen.controls = self.InputHandler.controls self.current_screen.update_keys() # sends player input to lient class self.current_screen.register(self.receive_events, 'input') self.current_screen.camera.register(self.InputHandler.receive_aim, 'mousepos') if not self.current_screen.isSpec: self.window.set_mouse_visible(False) self.window.set_exclusive_mouse(True) self.current_screen.register(self.receive_events) self.stack.append(self.current_screen) def input_to_client(self): pass
# #class FlowerItem(FallingItem): # surf = flowerSurfaceObj # def giveBonus(self,p): # p.addScore(50) # #soundPickup.play() # #class FlowerStalkItem(FallingItem): # surf = flowerstalkSurfaceObj # def giveBonus(self,p): # p.addScore(25) # #soundPickup.play() # while True: g = Game() gs = GameScreen(g, windowSurfaceObj) gs.showTitleScreen() while (not g.isGameOver): g.update(fpsClock.tick_busy_loop()) gs.render() pygame.display.flip() gs.showGameOverScreen()
class Game(object): # game object, controls rendering game and moving player def __init__(self): self.screen = GameScreen() self.bg = pygame.image.load(IMG_DIR + 'background.png') death_sound = pygame.mixer.Sound(SFX_DIR + 'death.ogg') self.inventory = Inventory() self.map = Map() self.map.player = (1*TILE_SIZE, 1*TILE_SIZE) self.player_stats = Player() treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.clock = pygame.time.Clock() self.direction = 0 self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map) self.run() def add_treasure(self, treasure): text = 'You found a %s. %s' % (treasure.title, treasure.description) self.inventory.add_to_inventory(treasure, self.player_stats) self.screen.draw_alert(text) def move(self, hor, vert): # given keypress, moves player # also checks for fight or treasure pick-up self.old_row, self.old_col = self.map.player row = self.old_row + hor col = self.old_col + vert if row > (ROWS-1)*TILE_SIZE or row < 0 or col > (COLUMNS-1)*TILE_SIZE or col < 0: return if self.map.has_wall(row, col): return if self.map.has_monster(row, col): Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]).fight() if self.map.monsters[row/TILE_SIZE][col/TILE_SIZE].current_hp <= 0: Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]).award_exp() Combat(self.player_stats, self.map.monsters[row/TILE_SIZE][col/TILE_SIZE]).death_note(self.map.monsters[row/TILE_SIZE][col/TILE_SIZE].stats['Death Note']) self.map.monsters[row/TILE_SIZE][col/TILE_SIZE] = 0 if self.player_stats.current_hp <= 0: death_sound.play() self.end_game() self.move(0, 0) return self.map.player = (row, col) self.map.player = (row, col) self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.screen.draw_inventory(self.inventory) self.screen.draw_equipment(self.player_stats.equipped) def refresh_screen(self): self.screen.draw_player(self.map.player) self.screen.draw_screen_layers(self.map, self.player_stats) def end_game(self): # exit screen for when player has died or won self.terminate() def run(self): # event handler hor = 0 vert = 0 hard_music = 0 while hard_music == 0: self.begin_music() hard_music = 1 while 1: self.clock.tick(30) for event in pygame.event.get(): if not hasattr(event, 'key'): continue if event.type == KEYDOWN: if event.key == K_ESCAPE: self.terminate() if event.key == K_LEFT: hor = -TILE_SIZE vert = 0 if event.key == K_RIGHT: hor = TILE_SIZE vert = 0 if event.key == K_UP: vert = -TILE_SIZE hor = 0 if event.key == K_DOWN: vert = TILE_SIZE hor = 0 if event.type == KEYUP: self.map.move_monsters() self.move(hor, vert) hor = 0 vert = 0 self.refresh_screen() def terminate(self): pygame.quit() sys.exit() def begin_music(self): pygame.mixer.init(22050, -8, 4, 4096) pygame.mixer.music.load(SFX_DIR + 'Raver.flac') pygame.mixer.music.play(-1, 0.0)
class Game(object): def __init__(self): #initialize GameScreen self.gamescreen = GameScreen() all_sprite_list = pygame.sprite.Group() wall_list = pygame.sprite.Group() myWall = Wall(0, 0, 10, 600) self.gamescreen.drawWall(myWall) self.runGame() def runGame(self): moveLeft = False moveRight = False moveUp = False moveDown = False gameOverMode = False cameraX = 0 cameraY = 0 heroImg = IMG_HERO_D heroObj = {'surf' : heroImg, 'x' : START_X, 'y' : START_Y, 'health' : MAXHEALTH} # main game loop while True: # draw background here prevents sprite duplication self.gamescreen.drawBackground() heroX = heroObj['x'] heroY = heroObj['y'] if (cameraX + START_X) - heroX > CAMERASLACK: cameraX = heroX + CAMERASLACK - START_X #cameraX = heroX - START_X elif heroX - (cameraX + START_X) > CAMERASLACK: cameraX = heroX - CAMERASLACK - START_X if (cameraY + START_Y) - heroY > CAMERASLACK: cameraY = heroY + CAMERASLACK - START_Y elif heroY - (cameraY + START_Y) > CAMERASLACK: cameraY = heroY - CAMERASLACK - START_Y self.gamescreen.drawCamera(cameraX, cameraY) for event in pygame.event.get(): if event.type == QUIT: self.endGame() elif event.type == KEYDOWN: if event.key in (K_UP, K_w) : #setting other directions to False #gets rid of the diagonal issue moveDown = False moveUp = True moveLeft = False moveRight = False elif event.key in (K_DOWN, K_s): moveUp = False moveDown = True moveLeft = False moveRight = False elif event.key in (K_LEFT, K_a): moveRight = False moveLeft = True moveUp = False moveDown = False elif event.key in (K_RIGHT, K_d): moveLeft = False moveRight = True moveUp = False moveDown = False elif event.type == KEYUP: if event.key in (K_LEFT, K_a): moveLeft = False elif event.key in (K_RIGHT, K_d): moveRight = False elif event.key in (K_UP, K_w): moveUp = False elif event.key in (K_DOWN, K_s): moveDown = False elif event.key == K_ESCAPE: self.endGame() if not gameOverMode: if moveLeft: heroObj['x'] -= MOVERATE self.gamescreen.heroWalk((heroObj['x'], heroObj['y']), IMG_HERO_L1) if moveRight: heroObj['x'] += MOVERATE self.gamescreen.heroWalk((heroObj['x'], heroObj['y']), IMG_HERO_R1) if moveUp: heroObj['y'] -= MOVERATE self.gamescreen.heroWalk((heroObj['x'], heroObj['y']), IMG_HERO_U1) if moveDown: heroObj['y'] += MOVERATE self.gamescreen.heroWalk((heroObj['x'], heroObj['y']), IMG_HERO_D) def endGame(self): pygame.quit() sys.exit(0)
class Game(object): ''' The game object. Controls rendering the game and moving the player. ''' def __init__(self): ''' Sets up the initial game board, with the player at a set position. Once everything is set up, starts the game. ''' # Set up the screen self.screen = GameScreen() self.bg = pygame.image.load(IMG_DIR + 'rainbowbg.png') # Set up some game components self.inventory = Inventory() self.map = Map() self.map.player = (1 * TILE_SIZE, 1 * TILE_SIZE) self.player_stats = Player() treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.clock = pygame.time.Clock() self.direction = 0 self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) self.screen.draw_screen_layers(player_stats=self.player_stats, map=self.map) self.run() def add_treasure(self, treasure): ''' Adds the treasure to the player's inventory ''' text = "You found a %s. %s" % (treasure.title, treasure.description) self.inventory.add_to_inventory(treasure, self.player_stats) self.screen.draw_alert(text) def move(self, hor, vert): ''' Moves the player, given a keypress. Also evaluates if the player needs to fight or pick up some treasure. ''' self.old_row, self.old_col = self.map.player row = self.old_row + hor col = self.old_col + vert if row > (ROWS - 1) * TILE_SIZE or row < 0 or col > ( COLUMNS - 1) * TILE_SIZE or col < 0: return if self.map.has_wall(row, col): return if self.map.has_monster(row, col): Combat(self.player_stats, self.map.monsters[row / TILE_SIZE][col / TILE_SIZE]) if self.map.monsters[row / TILE_SIZE][col / TILE_SIZE].current_hp <= 0: pass #put death throes here if self.player_stats.current_hp <= 0: self.end_game() self.move(0, 0) return self.map.player = (row, col) self.map.player = (row, col) self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.screen.draw_inventory(self.inventory) self.screen.draw_equipment(self.player_stats.equipped) def refresh_screen(self): self.screen.draw_player(self.map.player) self.screen.draw_screen_layers(self.map, self.player_stats) def end_game(self): ''' The exit screen for when the player has died, or completed the game. So far, all it does is exit the game. ''' sys.exit() def run(self): ''' The main loop of the game. ''' # Fix for double move from Joshua Grigonis! Thanks! hor = 0 vert = 0 while 1: self.clock.tick(30) for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit(0) if event.key == K_LEFT: hor = -TILE_SIZE vert = 0 if event.key == K_RIGHT: hor = TILE_SIZE vert = 0 if event.key == K_UP: vert = -TILE_SIZE hor = 0 if event.key == K_DOWN: vert = TILE_SIZE hor = 0 if event.type == KEYUP: # updates only occur is player has moved. if vert or hor: self.move(hor, vert) self.map.move_monsters() hor = 0 vert = 0 self.refresh_screen()