def execute(arguments): player_string = player_options[arguments.m] player_object = lazy_load_object(player_string) game = PlayerThread(player_object) game.play_game((arguments.a,arguments.p))
def play_tourney(config): """ A tourney is a plurality of games. """ for i in range(0, config.num_games): game.play_game(config) for player in config.players: player.new_game() # clear last game stats winner = find_tourney_winner(config.players) display_tourney_info(winner, config.players, config.is_verbose)
def test_whole(): sys.stdin = open("test_input_files/2p_input.txt") player, board_size, reverse_status = game_setup() assert play_game(board_size, player) == 1 sys.stdin = open("test_input_files/2p_input.txt") run_game()
def play_gene_pool(self, gene_pool): # Fitness value fitness = [0 for i in range(len(gene_pool))] stupid_count = [0 for i in fitness] for i in range(len(gene_pool)): # Play with all other bots in gene pool for j in chain(range(i), range(i + 1, len(gene_pool))): # Play bots try: winner = game.play_game([gene_pool[i], gene_pool[j]]) except IndexError as ie: print("Exactly two bots must play tic tac toe") game.board.clear( ) # TODO: Make sure this is safe to remove and remove it # Update win counts if winner == 1: fitness[i] += FIRST_WIN_AWARD fitness[j] += FIRST_LOSE_AWARD elif winner == -1: fitness[i] += STUPID_AWARD stupid_count[i] += 1 elif winner == 2: fitness[j] += SECOND_WIN_AWARD fitness[i] += SECOND_LOSE_AWARD elif winner == -2: fitness[j] += STUPID_AWARD stupid_count[j] += 1 elif winner == 0: # Draw fitness[i] += FIRST_DRAW_AWARD fitness[j] += SECOND_DRAW_AWARD return fitness, stupid_count
def _play_game(self, match): key = match[2] if key in self.results: return away_team = self.teams[match[0]] home_team = self.teams[match[1]] result = game.play_game(away_team, home_team) self.results[key] = result
def test_ai_battle(self): for i in range(1): players = [ dumb_ai.PowerAI('Steve'), dumb_ai.DumbAI('Trip'), dumb_ai.Outbidder('Goof'), ] self.assertEqual(game.play_game(players).name, 'Steve')
def run_games(n=100): history = [] for i in range(n): if (i + 1) % 100 == 0: print("Played %d of %d games" % (i + 1, n)) winner, p1_turns = game.play_game(False) history.append([winner, p1_turns]) return np.array(history)
def start_screen(): """ Запуск цикла игры для отображения главного окна """ global screen draw = draw_main_view while True: time_del = clock.tick(fps) / 1000 for e in pygame.event.get(): if e.type == pygame.QUIT: terminate() # Обработка триггеров на нажатие интерфейсных кнопок if e.type == pygame.USEREVENT: if e.user_type == pygame_gui.UI_BUTTON_PRESSED: if e.ui_element == start_btn: draw = draw_select_game_mode_view if e.ui_element in (one_player_btn, two_player_btn): stop_sound(fon_menu_music) game.play_game('level1', (e.ui_element == two_player_btn) + 1, True) play_sound(fon_menu_music, -1) draw = draw_main_view screen = pygame.display.set_mode(SIZE) if e.ui_element == description_btn: draw = draw_description_view if e.ui_element == highscores_btn: draw = draw_highscores_view if e.ui_element == exit_btn: terminate() if e.ui_element == back_btn: draw = draw_main_view manager.process_events(e) # draw() manager.update(time_del) manager.draw_ui(screen) pygame.display.flip() clock.tick(fps)
def main(): while True: try: play_game( # IGGCPlayer(login='******', password='******', app_id=18, app_code='navaha8730'), # IGGCPlayer(login='******', password='******', app_id=19, app_code='vhaaan2783'), IGGCPlayer(login='******', password='******', app_id=18, app_code='navaha8730'), # Lajkonik('../lajkonik/lajkonik-10'), # Castro('../castro/castro'), Wanderer('../wanderer/wanderer'), boardsize=10, timegame=3600, timemove=15) except Exception as e: print e
def on_game(self, *largs): """ Método chamado quando o jogo precisa ser iniciado (pygame) :param largs: lista de argumentos (não utilizado, mas necessário para assinatura do método) :return: nada """ # Transfere os valores do menu para o controlador do jogo GameController.is_multiplayer = self.is_multiplayer GameController.username = self.username[:12] GameController.player_color = self.color if len(self.match) > 0: GameController.match = self.match[:12] else: GameController.match = self.username[:12] GameController.bombs_percentage = self.bombs GameController.rows = max(5,self.rows) GameController.columns = max(10,self.columns) # Inicia o jogo play_game()
def _play_game(self, match): key = match[2] if key in self.results: return away_team = self.league.get_team(match[0]) home_team = self.league.get_team(match[1]) result = game.play_game(away_team, home_team) self.standings[result.get_winner()][0] += 1 self.standings[result.get_loser()][1] += 1 self.results[key] = result
def turn_on(): print('=Turn on game =') while True: choice = input( 'What would you like to do?\n 1: Go Go Shop, 2:Play Game, 3:Message 0: Exit\n Input: ' ) if choice == '0': break elif choice == '1': shop.buy_item() elif choice == '2': game.play_game() elif choice == '3': send_message() else: print('Choice not exist') print('--------------------------') print('==Turn off game==')
def display_stats(generation, gene_pools, sorted_ind_lists, fitness_list, stupid_list, list_limit): print('generation {0}:'.format(generation)) for gene_pool, fitness, stupid, top_indeces in zip( gene_pools, fitness_list, stupid_list, sorted_ind_lists): print(' Gene Pool:') # print( ' gene_pool biases: {0}'.format( sum([ sum([np.sum(b, axis=0) for b in genome.biases]) for genome in gene_pool ]) ) ) print(' gene_pool avg biases: {0}'.format( sum([genome.get_average_bias() for genome in gene_pool]) / len(gene_pool))) print(' gene_pool size: {0}'.format(len(gene_pool))) print(' top stupidity/fitness: {0} / {1}'.format( [stupid[i] for i in top_indeces[:list_limit]], [fitness[i] for i in top_indeces[:list_limit]])) # Print out the board after a game of the top two bots game.play_game(gene_pool[0:2]) game.board.display(indentation=' ') print()
def test_players(p1, p2, n_games): result = { 1: 0, # Player 1 wins 2: 0, # Player 2 wins -1: 0 # Draws } p1.set_player(1) p2.set_player(2) for i in range(n_games): winner,board = play_game(p1, p2, Board()) result[winner] += 1 return result
def main_menu(): img = libtcod.image_load(random.choice(defn.title_screen_choices)) while not libtcod.console_is_window_closed(): #show the background image, at twice the regular console resolution libtcod.image_blit_2x(img, 0, 0, 0) #show the game's title, and some credits! libtcod.console_set_default_foreground(0, libtcod.light_yellow) libtcod.console_print_ex(0, defn.SCREEN_WIDTH / 2, defn.SCREEN_HEIGHT / 2 - 4, libtcod.BKGND_NONE, libtcod.CENTER, 'Mage Wars RL') libtcod.console_print_ex(0, defn.SCREEN_WIDTH / 2, defn.SCREEN_HEIGHT - 2, libtcod.BKGND_NONE, libtcod.CENTER, 'A Roguelike Adventure by ACG') #show options and wait for the player's choice choice = gui.menu('', ['Play a new game', 'Continue last game', 'Quit'], 24) if choice == 0: #new game new_game.new_game() game.play_game() if choice == 1: #load last game gui.msgbox( '\n Sorry - I haven\'nt implemented a save/load feature yet.\n\n-ACG\n', 24) #try: # load_game() #except: # msgbox('\n No saved game to load.\n', 24) # continue #game.play_game() elif choice == 2: #quit break
def intro(screen, world): fps_clock = pygame.time.Clock() # load the ui ui = pygame.image.load(os.path.join('.', 'data', 'ui', 'intro_splash.png')) while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() elif event.type in (KEYDOWN, KEYUP): # start the game! play_game(screen, world) fps_clock.tick(60) screen.fill((0, 0, 0)) screen.blit(ui, (0, 0)) pygame.display.flip()
def calc_stats(pieces, orig_players): global stats for i in range(NUM_STATS_GAMES): stats['num_plays'].append(0) stats['num_branch'].append([]) players = [player.copy() for player in orig_players ] #[player_type(i) for i in range(NUM_PLAYERS)] game_start_time = time.time() play_game(pieces, players) game_end_time = time.time() stats['game_time'].append(game_end_time - game_start_time) stats['avg_branch'].append(np.mean(stats['num_branch'][-1])) stats['max_branch'].append(np.max(stats['num_branch'][-1])) stats['max_branch_turn'].append(np.argmax(stats['num_branch'][-1])) if ((i + 1) * 10) % NUM_STATS_GAMES == 0: print(str(int(100 * (i + 1.0) / NUM_STATS_GAMES)) + '%') print() print('Games played: ' + str(stats['num_games'])) print_str = 'Win %:' for i in range(NUM_PLAYERS): print_str += ' Player ' + str(i + 1) + ' - ' + print_num( 100 * float(stats['num_wins'][i]) / stats['num_games']) + ', ' print(print_str) print('Time per game (s): ' + print_num(np.mean(stats['game_time'])) + ' +\\- ' + print_num(np.std(stats['game_time']))) print('Plays per game: ' + print_num(np.mean(stats['num_plays'])) + ' +\\- ' + print_num(np.std(stats['num_plays']))) print('Avg. branching factor: ' + print_num(np.mean(stats['avg_branch'])) + ' +\\- ' + print_num(np.std(stats['avg_branch']))) print('Max branching factor: ' + print_num(np.mean(stats['max_branch'])) + ' +\\- ' + print_num(np.std(stats['max_branch']))) print('Max branching turn: ' + print_num(np.mean(stats['max_branch_turn'])) + ' +\\- ' + print_num(np.std(stats['max_branch_turn'])) \ + ' (round ' + str(int(np.floor(np.mean(stats['max_branch_turn'])/NUM_PLAYERS))) + ')')
def echo_message(message): waiting_player = players.find_one({ 'id': message.from_user.id, 'status': 'waiting' }) if waiting_player is not None: reply_with_log( message, 'you have already started the game and now you have to wait for others' ) elif message.text == 'start game': players.insert_one({ 'id': message.from_user.id, 'room': default_room, 'status': 'waiting', 'nickname': message.from_user.username or 'anonimous' }) active_players = list( players.find({ 'room': default_room, 'status': 'waiting' })) if len(active_players) <= 2: reply_with_log(message, 'now you should wait for other players') return game, winner, winner_card = play_game(active_players) for player in game.players: if player == winner: bot.send_message(player.id, 'you win!') else: bot.send_message(player.id, 'you lose!') players.update_one( { 'room': default_room, 'status': 'waiting', 'id': player.id }, {'$set': { 'status': 'win' if player == winner else 'lose' }}) else: reply_with_log(message, 'say "start game" to start a game')
from game import play_game play_game()
import game computer_figure = "" player_figure = "" while computer_figure == "": player_figure = input("Wybierz x lub o: ") computer_figure = "" if player_figure == "x": computer_figure = "o" elif player_figure == "o": computer_figure = "x" game.play_game(player_figure, computer_figure)
def complete_game(player_paths): ids, players = zip(*[get_player(p) for p in player_paths]) with redirect_stdout(open("/dev/null", "w")): outcome = game.play_game([p.play for p in players]) return outcome
def guess(username, guess_data): if request.method=="POST": guess_results = game.play_game(username, guess_data) return guess_results
from sys import argv import jsonpickle from human import Human import game log = input("Do you want to log the replay? It will overwrite the previous one! [N]/Y ").lower() == "y" is_different_start_state = input("Do you want to input a different start state? [N]/Y ").lower() == "y" if is_different_start_state: text = "Game_State(0, 0, [" + input("Type it in: ") + "], -1)" current_state = eval(text) else: current_state = Game_State(0, 0, [4,4,4,4,4,4,4,4,4,4,4,4], -1) if len(argv) > 1: replay = open(argv[1], "r").read() game_states = jsonpickle.decode(replay) turn = int(input("On what turn of the replay do you want to start? ")) - 1 try: current_state = game_states[turn] player_1_turn = current_state.is_player_1_turn except e: print("Error: the replay is only", len(game_states), "turns long!") exit() player_1 = Human(True) player_2 = Human(False) print(game.play_game(player_1, player_2, current_state, log), "won the game")
if len(l2) == len(l1): result += [l2[i+1]] return result sumlist=[] for i in range(100): board = Board(percepts = random_board()) p0 = RandomPlayer() p1 = RandomPlayer() play_game((p0, p1), board) #print(p0.listoflen) #print(p1.listoflen) mergelist = merge(p0.listoflen, p1.listoflen) #print(mergelist) for j in range(len(mergelist)): if j < len(sumlist): sumlist[j] += mergelist[j] else: sumlist += [mergelist[j]] #print (sumlist)
bot_gene_pool = evolution.BotEvolution(GENE_POOL_SIZE, GENE_POOL_COUNT) cont = 'c' while (cont == 'c'): smart_pools = bot_gene_pool.evolve(int(input('Generations to evolve for...')), update_generation = 20) gp_index = int(input("Gene pool to play: ")) ind_sb = int(input("Smart Bot: ")) ind_db = int(input("Dumb Bot: ")) try: dumb_bot = smart_pools[gp_index][ind_db] smart_bot = smart_pools[gp_index][ind_sb] except IndexError as ie: print("Invalid gene pool index. Please choose a valid gene pool") continue game.play_game([smart_bot, dumb_bot], show_game = True) cont = input("Game Over. Enter c to continue: ") # Export winner network biases = [ [list(b) for b in biases_layer] for biases_layer in smart_bot.biases ] weights = [ [list(w) for w in weights_layer] for weights_layer in smart_bot.weights ] nNet = {'biases': biases, 'weights': weights} with open ('[net_params]tictactoe_net.json', 'w') as outfile: json.dump(nNet, outfile)
speak("Please Enter a command") if "bye" in x or "quit" in x or "cya" in x or "exit" in x: print(Fore.CYAN + "Bye!! See You Soon" + Fore.RESET) speak("Bye!! See You Soon") exit() if "help" in x: helping() speak("I can help you with above things") elif "thank you" in x or "thanks" in x: p = random.choice(thank) + name print(Fore.CYAN + p + Fore.RESET) speak(p) elif "games" in x or "game" in x: print(Fore.CYAN + play_game() + Fore.RESET) speak("Opening game") elif "movie" in x or "movies" in x: print(Fore.CYAN + "Opening Movie Menu" + Fore.RESET) speak("Opening Movie Menu") p = play_movies() print(Fore.CYAN + p + Fore.RESET) speak(p) elif "whatsapp" in x: whatsapp() elif "mail" in x or "email" in x: name = x.replace("send email to ", "") mail = get_emailId(name) if mail == '0': print("Email Id not found in database, please input mail id") mail = input("Enter mail: ")
def test_AI_play_game(): player1 = player.Player("AI", 1) player2 = player.Player("AI", 2) play_game(6, [player1, player2])
Ruttopallo by Jussi Laitala Pelin ideana on löytää pelilaudalta mahdollisimman monta viiden pallon sarjaa ja vetää viivoja niiden väliin. Jokaisesta viivasta pelaaja saa yhden pisteen ja pallon ja peli päättyy kun vapaita paikkoja ei enää löydy mihin viivan voi vetää. pelitilanne tallennetaan kun pelistä poistuu ja peli jatkuu tästä tilanteesta uudelleen käynnistäessä. Pelissä on käytetty pygamen kirjastoja (https://www.pygame.org) ja tämä moduuli pitäisi olla asennettuna koneelle jotta ohjelman voi suorittaa. Pelin lähdekoodi on vapaasti muokattavissa, jaettavissa ja kopioitavissa. versio 1.0 """ import pygame import game import os from settings import * pygame.init() # alustetaan pygame kirjastot pygame.font.init() # Alustetaan fontit os.environ['SDL_VIDEO_CENTERED'] = '1' # asetetaan peli-ikkuna näytön keskelle screen = pygame.display.set_mode( (SCREEN_W, SCREEN_H)) # alustetaan ikkuna pelille pygame.display.set_caption("Ruttopallo") # määritetään nimi peli-ikkunalle game_image = pygame.image.load("images/ruttopallo.png") pygame.display.set_icon(game_image) # ladataan pelin ikoni ikkunalle game = game.Game(screen) # uusi olio pelille game.play_game() # suoritetaan peli pygame.display.quit() # lopetetaan peli-ikkuna
def test_restart_undo(): sys.stdin = open("test_input_files/input_restart_undo.txt") player1 = player.Player("asdfgh", 1) player2 = player.Player("adsdfgh", 2) assert play_game(6, [player1, player2]) == 2
def main(): olog.info(ZORK_INTRO) olog.info('oops, wrong game!. Now, what do we have here?') olog.info('\n====== Dungeon Game! ======\n') play_game(SIZE)
import game as g import player as p import numpy as np import matplotlib.pyplot as plt import utilities as u players = [] players.append(p.CleverPlayer('Clever')) players.append(p.CleverPlayer('Clever2')) g = g.Game(players) #old = u.blockPrint() data = g.play_game(N=1000) #u.enablePrint(old) #for player in players: # #g.game_stats[player].display() # plt.plot(g.game_stats[player].stack_history,label=player.name) # plt.legend() #g.game_stats[players[0]].display()
result += [l1[i + 1]] if len(l2) == len(l1): result += [l2[i + 1]] return result sumlist = [] for i in range(100): board = Board(percepts=random_board()) p0 = RandomPlayer() p1 = RandomPlayer() play_game((p0, p1), board) #print(p0.listoflen) #print(p1.listoflen) mergelist = merge(p0.listoflen, p1.listoflen) #print(mergelist) for j in range(len(mergelist)): if j < len(sumlist): sumlist[j] += mergelist[j] else: sumlist += [mergelist[j]] #print (sumlist)
from human import Human from random_player import Random from default_ai import Default_AI import game log = input("Do you want to log the replay? It will overwrite the previous one! [N]/Y ").lower() == "y" is_different_start_state = input("Do you want to input a different start state? [N]/Y ").lower() == "y" if is_different_start_state: text = "Game_State(0, 0, [" + input("Type it in: ") + "], -1)" current_state = eval(text) else: current_state = Game_State(0, 0, [4,4,4,4,4,4,4,4,4,4,4,4], -1) if len(argv) > 1: replay = open(argv[1], "r").read() game_states = jsonpickle.decode(replay) turn = int(input("On what turn of the replay do you want to start? ")) - 1 try: current_state = game_states[turn] player_1_turn = current_state.is_player_1_turn except e: print("Error: the replay is only", len(game_states), "turns long!") exit() player_1 = Default_AI() player_2 = Random() print(game.play_game(player_1, player_2, current_state, log, False))
log = False is_different_start_state = False if is_different_start_state: text = "Game_State(0, 0, [" + input("Type it in: ") + "], -1)" current_state = eval(text) else: current_state = Game_State(0, 0, [4,4,4,4,4,4,4,4,4,4,4,4], -1) if len(argv) > 1: replay = open(argv[1], "r").read() game_states = jsonpickle.decode(replay) turn = int(input("On what turn of the replay do you want to start? ")) - 1 try: current_state = game_states[turn] player_1_turn = current_state.is_player_1_turn except e: print("Error: the replay is only", len(game_states), "turns long!") exit() player_1 = Monte_Carlo(100) player_2 = Human(False) winner = game.play_game(player_1, player_2, current_state, log)[0] if winner == 1: print("AI wins!") else: print("The human wins!")
from helper import reset from game import play_game, player_input if __name__ == "__main__": play_again = True player_1, player_2 = player_input() while play_again: i, sample, valid = reset() play_game(i, valid, sample, player_1, player_2) replay_decide = input('Do you want to play again? Choose Y or N: ') play_again = replay_decide.upper() == 'Y' pass
import game from gameResources import get_random_word_meaning name = input("What is your name? ") print(f"Hello {name}! Welcome to The Vocab_Builder") print(f"Word of the Day: {get_random_word_meaning()}") print() while True: play_choice = input("Shall we enter the Arena? Y/N: ") if play_choice == 'y' or play_choice == 'Y': print("Now let's start the Game") game.play_game() print("Thank You ! Have a nice day!") break elif play_choice == 'N' or play_choice == 'n': print("Thank You ! Have a nice day!") break else: print("Invalid Input!") continue
agents = [ q_ag, OneLookAheadAgent(1, 4), OneLookAheadAgent(2, 4), OneLookAheadAgent(3, 4), ] episodes, winrates = \ q_ag.train(2000, 0.3, 0.97, epsilon_min=0.005, test_every_n_epsiodes=50, number_of_test_games=10, test_against=agents[1:], use_softmax_with_temperature=True) plt.plot(episodes, winrates) plt.xlabel("Episodes") plt.ylabel("Win rate") plt.show() game.play_game(agents, True) model.save("temp.h5") scores = [] wins = defaultdict(lambda: 0) # switched = False for i in range(100): score = game.play_game(agents, False, shuffle_agents=True) score_list = [] for ag in agents: score_list.append(score[ag]) # if switched: # score[0], score[1] = score[1], score[0]
def complete_game(player_paths): ids, players = zip(*[get_player(p) for p in player_paths]) with redirect_stdout(open('/dev/null', 'w')): outcome = game.play_game([p.play for p in players]) return outcome