def __init__(self, game: Game, process, owner): Gun.__init__( self, game, process, game.getTextureManager().getAnimationPack( AnimationPackInfo.POWERGUN_BULLET_ANIMATION), createRectangleBodyTemplate(b2_dynamicBody, 30, 30, gravityScale=0), game.getTextureManager().getAnimationPack( AnimationPackInfo.POWERGUN_ANIMATION), { "bulletSpeed": 80, "bulletType": "TwoDirectionExplode", "bulletPower": 30, "ExplodeTime": 0.4, "ExplodeDamage": 2, "ExplodeSize": 65, "ExplodeAnimation": game.getTextureManager().getAnimationPack( AnimationPackInfo.POWER_EXPLODE_BULLET_ANIMATION) }, owner, "Player", POWER_AMMO) self.cooldown = 1
def threaded(conn, addr): try: with conn: num_wins = 0 for i in range(NUM_GAMES): # TODO: Doc game = Game(SemiRandomAgent, HumanAgent) try: try: winner = Game.play_game(game, conn, addr) if winner >= 0: num_wins += 1 print('{}:{} : {}/{}'.format(addr[0], addr[1], num_wins, NUM_GAMES)) conn.sendall(encoded('{}/{}'.format(num_wins, i + 1))) except InvalidActionError: print('{}:{} : Invalid action'.format( addr[0], addr[1])) conn.sendall(encoded('Invalid action !')) break except ConnectionResetError: print('{}:{} : Connection Reset'.format(addr[0], addr[1])) break if num_wins > WIN_FLAG: conn.sendall(encoded(FLAG)) else: conn.sendall(encoded('No flag for you !')) except socket.timeout: print('{}:{} : Socket timeout'.format(addr[0], addr[1])) except: e = sys.exc_info()[0] print(e, 'happened') exit()
def run_random_vs_random_max(): winners = [] board_length = 8 action_space = (board_length, board_length, board_length, board_length) agent_one = RandomAgentWithMaxValue((board_length, board_length), action_space, "One", "up") agent_two = RandomAgent((board_length, board_length), action_space, "Two", "down") iterations = 1000 for i in range(iterations): board = Board(board_length=8) game = Game(agent_one=agent_one, agent_two=agent_two, board=board) game.play(verbose=False) winners += [game.winner] if (i % 5000 == 0 and i > 0) or iterations - 1 == i: victories_player_two = 0 victories_player_one = 0 for winner in winners: if winner == "One": victories_player_one += 1 if winner == "Two": victories_player_two += 1 logging.info("Player One: {}".format(str(victories_player_one))) logging.info("Player Two: {}".format(str(victories_player_two))) logging.info("Mean Rewards Agent One: {}".format( agent_one.moving_average_rewards[-1])) logging.info("Mean Rewards Agent Two: {}".format( agent_two.moving_average_rewards[-1])) #
def run_sarsa_vs_qlearning(): winners = [] board_length = 8 action_space = (board_length, board_length, board_length, board_length) agent_one = QLearningAgent((board_length, board_length), action_space, "qlearning", "up", 0.0, 250000000, 10000000) agent_two = SARSAAgent((board_length, board_length), action_space, "sarsa", "down", 0.0, 25000000, 10000000) iterations = 10000 for i in range(iterations): board = Board(board_length=8) game = Game(agent_one=agent_one, agent_two=agent_two, board=board) game.play(verbose=False) winners += [game.winner] agent_one.epsilon *= 0.9999 agent_two.epsilon *= 0.9999 if (i % 5000 == 0 and i > 0) or iterations - 1 == i: victories_player_two = 0 victories_player_one = 0 for winner in winners: if winner == "qlearning": victories_player_one += 1 if winner == "sarsa": victories_player_two += 1 logging.info("Player One: {}".format(str(victories_player_one))) logging.info("Player Two: {}".format(str(victories_player_two))) logging.info("Mean Rewards Agent One: {}".format( agent_one.moving_average_rewards[-1])) logging.info("Mean Rewards Agent Two: {}".format( agent_two.moving_average_rewards[-1]))
def run_a2c_vs_random(): winners = [] board_length = 8 action_space = (board_length, board_length, board_length, board_length) agent_one = A2C((board_length, board_length), action_space, "a3c", "up", 1.0, 2000, 100000) agent_two = RandomAgent((board_length, board_length), (board_length, board_length), "Two", "down") iterations = 200000 for i in range(iterations): board = Board(board_length=8) game = Game(agent_one=agent_one, agent_two=agent_two, board=board) game.play(verbose=False) winners += [game.winner] agent_one.epsilon *= 0.99999 if (i % 5000 == 0 and i > 0) or (iterations - 1 == i): victories_player_two = 0 victories_player_one = 0 for winner in winners: if winner == "a3c": victories_player_one += 1 if winner == "Two": victories_player_two += 1 logging.info("Current epsilon: {}".format(agent_one.epsilon)) logging.info("Player One: {}".format(str(victories_player_one))) logging.info("Player Two: {}".format(str(victories_player_two))) logging.info("Mean Rewards Agent One: {}".format( agent_one.moving_average_rewards[-1])) logging.info("Mean Rewards Agent Two: {}".format( agent_two.moving_average_rewards[-1]))
def start_game_auto(colors: int, layers: int, solver, rnd_init=None): game = Game(colors, layers, rnd_init) turn = 1 print(f"Solver '{solver.to_string()}' will try to solve the puzzle now!") while True: print(f"Turn {turn}") show_current_state(game.containers) while True: try: check_input_for_exit( "Press ENTER to continue or type 'exit' to exit") (source, dest) = solver.next_move(game.containers) print(f"Where to take from?\t{source}") print(f"Where to put to?\t{dest}") except ForceQuit: result = Status.exit break except SolverStuck: print("Solver can't find moves that would lead to a new state") result = Status.exit break result = game.next_turn(source, dest) if result != Status.impossible: break print("Impossible move") if result != Status.next: break turn = turn + 1 print("") show_current_state(game.containers) end_game(result, turn)
def __init__(self, game: Game, process, owner): Gun.__init__( self, game, process, game.getTextureManager().getAnimationPack( AnimationPackInfo.POISONGUN_BULLET_ANIMATION), createRectangleBodyTemplate(b2_dynamicBody, 10, 10), game.getTextureManager().getAnimationPack( AnimationPackInfo.POISONGUN_ANIMATION), { "bulletSpeed": 40, "bulletType": "BallisticExplode", "bulletPower": 20, "ExplodeTime": 5.0, "ExplodeDamage": 0.2, "ExplodeSize": 110, "ExplodeAnimation": game.getTextureManager().getAnimationPack( AnimationPackInfo.POISONEXPLODE_ANIMATION) }, owner, "Player", POISON_AMMO) self.cooldown = 0.7
def __init__(self, game: Game, process, x, y, player: Player): self.__animation = game.getTextureManager().getAnimation(AnimationInfo.BASE_ANIMATION) self.__animation.scale2x() self.__animation.play() self.__light = pg.transform.scale2x(game.getTextureManager().getTexture(TextureInfo.LIGHT_BASE)) self.__badBase = pg.transform.scale2x(game.getTextureManager().getTexture(TextureInfo.BAD_BASE)) self.__turnedOn = False self.__player = player self.__rect = rectFromSize(x, y, *self.__light.get_size()) self.__path = [] self.__originalPath = [] self.__movingTo = b2Vec2(0, 0) self.__pos = b2Vec2(x, y) self.__speed = BASE_SPEED self.__healCooldown = HEAL_COOLDOWN self.__sinceLastHeal = self.__healCooldown self.__ammoCooldown = AMMO_COOLDOWN self.__sinceLastAmmo = self.__ammoCooldown self.__sinceLastDisappear = 0 self.__disappearMoment = BASE_DISAPPEAR_TIME self.__appearMoment = self.__disappearMoment + BASE_APPEAR_TIME self.__lowerPlatform = BasePlatform(game, process, x, y) self.__upperPlatform = BasePlatform(game, process, x, y + self.__light.get_size()[1] - self.__lowerPlatform.getAABB().h)
def _fire(self): self.setPos() mousePos = pygame.mouse.get_pos() bullet = self.bullet bullet.move(mousePos, self.speed) Game.addSprite("bullets", bullet)
def run(self): # Main game loop while not self.done: if not self.menu.game_started: # Process events (keystrokes, mouse clicks, etc) self.done = self.menu.process_events() # Draw the current frame self.menu.display_frame(self.screen) else: if self.game == None: self.game = Game(self.menu.player_attributes) # Process events (keystrokes, mouse clicks, etc) self.done = self.game.process_events() # If game is over and players select to go to menu if self.game.menu_selected: self.game = None self.menu.return_to_player_selection() continue # # Update object positions, check for collisions self.game.run_logic() # Draw the current frame self.game.display_frame(self.screen) # Pause for the next frame self.clock.tick(FPS) # Close window and exit pygame.quit()
def fix_broken_times(err_file): with open(err_file, 'r') as f: for line in f: matches = re.findall('\([\d]+\)', line) if matches and matches != []: ids = map(lambda x: int(x.replace('(', '').replace(')', '')), matches) player_id, game_id = ids[0], ids[1] player = Player(player_id) game = Game(game_id) print( 'Calculating time on court for {} ({}) in {} ({})'.format( player, player.id, game, game.id)) time_on_court = player.time_on_court(game, recompute=True) computed_minutes = compute_ts_length(time_on_court, unit='minutes') boxscore_minutes = game.player_boxscore( player)['totalSecondsPlayed'] / 60.0 if not abs(computed_minutes - boxscore_minutes) <= 1.0: print('In computing playing time for {} ({}) in {} ({}):'. format(player, player.id, game, game.id), file=sys.stderr) print( 'Discrepancy between computed time: {0:2.2f}, and boxscore time: {1:2.2f}' .format(computed_minutes, boxscore_minutes), file=sys.stderr) else: print('{} played {} minutes in {}'.format( player, round(computed_minutes, 3), game))
def fix_broken_times_json(err_file): data = json.load(open(err_file, 'r')) fixes = data['fixes'] for fix in fixes: game_id = fix['game_id'] game = Game(game_id) player_id = fix['player_id'] player = Player(player_id) time_data = [(dt.timedelta(seconds=t['start']), dt.timedelta(seconds=t['end'])) for t in fix['times']] print('Updating playing time for {} ({}) in {} ({})'.format( player, player.id, game, game.id)) player.save_timestream(game, time_data) #print(compute_ts_length(time_data, unit='minutes')) boxscore_minutes = game.player_boxscore( player)['total_seconds_played'] / 60.0 computed_minutes = compute_ts_length(player.time_on_court( game, recompute=False), unit='minutes') if not abs(computed_minutes - boxscore_minutes) <= 0.5: err = colored( 'Discrepancy between computed time: {0: 2.2f} and boxscore time: {1:2.2f}' .format(computed_minutes, boxscore_minutes), 'red') print(err) else: print('{} played {} minutes in {}'.format( player, round(computed_minutes, 3), game))
def run(self): run = True while run: for event in pygame.event.get(): # Izhod iz programa, če pritisnemo križec if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONUP: # check if hit start btn x, y = pygame.mouse.get_pos() if self.btn[0] <= x <= self.btn[0] + self.btn[2]: if self.btn[1] <= y <= self.btn[1] + self.btn[3]: igralec = Login(self.win).run() game = Game(self.win, 0, self.music, self.sound, igralec) game.run() if self.music: self.play() if x > 50 and x < 200 and y > 50 and y < 200: if self.music: pygame.mixer.music.pause() else: pygame.mixer.music.unpause() if not pygame.mixer.get_busy(): self.play() self.music = not self.music if x > 250 and x < 400 and y > 50 and y < 200: self.sound = not self.sound if event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() if x > 1200 and x < 1350 and y > 50 and y < 200: LeaderBoard(self.win).run() self.draw()
def __init__(self, game: Game, process, owner): Gun.__init__( self, game, process, game.getTextureManager().getAnimationPack( AnimationPackInfo.GRAVITYGUN_BULLET_ANIMATION), createRectangleBodyTemplate(b2_dynamicBody, 1, 1, gravityScale=0), game.getTextureManager().getAnimationPack( AnimationPackInfo.GRAVITYGUN_ANIMATION), { "bulletSpeed": 80, "bulletType": "Gravity", "bulletPower": 0, "ExplodeTime": 0.2, "ExplodeDamage": 0, "ExplodeSize": 150, "ExplodeAnimation": game.getTextureManager().getAnimationPack( AnimationPackInfo.GRAVITY_EXPLODE_BULLET_ANIMATION) }, owner, "Player", GRAVI_AMMO) self.cooldown = 0.5
def __init__(self): super().__init__(width=Gui.WINDOW_WIDTH, height=Gui.WINDOW_HEIGHT) self.__game = Game(Gui.BOARD_SIZE, Gui.BOARD_SIZE) self.__gui = DrawChess(self.__game.board_size(), self.WHITE_PIECE_COLOR, self.BLACK_PIECE_COLOR, self.WHITE_TILE_COLOR, self.BLACK_TILE_COLOR, self.CAPTURE_COLOR, self.TILE_SIZE, self.PIECE_SIZE, self.CAPTURE_PIECE, self.CAPTURE_SIZE, self.width, self.height) self.__current_pos = None
def predict(self, game: Game, player: Player): actions = [] e_x, e_y = game.get_closest_enemy_location(player.location[0], player.location[1], player.team_id) actions.append((ATTACK_CLOSEST_TARGET, self.distance((e_x, e_y), player.location))) r_x, r_y = game.get_nearest_resource_index(player.location[0], player.location[1]) actions.append((HARVEST_CLOSEST_RESOURCE, self.distance((r_x, r_y), player.location))) b_x, b_y = game.get_enemy_base(player.team_id) actions.append((ATTACK_BASE, self.distance((b_x, b_y), player.location))) return min(actions, key=lambda x: x[1])[0]
def test_game_update(self): game = Game() game.world.update = MagicMock() game.player.update = MagicMock() game.update(dt=1) game.world.update.assert_called_once_with(dt=1) game.player.update.assert_called_once_with(dt=1)
def __init__(self, game: Game, process, owner): Gun.__init__( self, game, process, game.getTextureManager().getAnimationPack( AnimationPackInfo.BALLISTICGUN_BULLET_ANIMATION), createRectangleBodyTemplate(b2_dynamicBody, 10, 10), game.getTextureManager().getAnimationPack( AnimationPackInfo.BALLISTICGUN_ANIMATION), { "bulletSpeed": 40, "bulletType": "Ballistic", "bulletPower": 20 }, owner, "Enemy", 1000_000) self.cooldown = 0.7
class LightBike(object): def __init__(self): pygame.init() size = [SCREEN_WIDTH, SCREEN_HEIGHT] self.screen = pygame.display.set_mode(size) pygame.display.set_caption("Light Bike") pygame.mouse.set_visible(True) # Create our objects and set the data self.done = False self.clock = pygame.time.Clock() self.game = None self.menu = Menu() def run(self): # Main game loop while not self.done: if not self.menu.game_started: # Process events (keystrokes, mouse clicks, etc) self.done = self.menu.process_events() # Draw the current frame self.menu.display_frame(self.screen) else: if self.game == None: self.game = Game(self.menu.player_attributes) # Process events (keystrokes, mouse clicks, etc) self.done = self.game.process_events() # If game is over and players select to go to menu if self.game.menu_selected: self.game = None self.menu.return_to_player_selection() continue # # Update object positions, check for collisions self.game.run_logic() # Draw the current frame self.game.display_frame(self.screen) # Pause for the next frame self.clock.tick(FPS) # Close window and exit pygame.quit()
def __init__(self, game: Game, process, owner): Gun.__init__( self, game, process, game.getTextureManager().getAnimationPack( AnimationPackInfo.BIG_ENEMY_BULLET_ANIMATION), createRectangleBodyTemplate(b2_dynamicBody, 40, 40, gravityScale=0), game.getTextureManager().getAnimationPack( AnimationPackInfo.BIG_ENEMY_GUN_ANIMATION), { "bulletSpeed": 80, "bulletType": "AllDirection", "bulletPower": 5 }, owner, "BigEnemy", 1000_000) self.cooldown = 0
def __init__(self, game: Game, process, x: float, y: float, width: float, height: float): # process: GameProcess Platform.__init__( self, game, process, game.getTextureManager().getAnimationPack( AnimationPackInfo.PLATFORM_ANIMATION), x, y, width, height)
def __init__(self, game: Game): self.__world = b2World((0, -100)) self.__contactListener = ContactListener() self.__world.contactListener = self.__contactListener self.__factory = BodyFactory(self.__world) self.__background = pg.transform.scale( game.getTextureManager().getTexture(TextureInfo.BACKGROUND), WINDOW_RESOLUTION) self.__game = game self.__events = [] self.__justCreatedObjects = set() self.__removedObjects = set() self.__objects = set() self.__cameraRect = rectFromSize(0, -WINDOW_RESOLUTION[1], *WINDOW_RESOLUTION) self.__player = Player(game, self, GunsList(game, (20, 20))) self.addObject(self.__player) self.__base = Base(game, self, *BASE_START_POS, self.__player) self.__builder = Builder(game) self.__builder.build(self, self.__player, self.__base, "L1") pg.mixer.music.load(_createPath('music', 'fight.mp3')) pg.mixer.music.play()
def __init__(self, game: Game, pos: tuple): self.__background = pg.transform.scale2x(game.getTextureManager().getTexture(TextureInfo.GUNS_BACKGROUND)) self.__pos = pos self.__guns = [game.getTextureManager().getTexture(info) for info in (TextureInfo.GUN1, TextureInfo.GUN2, TextureInfo.GUN3)] self.__detGuns = [game.getTextureManager().getTexture(info) for info in (TextureInfo.DETALIZED_GUN1, TextureInfo.DETALIZED_GUN2, TextureInfo.DETALIZED_GUN3)] self.__numbers = list(map(pg.transform.scale2x, game.getTextureManager().getNumbers())) self.__i = 0 self.__guns = list(map(pg.transform.scale2x, self.__guns)) self.__detGuns = list(map(pg.transform.scale2x, self.__detGuns))
def moveSneak(self): dimensions = Game.getDimensions() if self.move_x < 0 and self.pos[0] > 0: self.pos[0] -= self.sneak_speed elif self.move_x > 0 and self.pos[0] < (dimensions[0] - self.src_width): self.pos[0] += self.sneak_speed
def update_game_times(): games = pbp.find({}) for game in games: game_obj = Game(game['id']) game['game_date'] = game_obj.date # print('updating game {} on {}'.format(game_obj.id, game_obj.date)) pbp.update({'id': game_obj.id}, game)
class GameTest(TestCase): def setUp(self): self.game = Game(1349077) def test_get_team_stats_by_time(self): team = Team(12) players = [Player(399725), Player(3085)] timestream = self.game.multiple_player_overlap(players)[0] stats = self.game.team_stats_by_time(team, timestream) pprint(stats.__dict__) self.assertEqual(stats.assists, 13) self.assertEqual(stats.field_goals_attempted, 40) self.assertEqual(stats.field_goals_made, 18)
def run_worker(): while True: # get the next game (botSpecs, gameType, matchId) = pollUntilGameReady() bots = [] # create a bot object for each bot that's in this match for b in botSpecs: bots.append( DockerBot(b['id'], b['index'], b['url'], b.get('params', {}))) game = Game(bots) try: # we'll need more than just a log at some point # should probably return a tuple of log and results, which would contain # flags/info on game termination (timeout, completion, bot error, etc.) game.start() print("Got results.") # send the results back to the server post_match_results(matchId, game.get_log()) except Exception as err: print("GAME ERR") print(err) for p in game.players: if not p.bot.is_running(): p.crashed = True game.rank_players() game.log_winner() post_match_results(matchId, game.get_log()) # TODO handle if no bot crashed, meaning the error was ours try: for b in bots: b.cleanup() except Exception as err: print("Issue cleaning up.") print(err) print("Done cleaning up.")
def moveX(self): dimensions = Game.getDimensions() if self.pos[0] >= 0 and self.move_x < 0: if self.location.againstTerrainRight(self) == False: self.pos[0] += self.move_x elif self.pos[0] <= (dimensions[0] - self.src_width) and self.move_x > 0: if self.location.againstTerrainLeft(self) == False: self.pos[0] += self.move_x
def buildLevel(self): dimensions = Game.getDefaultDimensions() platform1_pos = (50, dimensions[1] - 100) platform1 = Platform(self, platform1_pos, self.random_colour, 400, 50) room = Room(self, (self.dimensions[0] / 4, self.dimensions[1] / 3 + 100), (400,200), (10,10,30,10), True, False) room.buildFloor((255,255,255)) room.buildWalls((255,0,0), (0,255,0)) room.buildCeiling((0,0,255))
def __init__(self, location, pos, src, width, height): '''first parameter can be colour or image''' super(Terrain, self).__init__() self.pos = pos self.width = width self.height = height self.src = src self.image = pygame.Surface([self.width, self.height]) if not isinstance(src, basestring): self.image.fill(src) self.rect = self.image.get_rect() Game.addSprite('terrain', self) location.terrain.append(self)
def game(): # show layout ConsoleView.render_board() # run game logic game_logic = Game() while True: # toggle side game_logic.toggle_side() # display who's turn is side = game_logic.get_current_side() ConsoleView.display_game_side(side) # ask for input field = ConsoleView.get_field() # main game loop while True: # check if value is proper & field is not occupied move_allowed, error = game_logic.is_move_allowed(field) if move_allowed: break else: ConsoleView.display_error_msg(error) # ask for input field = ConsoleView.get_field() # add move game_logic.add_move(field) # check if game finished game_finished, result = game_logic.is_game_finished() # display game board move_dict = game_logic.get_moves_dict() ConsoleView.update_layout(move_dict) if game_finished: ConsoleView.display_result(result) break print("ENDGAME")
def run(): # Initialize the game game = Game() # Build model model = build_model(game) # Train model qtrain(model, game, epochs=15000, max_memory=8*game.size, data_size=64, weights_file='')
def compare_to_odds(predictions, odds): wins = 0 losses = 0 ties = 0 index = predictions.game_id.values results = pd.Series(index=index) cover = pd.Series(index=index) for game_id in predictions.game_id: odds_pred = odds[odds.game_id == game_id] my_pred = predictions[predictions.game_id == game_id] #print my_pred #print odds_pred.empty if not odds_pred.empty: line = odds_pred.spread.values[0] pred_margin = my_pred.prediction.values[0] margin = my_pred.actual_margin.values[0] game = Game(game_id) #print game_id, pred_margin, line if pred_margin - line >= 0: # I have picked home cover[game_id] = 'H' if game.home_points > game.away_points + line: status = 'W' wins += 1 elif game.home_points == game.away_points + line: status = 'T' ties += 1 elif game.home_points < game.away_points + line: status = 'L' losses += 1 elif pred_margin - line < 0: # I have picked away cover[game_id] = 'A' if game.home_points < game.away_points + line: status = 'W' wins += 1 elif game.home_points == game.away_points + line: status = 'T' ties += 1 elif game.home_points > game.away_points + line: status = 'L' losses += 1 #elif pred_margin - line == 0: results[game_id] = status #print game, game_id #print 'line: {: 2.1f}'.format(line), 'predicted: {: 2.1f}'.format(pred_margin), 'actual: {: 2.1f}'.format(margin), status return (wins, ties, losses, cover, results)
def run(): sdl2.ext.init() window = sdl2.ext.Window("Snake", size=(configuration.window_width, configuration.window_height)) world = sdl2.ext.World() window.show() curr = Game(window, world) running = True while running: events = sdl2.ext.get_events() for event in events: if event.type == sdl2.SDL_QUIT: running = False break curr.handle_event(event) world.process() if curr.game_state.game_over is True: curr.clean_up() curr = Game(window, world) return 0
def fire(self): self.setPos() mousePos = pygame.mouse.get_pos() bullet = BaseBullet(self.pos) bullet.move(mousePos, self.speed) Game.addSprite("bullets", bullet)
music.append( pygame.mixer.Sound( "sounds/music-3.wav" ) ) music_track = 0 music[music_track].play( ) music_length = music[music_track].get_length( ) music_length_played = 0.0 music_start_time = 0 # Start game Game.screen_width = screen_width Game.screen_height = screen_height Game.screen_move_x = Game.screen_width / 2.2 Game.addSpriteGroup( "background" ) Game.addSpriteGroup( "world" ) Game.addSpriteGroup( "tiny-worlds" ) Game.addSpriteGroup( "enemies" ) Game.addSpriteGroup( "player" ) Game.addSpriteGroup( "player-weapon" ) Game.addSpriteGroup( "player-paint" ) game_start_text1 = BitmapText( font_2, [(Game.screen_width / 2)-300, 50] ) game_start_text1.setSurface( screen ) game_start_text2 = BitmapText( font_1, [(Game.screen_width / 2)-300, 100] ) game_start_text2.setSurface( screen ) game_start_text3 = BitmapText( font_1, [(Game.screen_width / 2)-300, 260] ) game_start_text3.setSurface( screen ) score_text = BitmapText( font_1, [20, 20] )
def __init__(self): dimensions = Game.getDefaultDimensions() pos = (dimensions[0] / 2, dimensions[1] / 2) super(Background, self).__init__("world/background.png", pos) Game.addSprite("world", self)
# Check if Windows and import pygame._view if so from sys import platform as _platform #if _platform == "win32" or _platform == "cygwin": # import pygame._view # Initialise pygame library pygame.init() # Import game files from game.Game import Game from game.character.Player import Player from game.mechanics.Crosshair import Crosshair from game.world.Background import Background # Setup screen size = Game.getDefaultDimensions() screen = pygame.display.set_mode(size) pygame.display.set_caption(project_title) screen.convert() # Run game Game.addSpriteGroup("world") Game.addSpriteGroup("player") Game.addSpriteGroup("bullets") Game.addSpriteGroup("enemies") Game.addSpriteGroup("terrain") background = Background() player = Player() crosshair = Crosshair()
def __init__(self): super(Player, self).__init__("player.png", [300, 200]) self.weapon = Pistol(self) dimensions = Game.getDefaultDimensions() self.ground_level = dimensions[1] - 100 Game.addSprite("player", self)
def __init__(self, maxScore = 25): Game.__init__(self) self.scores = [0, 0] self.maxScore = 25
parser.add_argument('--plot-results', default=False, action='store_true', help='Plot the results with numpy') parser.add_argument('--no-multi-process', default=False, action='store_true', help='Disable multiprocessing on all cores') parser.add_argument('--version', action='version', version='%%(prog)s v%s' % VERSION) args = parser.parse_args() dist = __import__("distributors.%s" % args.distributor, fromlist=[args.distributor]) dist = getattr(dist, args.distributor) strategy = __import__("strategies.%s" % args.strategy, fromlist=[args.strategy]) strategy = getattr(strategy, args.strategy) g = Game(dist, strategy, args.width, args.height, args.ships) if args.print_game: g.prepare() g.play() print g elif args.animate_game: g.prepare() try: g.play(True, args.steps) except KeyboardInterrupt: pass else: s = Statistics(g) t = time()
""" A main script @version: 0.1 @author: quenti77 """ import pygame from game.Game import Game if __name__ == "__main__": game = Game() game.play()
def dimensions(self): return Game.getDimensions()
def __init__(self): super(Player, self).__init__("player.png", [300, 200]) self.weapon = Pistol(self) self.location = BaseLocation(self) dimensions = Game.getDefaultDimensions() Game.addSprite("player", self)
def __init__(self): super(Player, self).__init__("sprites/test.png", [300, 200]) Game.addSprite("player", self)