def _reset(self): K.clear_session() self.AI = [AI(self.cv, self.cg), AI(self.cv, max(self.cg - 1, 0))] self._library = Library() self._board = Board() self._player1 = Player("A") self._player2 = Player("B") self._players = [self._player1, self._player2] self._scores = [Score(), Score()] self._turn_side = random.randint(0, 1) # if 0, player 1 starts first if self._is_user: if self._turn_side == 0: print("Player First") else: print("Player Second") self._library.shuffle() for i in range(10): self._player1.draw(self._library.draw()) self._player2.draw(self._library.draw()) for i in range(8): self._board.put(self._library.draw()) if self._is_user: print(self)
def test_payAll_two(): game = Game() game.setPlayers([Player(),Player(),Player()]) game.payAll(0,50) assert game.getPlayer(0).getMoney() == -100 assert game.getPlayer(1).getMoney() == 50 assert game.getPlayer(2).getMoney() == 50
def test_game_over_true(): game = Game() game.setPlayers([Player(),Player()]) a = game.getPlayers() a[1].setAlive(False) game.checkGameOver() assert game.getGameOver() == True
def __init__(self, screen, brain, extra_ast): game_folder = os.path.dirname(__file__) img_folder = os.path.join(game_folder, 'sprites') self.bg = pg.image.load(os.path.join(img_folder, 'Space_Stars4.png')) self.bullet_img = pg.image.load(os.path.join(img_folder, 'bullet.png')) self.ast_imgs = [pg.image.load(os.path.join(img_folder, 'ast1.png'))] self.player_img = pg.image.load(os.path.join(img_folder, 'tile010.png')) self.player = Player(300, 200, self.player_img, brain) self.screen = screen self.bullets = pg.sprite.Group() self.asteroids = pg.sprite.Group() self.player_group = pg.sprite.Group() self.player_group.add(self.player) self.cooldown = 0 self.grid = Grid(RESOLUTION[0], RESOLUTION[1], 128) self.grid.insert(self.player, self.player.rect.center[0], self.player.rect.center[1]) self.displaying = False self.net_renderer = NetworkRenderer(self.screen) self.time = 0 self.bounty_timer = 20 self.extra_asteroids = extra_ast
def test_collect_all(): game = Game() game.setPlayers([Player(),Player(),Player()]) game.collectAll(0,50) assert game.getPlayer(0).getMoney() == 100 assert game.getPlayer(1).getMoney() == -50 assert game.getPlayer(2).getMoney() == -50
def __init__(self, number_cards=10): # creates a new deck game_deck = DeckOfCards() self.player_1 = Player("Dolev") self.player_2 = Player("Shay") self.game_deck = game_deck.lst_cards self.number_cards = number_cards self.new_game()
def __init__(self): # Enumerate all possible 3 in a row positions self.win_positions = [[0, 4, 8], [2, 4, 6], [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8]] self.board = Board() self.human = Player() self.bot = Player(True) self.opening_move = True
def __init__(self, maze): """ Constructor of the class Game with arguments: - the maze, by loading it from its filename - the palyer that starts at position 0,0 """ self.maze = maze # the maze x, y = self.maze.start_position # the start position to set the player self.player = Player(x, y) # the class of the player
def __init__(self): self.Players = [Player('Player1', 0), Player('Player2', 1)] self.Players[0].OpPlayer = self.Players[1] self.Players[1].OpPlayer = self.Players[0] self.Players[0].ThisGame = self.Players[1].ThisGame = self self.GlobalEffect = [] self.PlayCardQueue = [] self.DayOrNight = random.choice([True, False]) self.NumberOfBoard = 0
def create_teams(): blue_players = [] yellow_players = [] for i in range(PLAYER_PER_TEAM): bPlayer = Player(i) yPlayer = Player(i) blue_players.append(bPlayer) yellow_players.append(yPlayer) blue_team = Team(blue_players, False) yellow_team = Team(yellow_players, True) return blue_team, yellow_team
def generateDefaultPlayers(self): defaultPlayers = [] redPlayer = Player("red", "R", Status.LIVE, 0, 0, None, 0, 0) bluePlayer = Player("blue", "B", Status.LIVE, 0, 7, None, 0, 0) greenPlayer = Player("green", "G", Status.LIVE, 7, 7, None, 0, 0) yellowPlayer = Player("yellow", "Y", Status.LIVE, 7, 0, None, 0, 0) defaultPlayers.extend( [redPlayer, bluePlayer, greenPlayer, yellowPlayer]) return defaultPlayers
def __init__(self, mode, playground): self.simulation = Simulation(self, mode, playground) self.camera = Camera(self, 70) self.mode = mode self.playground = playground # Players #----------------------------- 1st player ----------------------------- self.players = [] if mode == "NE" or mode == "vsNN": self.players.append(Player(self, NN_StrategyA.NN_StrategyA(), "left")) else: self.players.append(Player(self, StrategyC.StrategyC(), "left")) # self.players.append(Player(self, MovementTest.MovementTest(), "left")) #----------------------------- 2nd player ----------------------------- if not playground: if mode == "vsAI" or mode == "vsNN": self.players.append(Player(self, StrategyD.StrategyD(), "right")) # self.players.append(Player(self, MovementTest.MovementTest(), "right")) elif mode == "NE": self.players.append(Player(self, NN_StrategyA.NN_StrategyA(), "right")) else: self.players.append(Player(self, StrategyD.StrategyD(), "right")) self.players[0].opponent = self.players[1] self.players[1].opponent = self.players[0] # States self.gameDone = False self.gameTime = 0 self.gameSpeed = 1 self.scoreChangeAt = 0 self.prevScore = [0, 0] self.bestScorePlayer = -1 self.winner = -1 self.stepTime = MIN_STEP_TIME self.mousePosition = None self.leftMouseDown = False self.middleMouseDown = False self.rightMouseDown = False # Statistic data self.onSide = 0 self.maxShotSpeed = [0, 0] self.puckControl = [0, 0] self.shotOnGoals = [0, 0] self.lostPucks = [0, 0]
def new_game(self): shuffle(self.game_deck) player_1 = Player('player1') player_2 = Player('player2') player_1.set_hand() player_2.set_hand() return f"{player_1.set_hand()}"
def ename(self): name = self.playersname.get() mail = self.emailp.get() self.er.config(text="") self.mer.config(text="") if (name == ""): #מוודא שהשם לא ריק self.er.config(text='Type a Password!', fg="red") if not self.testmail(mail): #מוודא שהמייל תקין self.mer.config(text='Invalid mail!', fg="red") else: #אם כל הפרטים תקינים-מכניס לרשימה ומוחק את הפרטים מהEntry self.playersname.delete(0, 'end') self.emailp.delete(0, 'end') player = Player(name, self.money, mail) self.players.append(player) self.countp += 1 self.playersname.delete(0, 'end') if (self.countp == 5): #אם הוכנסו כבר ארבעה שחקנים-מוחק את החלון self.playersbuttun.destroy() self.playersname.destroy() self.emailp.destroy() self.labeln.destroy() self.labelm.destroy() self.er.destroy() self.mer.destroy() self.welcome.destroy() begin = game.Label(text="Now Let's start the game.") begin.grid(row=2, column=1) self.window.after(10, lambda: self.window.destroy())
def init_players(self): """ Create player objects for each player name """ for name in self.player_names: new_player = Player(name) self.players.append(new_player)
def testinit2(self): try: player = Player("Bar", 8000, -1) except: pass else: self.fail()
def testinit1(self): try: player = Player("Yossi", 500) except: pass else: self.fail()
def test_player_alive_money(): game = Game() game.setPlayers([Player()]) player = game.getPlayers()[0] player.setMoney(0) game.checkMoneyRule(player) assert player.getAlive() == False
def __init__(self, evening) -> None: super().__init__() self.active_player = None self._evening = evening self.players = [ Player(member.id, member.name) for member in self._evening.members.values() ]
def addPlayer(self): char = self.characters.getRandom_character() self.players.append( Player(self.name_entry.get(), self.game_money, char)) # self.players[len(self.players)-1].loadCharacter_picture() - For future updates self.name_entry.delete(0, 'end') if self.players_quantity == len(self.players): self.destroyWindow(self.start_screen)
def test_collectPool(): game = Game(players=[Player()]) sq = FreeParking() game.setPool(100) assert game.getPool() == 100 sq.run(0,game) assert game.getPool() == 0 assert game.getPlayer(0).getMoney() == 100
def __init__(self): self.Players = [Player('Player1', 0), Player('Player2', 1)] # [Player,Player] 玩家们 self.Players[0].OpPlayer = self.Players[1] self.Players[1].OpPlayer = self.Players[0] self.Players[0].ThisGame = self.Players[1].ThisGame = self self.GlobalEffect = [] # [Card...] 全局效果 self.PlayCardQueue = [] # [Card...] 出牌队列 self.DayOrNight = random.choice([True, False]) # 白天?晚上? self.NumberOfBoard = 0 # 场次 # server self.Host = 0 # str server host self.Port = 0 # [int,int] server port self.comServer = 0 # socket 指令服务端 self.scrServer = 0 # socket 屏显服务端 self.PComClient = [] # socket_conn 指令客户端 self.PScrClient = [] # socket_conn 屏显客户端
def run_game(): ''' Game window initialization''' pygame.init() ai_settings = Settings() pygame.mixer.init() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Arkanoid v1.0") '''create''' player = Player(ai_settings, screen) while True: gf.check_events(ai_settings, screen, player) player.update() gf.update_screen(ai_settings, screen, player)
def test_rollJail_three(): game = Game(players=[Player()]) game.setBoard([null.Null(), jail.Jail()]) rule = Rules(game, jail=3) rule.roll(0, 6, 6) rule.roll(0, 6, 6) rule.roll(0, 6, 6) assert game.getPlayer(0).getDouble() == 3 assert game.getPlayer(0).getJail() == True assert game.getPlayer(0).getPos() == 1
def __init__(self, level_options): self.level_options = level_options self.view_x = (ARENA_WIDTH - SCREEN_WIDTH) / 2 self.view_y = (ARENA_HEIGHT - SCREEN_HEIGHT) / 2 self.player = Player(self.view_x + SCREEN_WIDTH / 2, self.view_y + SCREEN_HEIGHT / 2, textureHolder, Texture.PLAYER) self.monsters = [] self.projectiles = [] self.moonwalk = False self.shoot = False self.air = [] print(self.level_options.person_name) self.generate_level()
class CardGame: def __init__(self, number_cards=10): # creates a new deck game_deck = DeckOfCards() self.player_1 = Player("Dolev") self.player_2 = Player("Shay") self.game_deck = game_deck.lst_cards self.number_cards = number_cards self.new_game() def new_game(self): # shuffels the deck and deals each player the number of decided cards shuffle(self.game_deck) self.player_1.set_hand() self.player_2.set_hand() def get_winner(self): # prints the player with the least card. if equal,gives None if len(self.player_1.hand) > len(self.player_2.hand): return f"{self.player_2.name} won!" if len(self.player_2.hand) > len(self.player_1.hand): return f'{self.player_1.name} won!' else: return None
def test_just_visiting(): """" Handles test case of landing on the jail/just visting """ sq = Jail() p = Player() game = Game(players=[p]) old = game.getPlayers() sq.run(0, game) ran = game.getPlayers() #current player and all players assert old == ran
def __init__(self, player_names, n_decks): """ Initialize a blackjack player Args: :List player_names: Names of participants in the blackjack game. :Int n_decks: Number of decks cards are drawn from (Standard games include 1-8 decks). """ self.player_names = player_names # People playing the game self.players = [] self.init_players() # Dealer hand self.dealer = Player("Dealer") # Initialize a deck containing n_decks standard 52 card decks. self.deck = BlackjackDeck(n_decks) # Start the blackjack game self.run_game()
def join_game(self, message): response = {'type': 'set_username'} if len(self.players) == 4: # Prevent user from connecting response['freeSeats'] = False self.writer.sendMessage(response) self.writer.closeConnection() else: self.players.append(Player(message['user'])) response['user'] = message['user'] response['message'] = "Connected" response['time'] = datetime.datetime.now().strftime('[%H:%M:%S]') response['freeSeats'] = True self.writer.emitMessage(response) if len(self.players) == 4: self.start_game()
def __ExecuteBattle(self): # Get the century period = self._gameSettings.Get_I(category='Period') # Define the player data data = PlayerDataFromXML(self._gameSettings) # Define the game controller game = Player(data) game.SetTimePeriod(period) # Some internal default values (dont worry know about them, there are just for historical reasons) game.SetLoopsForEachTest(2) game.SetMaxCastleEvolutions(5) game.SetVerboseLevel(VERBOSE_RESULT) # Start the simulation game.Play(speed=SETTINGS.Get_I(category='Game', tag='speed'))
class Game: def __init__(self, level_options): self.level_options = level_options self.view_x = (ARENA_WIDTH - SCREEN_WIDTH) / 2 self.view_y = (ARENA_HEIGHT - SCREEN_HEIGHT) / 2 self.player = Player(self.view_x + SCREEN_WIDTH / 2, self.view_y + SCREEN_HEIGHT / 2, textureHolder, Texture.PLAYER) self.monsters = [] self.projectiles = [] self.moonwalk = False self.shoot = False self.air = [] print(self.level_options.person_name) self.generate_level() def run(self): pygame.init() pygame.key.set_repeat(25, 25) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.DOUBLEBUF | pygame.HWSURFACE,) arena = pygame.Surface((ARENA_WIDTH, ARENA_HEIGHT), pygame.DOUBLEBUF | pygame.HWSURFACE) clock = pygame.time.Clock() pygame.mixer.music.load(MUSIC) pygame.mixer.music.play() seconds = (700 + 100 * (self.level_options.enemiesCount - 1)) / (self.player.damage * 4) * 1000 print(seconds) scoreIncrementTimer = 0 lastFrameTicks = pygame.time.get_ticks() while True: # Limit frame speed to 50 FPS time_passed = clock.tick(50) thisFrameTicks = pygame.time.get_ticks() ticksSinceLastFrame = thisFrameTicks - lastFrameTicks lastFrameTicks = thisFrameTicks scoreIncrementTimer = scoreIncrementTimer + ticksSinceLastFrame if scoreIncrementTimer > seconds: self.gen_monsters() scoreIncrementTimer = 0 # Redraw the background arena.fill(BG_COLOR) textureHolder.load(self.level_options.enumTexture, self.level_options.enumTexture.value) bg = textureHolder.get(self.level_options.enumTexture) self.background_render(bg, arena) if self.handle_user_input(): return # Update and redraw all creeps self.player.update() self.player.render(arena) if len(self.monsters) > 0: self.handle_monsters(arena) else: #TODO: win after killing all 3 waves of zombies self.game_over(screen, "You Win") return if self.player.health < 0: self.game_over(screen, "Game Over") return for bullet in self.projectiles: self.handle_bullet(bullet, arena) #print(len(self.projectiles)) self.update_view_coordinates() for cloud in self.air: cloud.update() cloud.render(arena) #Draw the view on the screen screen.blit(arena, (0, 0), pygame.Rect(self.view_x, self.view_y, SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.flip() def random_coords(self): uy = randint(0, int(self.view_y)) dy = randint(int(self.view_y) + SCREEN_HEIGHT, ARENA_HEIGHT) lx = randint(0, int(self.view_x)) rx = randint(int(self.view_x) + SCREEN_WIDTH, ARENA_WIDTH) spawn_x = choice([lx, rx]) spawn_y = choice([uy, dy]) return spawn_x, spawn_y def gen_monsters(self): for i in range(self.level_options.enemiesCount - 1): spawn_x, spawn_y = self.random_coords() monster = Enemy(spawn_x, spawn_y, textureHolder, Texture.ZOMBIE) monster.set_speed(self.level_options.enemySpeed) monster.letter = self.level_options.person_name[i] self.monsters.append(monster) def generate_level(self): self.gen_monsters() spawn_x, spawn_y = self.random_coords() monster = Enemy(spawn_x, spawn_y, textureHolder, Texture.ZOMBIE) monster.set_speed(self.level_options.enemySpeed - 0.5) #monster.set_damage(monster.damage + 50) monster.letter = self.level_options.person_name.split(" ")[0] monster.set_health(700) self.monsters.append(monster) #add trees for i in range(10): self.air.append(Entity((randint(0, SCREEN_WIDTH), randint(0, SCREEN_HEIGHT)), textureHolder, Texture.TREE2)) self.player.set_speed(self.level_options.playerSpeed) self.player.set_damage(self.level_options.damage) def exit(self): pygame.quit() def background_render(self, bg, screen): x = 0 while x < ARENA_WIDTH: y = 0 while y < ARENA_HEIGHT: screen.blit(bg, (x, y)) y += bg.get_height() x += bg.get_width() def collision_detection(self, surface_1, surface_2): if len(surface_2.walk) > 0 and len(surface_1.walk) > 0: rect1 = pygame.Rect(surface_1.pos.x, surface_1.pos.y, surface_1.walk[0].get_width(), surface_1.walk[0].get_height()) #TODO: check this walks arrays rect2 = pygame.Rect(surface_2.pos.x, surface_2.pos.y, surface_2.texture.get_width(), surface_2.walk[0].get_width()) if rect1.colliderect(rect2): return True else: return False def game_over(self, screen, text): font1 = pygame.font.Font(None, 140) text = font1.render(text, True, (0, 0, 0)) text_rect = text.get_rect() text_x = screen.get_width() / 2 - text_rect.width / 2 text_y = screen.get_height() / 2 - text_rect.height / 2 scale = 1.0/float(4) surf_size = screen.get_size() scale_size = (int(surf_size[0]*scale), int(surf_size[1]*scale)) surf = pygame.transform.smoothscale(screen, scale_size) surf = pygame.transform.smoothscale(surf, surf_size) while True: screen.blit(surf, (0,0)) screen.blit(text, [text_x, text_y]) for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit() return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.exit() return pygame.display.update() def get_min(self, collisions): d = collisions[0] min_d = collisions[0].pos.distance_to(self.player.pos) for i, c in enumerate(collisions): if c.pos.distance_to(self.player.pos) <= min_d: min_d = c.pos.distance_to(self.player.pos) d = collisions[i] return d def handle_bullet(self, bullet, screen): bullet.update() if bullet.pos.x < 0 or bullet.pos.x > ARENA_WIDTH or bullet.pos.y < 0 or bullet.pos.y > ARENA_HEIGHT: self.projectiles.remove(bullet) return collisions = [] for monster in self.monsters: if self.collision_detection(monster, bullet): collisions.append(monster) if len(collisions) > 0: m = self.get_min(collisions) m.reduce_health(self.player.damage) #monster.reduce_health(self.player.damage) if bullet in self.projectiles: self.projectiles.remove(bullet) break #print(monster.health) bullet.render( screen ) def handle_monsters(self, screen): for monster in self.monsters: monster.set_target(self.player) monster.update() monster.render(screen) if monster.health <= 0: if monster in self.monsters: self.monsters.remove(monster) def handle_user_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit() return True elif event.type == pygame.KEYDOWN: #event.key in (pygame.K_UP, pygame.K_w) if event.key == pygame.K_w: self.player.speed = self.player.default_speed if event.key == pygame.K_a: self.player.set_direction(self.player.get_orientation().rotate(-15)) if event.key == pygame.K_d: self.player.set_direction(self.player.get_orientation().rotate(15)) if event.key == pygame.K_s: if not self.moonwalk: self.player.speed = -self.player.default_speed self.player.set_direction(-self.player.direction) self.moonwalk = True if event.key == pygame.K_SPACE: if not self.shoot: self.projectiles.append(self.player.shoot()) self.shoot = True if event.key == pygame.K_ESCAPE: self.exit() return True elif event.type == pygame.KEYUP: if event.key in (pygame.K_w, pygame.K_s): self.player.speed = 0 self.moonwalk = False if event.key == pygame.K_SPACE: self.shoot = False return False def update_view_coordinates(self): if self.player.pos.x > 3/4 * SCREEN_WIDTH + self.view_x: self.view_x = self.player.pos.x - 3/4 * SCREEN_WIDTH if self.view_x > ARENA_WIDTH - SCREEN_WIDTH: self.view_x = ARENA_WIDTH - SCREEN_WIDTH if self.player.pos.x < 1/4 * SCREEN_WIDTH + self.view_x: self.view_x = self.player.pos.x - 1/4 * SCREEN_WIDTH if self.view_x < 0: self.view_x = 0 if self.player.pos.y > 3/4 * SCREEN_HEIGHT + self.view_y: self.view_y = self.player.pos.y - 3/4 * SCREEN_HEIGHT if self.view_y > ARENA_HEIGHT - SCREEN_HEIGHT: self.view_y = ARENA_HEIGHT - SCREEN_HEIGHT if self.player.pos.y < 1/4 * SCREEN_HEIGHT + self.view_y: self.view_y = self.player.pos.y - 1/4 * SCREEN_HEIGHT if self.view_y < 0: self.view_y = 0
class Sandbox: def __init__(self, screen, brain, extra_ast): game_folder = os.path.dirname(__file__) img_folder = os.path.join(game_folder, 'sprites') self.bg = pg.image.load(os.path.join(img_folder, 'Space_Stars4.png')) self.bullet_img = pg.image.load(os.path.join(img_folder, 'bullet.png')) self.ast_imgs = [pg.image.load(os.path.join(img_folder, 'ast1.png'))] self.player_img = pg.image.load(os.path.join(img_folder, 'tile010.png')) self.player = Player(300, 200, self.player_img, brain) self.screen = screen self.bullets = pg.sprite.Group() self.asteroids = pg.sprite.Group() self.player_group = pg.sprite.Group() self.player_group.add(self.player) self.cooldown = 0 self.grid = Grid(RESOLUTION[0], RESOLUTION[1], 128) self.grid.insert(self.player, self.player.rect.center[0], self.player.rect.center[1]) self.displaying = False self.net_renderer = NetworkRenderer(self.screen) self.time = 0 self.bounty_timer = 20 self.extra_asteroids = extra_ast def display(self): self.setup_background() if self.player.target == self.player.closest_asteroid: pg.draw.line(self.screen, color=(255, 255, 255), start_pos=self.player.rect.center, end_pos=self.player.closest_asteroid.rect.center, width=2) else: pg.draw.line(self.screen, color=(255, 255, 255), start_pos=self.player.rect.center, end_pos=self.player.closest_asteroid.rect.center) pg.draw.line(self.screen, color=(255, 0, 0), start_pos=self.player.rect.center, end_pos=self.player.target.rect.center) self.bullets.draw(self.screen) self.asteroids.draw(self.screen) self.player_group.draw(self.screen) ft_font = pygame.freetype.SysFont('Sans', 20) text_str = 'Score: {}'.format(self.player.score) text_rect = ft_font.get_rect(text_str) text_rect.center = self.screen.get_rect().topleft ft_font.render_to(self.screen, (text_rect[0] + 50, text_rect[1] + 20), text_str, (255, 255, 255)) if gints is None: return text_str = 'Inputs: {}'.format(list(np.around(gints, 2))) text_rect = ft_font.get_rect(text_str) text_rect.center = self.screen.get_rect().topright ft_font.render_to(self.screen, (text_rect[0] - 110, text_rect[1] + 20), text_str, (255, 255, 255)) text_str = 'Outputs: {}'.format(list(np.around(gouts, 2))) text_rect = ft_font.get_rect(text_str) text_rect.center = self.screen.get_rect().topright ft_font.render_to(self.screen, (text_rect[0] - 100, text_rect[1] + 50), text_str, (255, 255, 255)) text_str = 'Time: {}'.format(self.bounty_timer) text_rect = ft_font.get_rect(text_str) text_rect.center = self.screen.get_rect().midtop ft_font.render_to(self.screen, (text_rect[0] - 40, text_rect[1] + 20), text_str, (255, 255, 255)) self.net_renderer.render(self.player.brain) def tick(self): self.player.wrap_around_screen() self.remove_out_of_screen(self.bullets) self.remove_out_of_screen(self.asteroids) self.replenish_asteroids() for i in self.bullets: self.update_element_and_grid(i) for i in self.asteroids: self.update_element_and_grid(i) self.update_element_and_grid(self.player) self.check_collisions() self.propagate_player() self.cooldown -= 1 self.cooldown = max(0, self.cooldown) self.time += 1 if self.time % 60 == 0: self.bounty_timer -= 1 if self.bounty_timer <= 0: self.player.die() def update_element_and_grid(self, elem): old_x = elem.rect.center[0] old_y = elem.rect.center[1] old_key = self.grid.get_key(old_x, old_y) elem.update() new_key = self.grid.get_key(elem.rect.center[0], elem.rect.center[1]) if old_key != new_key: self.grid.delete(elem, old_x, old_y) self.grid.insert(elem, elem.rect.center[0], elem.rect.center[1]) def propagate_player(self): ast = random.choice(list(self.asteroids)) closest = self.distance(ast.rect.center, self.player.rect.center) for a in self.asteroids: dist = self.distance(self.player.rect.center, a.rect.center) if dist < closest: closest = dist ast = a closest = self.norm_distance(self.player, ast) self.player.closest_asteroid = ast degs = self.norm_angle(ast) if self.player.target is None: self.player.target = random.choice(list(self.asteroids)) target_dist = self.norm_distance(self.player.target, self.player) target_angle = self.norm_angle(self.player.target) inputs = [degs, closest, target_angle, target_dist] outputs = self.player.propagate(inputs) if self.displaying: global gints gints = inputs global gouts gouts = outputs # Move if outputs[0] >= 0.8: self.player.accelerate() # Steer if outputs[1] >= 0.9: if outputs[0] >= 0.9 or outputs[0] <= 0.1: self.player.steer(1) else: self.player.steer(5) elif outputs[1] <= 0.1: if outputs[0] >= 0.9 or outputs[0] <= 0.1: self.player.steer(-1) else: self.player.steer(-5) # Shoot if outputs[2] >= 0.8: if self.cooldown == 0: # Don't allow player to make bullet laser beams bullet = Bullet(self.player, self.bullet_img) self.bullets.add(bullet) self.grid.insert(bullet, bullet.rect.center[0], bullet.rect.center[1]) self.player.shots_fired += 1 self.cooldown = 50 def norm_angle(self, a): dx = a.rect.center[0] - self.player.rect.center[0] dy = a.rect.center[1] - self.player.rect.center[1] rads = atan2(-dy, dx) rads %= 2 * pi degs = degrees(rads) degs = abs(360 - self.player.angle - abs(degs)) if degs > 180: degs -= 360 degs = abs(degs) return degs / 180 def norm_distance(self, a, b): target_dist = self.distance(a.rect.center, b.rect.center) target_dist /= (self.distance((0, 0), (RESOLUTION[0], 0)) / 2) target_dist = max(1 - target_dist, 0.00) return target_dist def setup_background(self): brick_width, brick_height = self.bg.get_width(), self.bg.get_height() for x, y in itertools.product(range(0, RESOLUTION[0], brick_width), range(0, RESOLUTION[1], brick_height)): self.screen.blit(self.bg, (x, y)) def remove_out_of_screen(self, sprites): count = 0 for s in sprites: if s.position.x > RESOLUTION[0] + 30 or s.position.x < -50 or s.position.y <= -50 or s.position.y > \ RESOLUTION[1] + 50: sprites.remove(s) self.grid.delete(s, s.rect.center[0], s.rect.center[1]) count += 1 if s == self.player.target: self.player.target = None return count def replenish_asteroids(self): while len(self.asteroids) < ASTEROID_COUNT + self.extra_asteroids: asteroid = Asteroid(random.choice(self.ast_imgs)) self.asteroids.add(asteroid) self.grid.insert(asteroid, asteroid.rect.center[0], asteroid.rect.center[1]) def check_collisions(self): player_zone = self.grid.get_zone(self.player.rect.center[0], self.player.rect.center[1]) for i in player_zone: if i == self.player: continue if i not in self.bullets and pg.sprite.collide_circle( self.player, i): self.player.die() self.player.killed = True for b in self.bullets: b_zone = self.grid.get_zone(b.rect.center[0], b.rect.center[1]) asteroids = [x for x in b_zone if type(x) is Asteroid] for i in asteroids: if pg.sprite.collide_circle(i, b): if self.player.closest_asteroid == i: self.player.score += 1 self.player.shots_hit += 1 if self.player.target == i: self.player.score += round((self.norm_distance( self.player, self.player.target)) * 5) self.player.shots_hit += 1 self.bounty_timer = 20 self.player.target = None if self.player.target != i and self.player.closest_asteroid != i: self.player.score -= 1 self.player.score = max(self.player.score, 0) self.asteroids.remove(i) self.bullets.remove(b) self.grid.delete(i, i.rect.center[0], i.rect.center[1]) self.grid.delete(b, b.rect.center[0], b.rect.center[1]) def distance(self, p1, p2): if len(p1) != len(p2): print("Parameter length mismatch") return None result = 0.0 for i in range(len(p1)): result += math.pow(p1[i] - p2[i], 2) return math.sqrt(result)