def test_score_sorting(self): human1 = player.Human(1, "Kenneth") human2 = player.Human(1, "Elaine") for category in player_scores: human1.scoresheet[category].score = 1 human2.scoresheet[category].score = 5 self.assertGreater(human2.score, human1.score)
def __init__(self): self.finish = False self.winner = None self.player = [None, None] self.round = 1 self.discs = ["X", "O"] self.turn = None print("Connect Four Game!") while self.player[0] == None or self.player[1] == None: print("Player A human or computer?") selectionA = str(input("Enter c for COMPUTER, h for HUMAN: ")) if selectionA == 'c': self.player[0] = player.Computer(self.discs[0]) elif selectionA == 'h': self.player[0] = player.Human(self.discs[0]) else: print("Invalid input!") continue print("Player B human or computer?") selectionB = str(input("Enter c for COMPUTER, h for HUMAN: ")) if selectionB == 'c': self.player[1] = player.Computer(self.discs[1]) elif selectionB == 'h': self.player[1] = player.Human(self.discs[1]) else: print("Invalid input!") continue print("Player A go first with X") self.turn = self.player[0]
def __init__(self, cursor_position): self.cursor = cursor_position self.match_player_text = [ "human vs human", "human vs COM", "COM vs human", "COM vs COM" ] self.match_player = [(player.Human(), player.Human()), (player.Human(), AI_TYPE), (AI_TYPE, player.Human()), (AI_TYPE, AI_TYPE)] self.is_active = True
def get_options(self): player1, player2, level = self.gui.show_options() if player1 == "human": self.now_playing = player.Human(self.gui, BLACK) else: self.now_playing = player.Computer(BLACK, level + 3) if player2 == "human": self.other_player = player.Human(self.gui, WHITE) else: self.other_player = player.Computer(WHITE, level + 3) self.gui.show_game() self.gui.update(self.board.board, 2, 2, self.now_playing.color)
def start(self, *args): player1, player2 = args logger.info('Settings: player 1: %s, player 2: %s ', player1, player2) if player1 == HUMAN: self.now_playing = player.Human(self.gui, BLACK) else: self.now_playing = player.Computer(BLACK) if player2 == HUMAN: self.other_player = player.Human(self.gui, WHITE) else: self.other_player = player.Computer(WHITE) self.gui.show_game() self.gui.update(self.board.board, 2, 2, self.now_playing.color)
def get_options(self) -> None: """ Sets up two players who will participate in the game. """ # set up players player1, player2 = self.gui.title_screen() if player1 == "human": self.now_playing = player.Human(self.gui, BLACK) if player2 == "human": self.other_player = player.Human(self.gui, WHITE) self.gui.show_game() self.gui.update_screen(self.board.board, 2, 2, self.now_playing.color)
def __init__(self): """ create a new game """ self.board = core.new_board() self.firsthand = player.Human(core.FIRST_HAND) self.lasthand = player.Bot(core.LAST_HAND)
def _addHumanPlayers(self): '''Adds each human player into the game''' for index in range(self.numHumanPlayers): playerName = raw_input( "Enter a name for player {0}: ".format(index)) newPlayer = player.Human(playerName) self._addPlayer(newPlayer)
def set_options(self): """ set up playres """ player1, player2 = self.gui.show_options() if player1 == HUMAN: self.now_playing = player.Human(self.gui, BLACK) else: self.now_playing = player.Computer(BLACK) if player2 == HUMAN: self.other_player = player.Human(self.gui, WHITE) else: self.other_player = player.Computer(WHITE) self.gui.show_game() self.gui.update_screen(self.board.board, 2, 2)
def setUp(self): self.player_object = player.Player() self.human_object = player.Human() self.AI_object = player.AI() self.battleship = ship.Ship(position=[2, 2]) self.cruiser = ship.Ship(position=[3, 2], length=4, letter="C") self.player_object.ships = [self.battleship, self.cruiser] self.shooting_range = {"45": "o", "23": "x", "11": "o"}
def prepare_game(self, player_count=1, board_size=10): """ starts battleship game :param player_count: int number of players :param board_size: int size of board (side length) """ #set up pause self.capture_pause() if player_count == 1: # singleplayer game #initialize players plyrs = [ player.Human(player_name="Human Player", board_size=board_size), player.AI(player_name="Computer Player", board_size=board_size) ] self.players = plyrs #set targets self.players[0].target = self.players[1] self.players[1].target = self.players[0] #run game self.run_game() else: # multiplayer game #initialize players plyrs = [""] * player_count for num in range(player_count): plyrs[num] = player.Human(player_name=f"Player { num + 1 }", board_size=board_size) self.players = plyrs #set targets for num, user in enumerate(self.players): if num + 1 == len(self.players): user.target = self.players[0] else: user.target = self.players[num + 1] #run game self.run_game()
def generatePlayers(self): user = player.Human(random.randint(0, self.dim - 1), random.randint(0, self.dim - 1), self.cellWidth) computerX = random.randint(0, self.dim - 1) computerY = random.randint(0, self.dim - 1) while computerX == user.gridX and computerY == user.gridY: computerX = random.randint(0, self.dim - 1) computerY = random.randint(0, self.dim - 1) computer = player.Computer(computerX, computerY, self.cellWidth) self.players.add(user, computer)
def __init__(self): """ create a new game """ Tk.__init__(self) self.board = app.App().create_hexes_board(app.App().initGrid( 20, 20, 18)) self.firsthand = player.Human(player.FIRST_HAND) self.lasthand = player.Bot(player.LAST_HAND) self.can = Tk.Canvas(self, width=650, height=550, bg="#60ace6") self.size = 18
def main(): m = map.HomelyHill() def play_map(player, game_map): g = game.Game(game_map) player.play(g) return g players = [ player.Human(), player.NaturalSelection(), player.NaturalEvolutionSGD(), player.FiniteDifferences(), player.ScipyOptimizer('BFGS'), player.ScipyOptimizer('Powell'), player.ScipyOptimizer('Nelder-Mead'), player.ScipyOptimizer('CG'), player.ScipyOptimizer('COBYLA') ] games = [play_map(player, m) for player in players] v = visualize.Visualize(players, games, m) v.show(n_evaluations=1)
def choose(self): self.gui.showMainMenu() option = self.gui.getOption() if option == 1: self.player1 = player.Computer(BLACK) self.player2 = player.Human(WHITE) self.run() elif option == 2: self.player1 = player.Human(BLACK) self.player2 = player.Computer(WHITE) self.run() elif option == 3: self.player1 = player.Human(BLACK) self.player2 = player.Human(WHITE) self.run() elif option == 4: self.player1 = player.Computer(BLACK) self.player2 = player.Computer(WHITE) self.run() elif option == 5: self.gui.showIP() self.player1 = player.Human(BLACK) self.player2 = player.HumanC(WHITE) #t = threading.Thread(target = self.gui.getCancel(self.player2.server.socket, self), name="Child Thread") #t.setDaemon(1) #t.start() self.player2.waitingForClient() self.run() elif option == 6: ip = self.gui.getServerIP() if ip == 'cancel': self.choose() return self.player1 = player.HumanS(BLACK, ip) self.player2 = player.Human(WHITE) self.run()
history = True if str(o_args[6]) != "None": watch = True if str(o_args[7]) != "None": human_is_x = True if str(o_args[8]) != "None" and not human_is_x: human_is_o = True if str(o_args[9]) != "None": show_board = True if watch and str(o_args[0]) == "None": print "Please enter the path to the file containing the game to watch:" game_file = prgm_lib.get_str() player1 = player.Human() player2 = player.Human() if num_humans == 1: if human_is_x: player2 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) elif human_is_o: player1 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) else: if random.randint(0,1) == 0: player1 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) else: player2 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) elif num_humans == 0: player1 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level) player2 = player.AI_ABPruning(heuristics.game_heuristic1, show_thought_level)
def game_loop(): #game layer best_bot = None #startnet = 'saves/best_bot_full' startnet = None quitting = False draw_game = True speed = 1 #generate first gen of players bot_list = [] human = [] for ii in range(nplayers): pbuf = player.Player() if full_nets: pbuf.net = network.full_network() pbuf.net.mutate() bot_list.append(pbuf) if startnet is not None: bot_list[len(bot_list) - 1].net = network.load_net(startnet) if place_human: human = [player.Human()] best_bot = bot_list[len(bot_list) - 1] while not quitting: ###GENERATION LAYER### if len(levels.levelarr) > 0: levels.cur_level = levels.levelarr[0] else: levels.cur_level = levels.generate_level(0) levels.cur_level_n = 0 ndead = 0 while ndead < len(bot_list + human): ###LEVEL LAYER### #reset level nwin = 0 give_up = False for bn, tri in enumerate(bot_list + human): if not tri.dead: tri.x_pos = objects.x_init tri.y_pos = objects.player_floor_1 tri.jumping = False tri.fallen = False tri.x_vel = player.xspeed tri.y_vel = 0 tri.angle = 0 tri.win = False levelrects = [] inputs = [0, 0, 0, 0, 0, 0, 0] decision = 0 #display bg, floors and net init.gameDisplay.fill((255, 255, 255)) objects.draw_net(best_bot.net) if draw_game: objects.draw_level(levels.cur_level, levelrects) objects.draw_floors() pygame.display.update() if place_human: pygame.time.wait(750) activerects = [] while ndead + nwin < nplayers + place_human: ###TICK LAYER### prevrects = activerects activerects = [] #active parts to update on screen #fill in previous positions if draw_game: init.gameDisplay.fill((255, 255, 255)) #for rect in prevrects: #init.gameDisplay.fill((255,255,255),rect=rect) for event in pygame.event.get(): if event.type == pygame.QUIT: quitting = True ndead = len(bot_list) + 5 if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and place_human: if not human[0].jumping: human[0].jumping = True human[0].y_vel = jump_v if event.key == pygame.K_PERIOD: speed = 256 if event.key == pygame.K_COMMA: speed = 1 if event.key == pygame.K_g: draw_game = not draw_game if event.key == pygame.K_r: give_up = True if event.key == pygame.K_p: print(inputs) print(decision) #objects.look_verbose = not objects.look_verbose #speed = 1/8 for bot in bot_list: #only decide if not in air if not bot.jumping and not bot.dead: inputs = objects.look(bot.x_pos, bot.y_pos, bot.fallen, levels.cur_level) decision = bot.net.propogate(inputs) if decision > 0: bot.jumping = True bot.y_vel = jump_v for tri in bot_list + human: ###PLAYER LOOP### if tri.dead or tri.win: continue if tri.jumping: tri.y_vel = tri.y_vel + 0.5 if tri.fallen: #tri.angle = 0 tri.angle = tri.angle + 5 else: #tri.angle = 0 tri.angle = tri.angle - 5 #UPDATE POSITION tri.x_pos = tri.x_pos + tri.x_vel tri.y_pos = tri.y_pos + tri.y_vel #FLOOR COLLISIONS if not tri.fallen: if tri.y_pos > objects.player_floor_1: tri.y_pos = objects.player_floor_1 tri.y_vel = 0 tri.jumping = False tri.angle = 0 elif tri.y_pos > objects.player_floor_2: tri.y_pos = objects.player_floor_2 tri.x_vel = -player.xspeed tri.y_vel = 0 tri.jumping = False tri.angle = 0 if tri.x_pos > init.display_width - objects.player_base: tri.x_pos = init.display_width - objects.player_base tri.y_pos = objects.player_floor_1 tri.y_vel = 0 tri.x_vel = 0 tri.fallen = True tri.jumping = True if tri.fallen and tri.x_pos < 0: tri.win = True nwin += 1 #CHECK FOR CRASH crashed = objects.test_collision(tri.x_pos, tri.y_pos, tri.fallen, levels.cur_level) if crashed: tri.dead = True ndead += 1 #print(inputs) #DRAW IF NOT CRASHED elif draw_game: activerects.append( objects.draw_player(tri.x_pos, tri.y_pos, tri.angle, tri.image)) tri.score += 1 #END OF TICK LAYER if place_human and human[0].dead and not give_up: human[0].dead = False ndead -= 1 human[0].x_pos = objects.x_init human[0].y_pos = objects.player_floor_1 human[0].jumping = False human[0].fallen = False human[0].x_vel = player.xspeed human[0].y_vel = 0 human[0].angle = 0 human[0].win = False if draw_game: objects.draw_level(levels.cur_level, levelrects) objects.draw_floors() objects.draw_net(best_bot.net) #updaterects = prevrects + activerects pygame.display.update() clock.tick(60 * speed) #END OF LEVEL LAYER if (nwin > 0): if levels.cur_level_n < levels.num_levels or continue_game: levels.next_level() else: quitting = True ndead = nplayers + 5 #END OF GEN LAYER, dont mutate if quitting if not quitting: scores = np.zeros(nplayers) for ii, tri in enumerate(bot_list): scores[ii] = int(tri.score) + np.random.rand() tri.dead = False tri.score = 0 #reset human if place_human: human[0].dead = False human[0].score = 0 cull_length = int(len(bot_list) / 2) idx = np.argsort(scores) buf = [] for ii in idx[cull_length:]: buf.append(bot_list[ii]) bot_list = buf best_bot = bot_list[len(bot_list) - 1] print(f'----------{scores[idx[-1]]:7.2f}' + f'------------{levels.cur_level_n}') for ii in range(cull_length): idx = ii % cull_length newbot = deepcopy(bot_list[::-1][idx]) newbot.net.mutate() bot_list.append(newbot) svweights = [] svfnodes = [] svtnodes = [] svnoden = [] svnodel = [] for l in range(best_bot.net.layers): for conn in best_bot.net.connectionList[l]: svweights.append(conn.weight) svfnodes.append(conn.fromNode.nodeNo) svtnodes.append(conn.toNode.nodeNo) for node in best_bot.net.nodeList[l]: svnodel.append(node.layer) svnoden.append(node.nodeNo) svconn = np.array([svweights, svfnodes, svtnodes]) svconn = svconn.T svnodes = np.array([svnoden, svnodel]) svnodes = svnodes.T if startnet is not None and False: np.savetxt(startnet + '_c.txt', svconn, delimiter='\t') np.savetxt(startnet + '_n.txt', svnodes, delimiter='\t') else: np.savetxt('./saves/best_bot_new_c.txt', svconn, delimiter='\t') np.savetxt('./saves/best_bot_new_n.txt', svnodes, delimiter='\t')
def setUp(self): self.game_object = game.Game() self.player_object = player.Human() self.options = ["Start New Game", "Resume Game", "Quit"] self.maxDiff = None
def game_loop(): #game layer quitting = False draw_game = True speed = 1 #generate first gen of players bot_list = [] human = [] human = [player.Human()] while not quitting: ###GENERATION LAYER### if len(levels.levelarr) > 0: levels.cur_level = levels.levelarr[0] else: levels.cur_level = levels.generate_level(0) levels.cur_level_n = 0 ndead = 0 while ndead < 1: ###LEVEL LAYER### #reset level nwin = 0 give_up = False for bn, tri in enumerate(bot_list + human): if not tri.dead: tri.x_pos = objects.x_init tri.y_pos = objects.player_floor_1 tri.jumping = False tri.fallen = False tri.x_vel = player.xspeed tri.y_vel = 0 tri.angle = 0 tri.win = False levelrects = [] #display bg, floors and net init.gameDisplay.fill((255, 255, 255)) if draw_game: objects.draw_level(levels.cur_level, levelrects) objects.draw_floors() pygame.display.update() pygame.time.wait(750) activerects = [] while ndead + nwin < 1: ###TICK LAYER### prevrects = activerects activerects = [] #active parts to update on screen #fill in previous positions if draw_game: init.gameDisplay.fill((255, 255, 255)) #for rect in prevrects: #init.gameDisplay.fill((255,255,255),rect=rect) for event in pygame.event.get(): if event.type == pygame.QUIT: quitting = True ndead = len(bot_list) + 5 if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if not human[0].jumping: human[0].jumping = True human[0].y_vel = jump_v if event.key == pygame.K_PERIOD: speed = 128 if event.key == pygame.K_COMMA: speed = 1 if event.key == pygame.K_g: draw_game = not draw_game if event.key == pygame.K_r: give_up = True for tri in bot_list + human: ###PLAYER LOOP### if tri.dead or tri.win: continue if tri.jumping: tri.y_vel = tri.y_vel + 0.5 if tri.fallen: #tri.angle = 0 tri.angle = tri.angle + 5 else: #tri.angle = 0 tri.angle = tri.angle - 5 #UPDATE POSITION tri.x_pos = tri.x_pos + tri.x_vel tri.y_pos = tri.y_pos + tri.y_vel #FLOOR COLLISIONS if not tri.fallen: if tri.y_pos > objects.player_floor_1: tri.y_pos = objects.player_floor_1 tri.y_vel = 0 tri.jumping = False tri.angle = 0 elif tri.y_pos > objects.player_floor_2: tri.y_pos = objects.player_floor_2 tri.x_vel = -player.xspeed tri.y_vel = 0 tri.jumping = False tri.angle = 0 if tri.x_pos > init.display_width - objects.player_base: tri.x_pos = init.display_width - objects.player_base tri.y_pos = objects.player_floor_1 tri.y_vel = 0 tri.x_vel = 0 tri.fallen = True tri.jumping = True if tri.fallen and tri.x_pos < 0: tri.win = True nwin += 1 #CHECK FOR CRASH crashed = objects.test_collision(tri.x_pos, tri.y_pos, tri.fallen, levels.cur_level) if crashed: tri.dead = True ndead += 1 #DRAW IF NOT CRASHED elif draw_game: activerects.append( objects.draw_player(tri.x_pos, tri.y_pos, tri.angle, tri.image)) tri.score += 1 #END OF TICK LAYER if human[0].dead and not give_up: human[0].dead = False ndead -= 1 human[0].x_pos = objects.x_init human[0].y_pos = objects.player_floor_1 human[0].jumping = False human[0].fallen = False human[0].x_vel = player.xspeed human[0].y_vel = 0 human[0].angle = 0 human[0].win = False if draw_game: objects.draw_level(levels.cur_level, levelrects) objects.draw_floors() #updaterects = prevrects + activerects pygame.display.update() clock.tick(60 * speed) #END OF LEVEL LAYER if (nwin > 0): if levels.cur_level_n < levels.num_levels or continue_game: levels.next_level() else: quitting = True ndead = 5 #END OF GEN LAYER, dont mutate if quitting if not quitting: #reset human human[0].dead = False human[0].score = 0
def fightLoop(settings): # Store the match settings lives = settings[0] characters = settings[1] playertypes = settings[2] botdiffs = settings[3] stage = settings[4] return_to_title = False # Create a sprite group for the objects in the world environment # OrderedUpdates type to make sure everything updates and draws in the order they were appended to the group world = pygame.sprite.OrderedUpdates() if stage == 4: stage = random.randint(0, 3) if stage == 0: # Add the stage background as part of the world environment world.add(environment.Scenery(assets.srr_bg)) # Add platforms as part of the world environment (has collision) world.add(environment.Platform(assets.srr_pl_s, 50, 700)) world.add(environment.Platform(assets.srr_pl_t, 50, 500, True)) world.add(environment.Platform(assets.srr_pl_t, 510, 500, True)) spawnpoints = [(170, 500), (630, 500)] # Load the stage music pygame.mixer.music.load(os.path.join(cfg.music_dir, 'Green_Stage.mp3')) elif stage == 1: # Add the stage background as part of the world environment world.add(environment.Scenery(assets.cc_bg)) # Add platforms as part of the world environment (has collision) world.add(environment.Platform(assets.cc_pl_s, 50, 700)) world.add(environment.Platform(assets.cc_pl_s, 280, 700)) world.add(environment.Platform(assets.cc_pl_s, 510, 700)) world.add(environment.Platform(assets.cc_pl_t, 150, 500, True)) spawnpoints = [(170, 700), (630, 700)] # Load the stage music pygame.mixer.music.load( os.path.join(cfg.music_dir, 'Crystal_stage.mp3')) elif stage == 2: # Add the stage background as part of the world environment world.add(environment.Scenery(assets.rv_bg)) # Add platforms as part of the world environment (has collision) world.add(environment.Platform(assets.rv_pl_s, 50, 700)) spawnpoints = [(150, 700), (650, 700)] # Load the stage music pygame.mixer.music.load(os.path.join(cfg.music_dir, 'Fire_Stage.mp3')) elif stage == 3: # Add the stage background as part of the world environment world.add(environment.Scenery(assets.at_bg)) # Add platforms as part of the world environment (has collision) world.add(environment.Platform(assets.at_pl_s, 150, 700)) world.add(environment.Platform(assets.at_pl_t, -50, 532, True)) world.add(environment.Platform(assets.at_pl_t, 650, 532, True)) spawnpoints = [(50, 532), (750, 532)] # Load the stage music pygame.mixer.music.load(os.path.join(cfg.music_dir, 'Sand_Stage.mp3')) # Play the stage music if cfg.sound: pygame.mixer.music.play(-1) # Create the camera (used for updating the offset values used for drawing objects to the screen) camera = environment.Camera() # Create a sprite group for on-screen entities # OrderedUpdates type to make sure everything draws in the order they were appended to the group entities = pygame.sprite.OrderedUpdates() # Create a list of players humans = [] bots = [] for plyr in range(0, len(characters)): # If the player chose random, then generate a random character index if characters[plyr] == 4: characters[plyr] = random.randint(0, 3) settings[1] = characters # Set the current player's character to Pebble with the specified amount of lives if characters[plyr] == 0: char = character.Pebble(lives, spawnpoints[plyr]) # Set the current player's character to Crystal with the specified amount of lives elif characters[plyr] == 1: char = character.Crystal(lives, spawnpoints[plyr]) # Set the current player's character to Magma with the specified amount of lives elif characters[plyr] == 2: char = character.Magma(lives, spawnpoints[plyr]) # Set the current player's character to Pharaoh with the specified amount of lives elif characters[plyr] == 3: char = character.Pharaoh(lives, spawnpoints[plyr]) entities.add(char) try: joystick = pygame.joystick.Joystick(plyr) joystick.init() except pygame.error: joystick = None if plyr == 0: keyboard = [ pygame.K_w, # Up pygame.K_s, # Down pygame.K_a, # Left pygame.K_d, # Right pygame.K_t, # Up attack pygame.K_g, # Down attack pygame.K_f, # Left attack pygame.K_h # Right attack ] elif plyr == 1: keyboard = [ pygame.K_i, # Up pygame.K_k, # Down pygame.K_j, # Left pygame.K_l, # Right pygame.K_UP, # Up attack pygame.K_DOWN, # Down attack pygame.K_LEFT, # Left attack pygame.K_RIGHT # Right attack ] else: keyboard = None if playertypes[plyr] == 'Human': humans.append(player.Human(keyboard, joystick, char)) else: bots.append(player.Bot(char, botdiffs[plyr])) # # Load the font for the HUD # dbgfont = pygame.font.SysFont(None, 25) # Countdown timer that lasts 181 frames (~3 seconds at 60fps) countdown = 181 # Render the font for the countdown in advance text_1 = assets.countdown_font.render('1', True, (255, 255, 255)) text_2 = assets.countdown_font.render('2', True, (255, 255, 255)) text_3 = assets.countdown_font.render('3', True, (255, 255, 255)) text_go = assets.countdown_font.render('GO!', True, (255, 255, 255)) # Start the loop running = True while running: # Event Loop for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: return_to_title = menu.Options("Fight") if return_to_title: running = False loser = "" if countdown < 0: for human in humans: human.updateInputs() for bot in bots: bot.updateInputs(entities.sprites(), stage) # Update the camera offsets according to the position of on-screen entities camera.updatePos(entities.sprites()) # Update the position of the world objects relative to the camera position world.update(camera) # Draw the environment sprites to the screen world.draw(cfg.window) # Update the state of every entity entities.update(camera, world.sprites(), entities.sprites()) # Draw the entities to the screen entities.draw(cfg.window) # Draw the in-game HUD interface.Display(entities.sprites()) if countdown > -30: countdown -= 1 if countdown == 180: if cfg.sound: pygame.mixer.Sound(os.path.join(cfg.voice_dir, '3.ogg')).play() elif countdown == 120: if cfg.sound: pygame.mixer.Sound(os.path.join(cfg.voice_dir, '2.ogg')).play() elif countdown == 60: if cfg.sound: pygame.mixer.Sound(os.path.join(cfg.voice_dir, '1.ogg')).play() elif countdown == 0: if cfg.sound: pygame.mixer.Sound(os.path.join(cfg.voice_dir, 'Go.ogg')).play() if 121 < countdown <= 180: cfg.window.blit( text_3, (cfg.width / 2 - pygame.Surface.get_width(text_3) / 2, cfg.height / 2 - pygame.Surface.get_height(text_3) / 2)) elif 61 < countdown <= 120: cfg.window.blit( text_2, (cfg.width / 2 - pygame.Surface.get_width(text_2) / 2, cfg.height / 2 - pygame.Surface.get_height(text_2) / 2)) elif 0 < countdown <= 60: cfg.window.blit( text_1, (cfg.width / 2 - pygame.Surface.get_width(text_1) / 2, cfg.height / 2 - pygame.Surface.get_height(text_1) / 2)) elif -30 < countdown <= 0: cfg.window.blit( text_go, (cfg.width / 2 - pygame.Surface.get_width(text_go) / 2, cfg.height / 2 - pygame.Surface.get_height(text_go) / 2)) # # Draw collision boxes (DEBUG) # for e in entities.sprites(): # pygame.draw.rect(cfg.window, (0,255,0), e.hurtbox, 1) # pygame.draw.rect(cfg.window, (0,0,255), e.rect, 1) # for attack in e.active_attacks: # for hitbox in attack.active_hitboxes: # pygame.draw.rect(cfg.window, (255,0,0), hitbox.rect, 1) # for p in world.sprites(): # pygame.draw.rect(cfg.window, (0,255,0), p.rect, 1) # # Render and draw text to the screen (DEBUG) # cfg.window.blit(dbgfont.render('x: ' + str(humans[0].character.x) + ' y: ' + str(humans[0].character.y), True, (255,255,255)), (10, 10)) # cfg.window.blit(dbgfont.render('rx: ' + str(humans[0].character.hurtbox.x) + ' ry: ' + str(humans[0].character.hurtbox.y), True, (255,255,255)), (10, 30)) # cfg.window.blit(dbgfont.render('cx: ' + str(camera.x_offset) + ' cy: ' + str(camera.y_offset), True, (255,255,255)), (10, 50)) # cfg.window.blit(dbgfont.render('airbourne: ' + str(humans[0].character.airbourne), True, (255,255,255)), (10, 70)) # cfg.window.blit(dbgfont.render('xv: ' + str(humans[0].character.x_vel) + ' yv: ' + str(humans[0].character.y_vel), True, (255,255,255)), (10, 90)) # cfg.window.blit(dbgfont.render('attacking: ' + str(humans[0].character.attacking), True, (255,255,255)), (10, 110)) # cfg.window.blit(dbgfont.render('fps: ' + str(cfg.clock.get_fps()), True, (255,255,255)), (10, 130)) # try: # for a in range(0, humans[0].joystick.get_numaxes()): # cfg.window.blit(dbgfont.render(str(a) + ': ' + str(humans[0].joystick.get_axis(a)), True, (255,255,255)), (10, 150 + a * 20)) # for b in range(0, humans[0].joystick.get_numbuttons()): # cfg.window.blit(dbgfont.render(str(b) + ': ' + str(humans[0].joystick.get_button(b)), True, (255,255,255)), (300, 10 + b * 20)) # except AttributeError: # pass # Check if anyone has no lives. If so, end the game for e in entities.sprites(): if e.lives <= 0: running = False loser = entities.sprites().index(e) # Update the screen pygame.display.flip() cfg.clock.tick(60) #print("ok1") pygame.mixer.music.stop() if cfg.sound: pygame.mixer.Sound(os.path.join(cfg.voice_dir, 'Game_Over.ogg')).play() while pygame.mixer.get_busy(): pass #print("ok2") if return_to_title: next_scene = "Title Screen" else: next_scene = "Results" #print("ok3") return next_scene, settings, loser
def test_human(self): human1 = player.Human(1, "Kenneth") self.assertEqual(human1.name, "Kenneth")
def initialize(self): if (input("do you would like to take the first hand?(y/n)") == 'n'): self.firsthand = player.Bot(core.FIRST_HAND) self.lasthand = player.Human(core.LAST_HAND)
from board import Board import player import user_interface # Choose the interface ui = user_interface.Graphical() # ui = user_interface.CommandLine() # ui = user_interface.Minimal() # Choose the players for respectively the uneven and even moves # player1 = player.Menace("trained_menace.pickle", "trained_menace.pickle") player1 = player.Menace() # player2 = player1 # This does not call the constructor again! so same MENACE player2 = player.Human( ui) # The system needs know where the Human will be providing their input # player2 = player.RandomMove() # Just make a random move def play_game(): # Initialize the gameloop variables board = Board() keep_going = True # Game loop while keep_going: # Draw the board ui.tick() ui.render(board) if board.winner(): # Previous game ended, reset board for new game
def create_players(self): """Stworzenie obiektów graczy.""" self.human = player.Human(self.screen, self, c.HUMAN, c.HUMAN_STONES_COLOR) self.computer = player.Computer(self.screen, self, c.COMPUTER, c.COMPUTER_STONES_COLOR)
def game_loop(): #game layer opponent_1 = 'saves/best_bot_std' opponent_2 = 'saves/best_bot_hard' opponent_3 = 'saves/best_bot_wow' opponents = [opponent_1, opponent_2, opponent_3] nplayers = len(opponents) quitting = False draw_game = True speed = 1 #generate first gen of players bot_list = [] human = [] for ii, bot in enumerate(opponents): bot_list.append(player.Player()) bot_list[ii].net = network.load_net(bot) bot_list[ii].image = 4 + ii if place_human: human = [player.Human()] while not quitting: ###GENERATION LAYER### if len(levels.levelarr) > 0: levels.cur_level = levels.levelarr[0] else: levels.cur_level = levels.generate_level(0) levels.cur_level_n = 0 ndead = 0 while levels.cur_level_n < 10 and not quitting: ###LEVEL LAYER### #reset level nwin = 0 ndead = 0 give_up = False for bn, tri in enumerate(bot_list + human): #comp mode, reset all players tri.x_pos = objects.x_init tri.x_pos -= (len(bot_list) - bn) * 64 tri.y_pos = objects.player_floor_1 tri.jumping = False tri.fallen = False tri.x_vel = player.xspeed tri.y_vel = 0 tri.angle = 0 tri.win = False tri.dead = False levelrects = [] #display bg, floors and net init.gameDisplay.fill((255, 255, 255)) if draw_game: objects.draw_level(levels.cur_level, levelrects) objects.draw_floors() pygame.display.update() if place_human: pygame.time.wait(1000) activerects = [] while ndead + nwin < nplayers + place_human: ###TICK LAYER### prevrects = activerects activerects = [] #active parts to update on screen #fill in previous positions if draw_game: init.gameDisplay.fill((255, 255, 255)) #for rect in prevrects: #init.gameDisplay.fill((255,255,255),rect=rect) for event in pygame.event.get(): if event.type == pygame.QUIT: quitting = True ndead = len(bot_list) + 5 if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and place_human: if not human[0].jumping: human[0].jumping = True human[0].y_vel = jump_v if event.key == pygame.K_PERIOD: speed = 128 if event.key == pygame.K_COMMA: speed = 1 if event.key == pygame.K_g: draw_game = not draw_game if event.key == pygame.K_r: give_up = True if event.key == pygame.K_p: print(inputs) print(decision) print(ndead, nwin) for bot in bot_list: #only decide if not in air if not bot.jumping and not bot.dead: inputs = objects.look(bot.x_pos, bot.y_pos, bot.fallen, levels.cur_level) decision = bot.net.propogate(inputs) if decision > 0: bot.jumping = True bot.y_vel = jump_v for tri in bot_list + human: ###PLAYER LOOP### if tri.dead or tri.win: continue if tri.jumping: tri.y_vel = tri.y_vel + 0.5 if tri.fallen: #tri.angle = 0 tri.angle = tri.angle + 5 else: #tri.angle = 0 tri.angle = tri.angle - 5 #UPDATE POSITION tri.x_pos = tri.x_pos + tri.x_vel tri.y_pos = tri.y_pos + tri.y_vel #FLOOR COLLISIONS if not tri.fallen: if tri.y_pos > objects.player_floor_1: tri.y_pos = objects.player_floor_1 tri.y_vel = 0 tri.jumping = False tri.angle = 0 elif tri.y_pos > objects.player_floor_2: tri.y_pos = objects.player_floor_2 tri.x_vel = -player.xspeed tri.y_vel = 0 tri.jumping = False tri.angle = 0 if tri.x_pos > init.display_width - objects.player_base: tri.x_pos = init.display_width - objects.player_base tri.y_pos = objects.player_floor_1 tri.y_vel = 0 tri.x_vel = 0 tri.fallen = True tri.jumping = True if tri.fallen and tri.x_pos < 0: tri.win = True nwin += 1 #CHECK FOR CRASH crashed = objects.test_collision(tri.x_pos, tri.y_pos, tri.fallen, levels.cur_level) if crashed: tri.dead = True tri.crashes += 1 ndead += 1 #DRAW IF NOT CRASHED elif draw_game: activerects.append( objects.draw_player(tri.x_pos, tri.y_pos, tri.angle, tri.image)) tri.score += 1 #END OF TICK LAYER if draw_game: objects.draw_level(levels.cur_level, levelrects) objects.draw_floors() scores = [ bot_list[0].crashes, bot_list[1].crashes, bot_list[2].crashes, human[0].crashes ] scims = [ bot_list[0].image, bot_list[1].image, bot_list[2].image, human[0].image ] objects.draw_scores(scims, scores, levels.cur_level_n) #updaterects = prevrects + activerects pygame.display.update() clock.tick(60 * speed) #END OF LEVEL LAYER if levels.cur_level_n < levels.num_levels or continue_game: levels.next_level() else: quitting = True ndead = nplayers + 5 #END OF GEN LAYER wait to display scores pygame.time.wait(15000) quitting = True
def get_humans(self, num): humans = [] for order in range(1, num+1): name = input("Name for Player {}: ".format(order)) humans.append(player.Human(order, name)) return humans
#!/usr/bin/env python3 """ versus3t.py play a round against the current bot; it learns from these games as well """ import random import tictactoe import player ai_player = player.AI(read_save=True) if random.randint(0, 1): print("Go first") game = tictactoe.Game(player.Human(), ai_player) else: print("Go second") game = tictactoe.Game(ai_player, player.Human()) if __name__ == "__main__": game.play() ai_player.freeze()