from game import Game import numpy as np arr = np.array([["-","-","-"], ["-","-","-"], ["-","-","-"]]) i = 0 game = Game(arr) while game.vacant != 0 and game.isEnd == False: i += 1 game.update_auto() print(str(i)+"------------") time.sleep(1) if game.vacant == 0 and game.isEnd == False: print("引き分け")
def move(self, state): print pretty_map(Game(state)) return self.to_dir(raw_input())
def self_play(simulation, game_nr): """ Let the ConnectNet play a number of games against itself. Each moves is decided by the Monte Carlo Tree Search. Values are seeded by the neural network. We need to create the neural network here, because the lack of support for multiprocessing by Tensorflow. """ # Random seed, otherwise all workers have the same random actions random.seed() np.random.seed() from connect_net import ConnectNet try: # Get the identity of the sub-process worker = multiprocessing.current_process()._identity[0] # Only one worker should print should_print = (worker % simulation.workers == 0) # Not multiprocessing except: should_print = True # # Perform self play with the latest neural network net = ConnectNet(simulation.net_name, only_predict=True) net.load('best', should_print) for _ in range(1): # Create a new empty game game = Game() states = [] # Storage for all game states states_values = [] # Storage for all game states with game outcome move_count = 0 done = False # Keep playing while the game is not done while not done: # Root of the search tree is the current move root = Node(game=game) if should_print: print(f'Game: {game_nr}', 'Move:', '\033[95mX\033[0m' if game.player == -1 else '\033[92mO\033[0m', '\n') # Explore for the first 10 moves, after that exploit if move_count <= 10: temperature = 2 else: temperature = 0.1 # Encoded board encoded_board = deepcopy(game.encoded()) # Run UCT search root = Simulation.mcts(root, simulation.moves_per_game, net, add_noise=True) # Get the next policy policy = Simulation.get_policy(root, temperature) # Decide the next move based on the policy move = np.random.choice(np.array([0, 1, 2, 3, 4, 5, 6]), p=policy) # Increase the total moves move_count += 1 # Make the move game.play(move) # Log status to the console if should_print: q_value = (root.child_Q()[move]) Simulation.console_print(game_nr, encoded_board, game, policy, net, q_value) # Store the intermediate state states.append((encoded_board, policy)) # If somebody won if game.won(): if (game.player * -1) == -1: if should_print: print('\033[95mX Won!\033[0m \n') if (game.player * -1) == 1: if should_print: print('\033[92mO Won!\033[0m \n') value = 1 # Store board states for training (alternate ) for state in states[:0:-1]: states_values.append((state[0], state[1], value)) value *= -1 # Empty board has no value states_values.append((states[0][0], states[0][1], 0)) # Mark game as done done = True # Game was a draw elif game.moves() == []: if should_print: print('Draw! \n') # Set all values to 0 for state in states: states_values.append((state[0], state[1], 0)) done = True # Store games as a side-effect (because of multiprocessing) simulation.memory.remember(states_values[::-1], game_nr)
colors['midnight green'], colors['neon green'], colors['rosewood'], colors['flame'] ) card_menu = BasicMenu(465, 400, 150, 40, ['Guard', 'Priest', 'Baron', 'Handmaid', 'Prince', 'King', 'Countess', 'Princess'], colors['flame'], colors['rosewood'], colors['rosewood'], colors['flame'], colors['midnight green'], colors['neon green'] ) game = Game([player1, player2, player3, player4]) game.restart() game.begin_turn() convert_images(game.display) print(game.deck) print(len(game.deck)) print((5/6) * display_width - card_width) running = True while running: data_past = game.get_data() data_next = dict() chosen_card = -1 command = ''
def move(self, state): """Determine which way the bot should move given game state.""" ##### ADMIN AND GAME MANAGEMENT ############################# t0 = time.time() myId = state['hero']['id'] game = Game(state, myId) if self.turn < 2: self.game_setup(game) self.update(game) # print game info if (self.turn % SHOW_MAP_EVERY_X_TURNS == 0): print '' print pretty_map(game, SHOW_CUSTOM_MAP) write_gamestate(state) print self.summary() ##### ADMIN COMPLETE - START WORKING ACTUAL MOVEMENT ######## direction = None #reeval goal every time self.goal = self.determine_goal(game, state) print "executing goal: " + str(self.goal) #clear all waypoints self.remove_all_waypoints() if self.goal[0] == HEAL: self.add_waypoint(self.determine_dest(HEAL, game)[0]) else: self.add_waypoint((self.goal[1][0], self.goal[1][1])) if self.get_current_waypoint(): #TODO see brett's calculation for when to heal #if health is low, go heal """if game.myHero.life < 30: self.remove_all_waypoints() self.add_waypoint(self.determine_dest(HEAL, game)) """ self.mode = TRAVEL path = self.pf.get_path(self.pos, self.get_current_waypoint(), game.board, self.path_heuristic) #make sure we have a valid path, if not revert to heal searches = 1 while (path == [self.pos, self.pos]) and self.goal != DEFEND: self.remove_current_waypoint() self.add_waypoint( self.determine_dest(HEAL, game, randomness=True)[0]) path = self.pf.get_path(self.pos, self.get_current_waypoint(), game.board, self.path_heuristic) searches = searches + 1 if searches > MAX_SEARCHES: path = [self.pos, self.pos] break ###self.evaluate_waypoints() # This version seems to do well """ # Make progress toward destination if any(self.waypoints): wpt = self.get_current_waypoint() path = self.pf.get_path(self.pos, wpt, game.board, self.path_heuristic) else: print 'No waypoints!!!' path = [self.pos, self.pos] # if no valid path found, remove waypoint, add randomness, and try again searches = 1 while (path == [self.pos, self.pos]): self.remove_current_waypoint() if not self.waypoints: self.add_waypoints(self.determine_dest(self.goal, game, randomness=True)) next_wpt = self.get_current_waypoint() path = self.pf.get_path(self.pos, next_wpt, game.board, self.path_heuristic) searches += 1 if searches > MAX_SEARCHES: path = [self.pos, self.pos] break """ print 'Current path:', path print 'Distance:', len(path) - 1 if len(path) > 1: next_pos = path[1] else: next_pos = self.pos print 'Next move:', next_pos direction = self.pf.get_dir_to(self.pos, next_pos) print 'Direction:', direction # test if bot has arrived at waypoint #if game.board.to(self.pos, direction) == self.get_current_waypoint(): # self.remove_current_waypoint() ##### MORE INFORMATION AND TIME/GAME MANAGEMENT ############# print '' # self.print_comparison_tests(game) # Safety check -- I think bad dirs can cause HTTP 400 Errors - kbm direction = safety_check(direction) self.record_move(direction) # track all moves td = time.time() - t0 # Time check if (td > TIME_THRESHOLD): print "Close on time!!!", td print 'Response time: %.3f' % td return direction
beta = min(beta, score) return chosen_child, score def make_move(init_game: Game, who_plays: int, depth: int = 2): root = Node(State(init_game, who_plays)) best_choice, alpha_beta_value = alpha_beta(root, depth=depth, alpha=-math.inf, beta=math.inf, maximizing_player=True) print_tree(root) return best_choice.name.game, [ "MOV", len(best_choice.name.move), best_choice.name.move ] if __name__ == '__main__': init_pop = { Game.Human: [[(2, 2), 10]], Game.Vampire: [[(1, 2), 10]], Game.Werewolf: [[(3, 4), 3], [(3, 3), 3], [(4, 3), 4]] } game = Game(5, 5, init_pop) # s = State(game, Game.Werewolf) decision, command = make_move(game, Game.Vampire) print(decision) print(command)
gm.setnbCaseV(int(split_string[1])) elif split_string[0] == "MAP": gm.setMap(loadMap(gm, file)) elif split_string[0] == "WAVE": gm.setWaves(loadWave(gm, file)) line = file.readline() split_string = line.split(" ") if (gm.getWidth() == 0 or gm.getHeight() == 0): print("ERROR height or width not found") return gm.setCaseW(gm.width / gm.nbCaseH) gm.setCaseH(gm.height / gm.nbCaseV) file.close() if __name__ == "__main__": pygame.init() gm = Game() parseFile(gm) gm.setScreen() pygame.display.set_caption('Tower defense') gm.screen.fill(gm.BLACK) pygame.display.flip() gm.generateEnnemies() print(gm) while gm.running: gm.handleEvents() gm.updateMap() pygame.quit()
def levelSelector(): jeu = Game() pygame.font.init() blocks = [ pygame.image.load("templates/templatesmini/brick.png"), pygame.image.load("templates/templatesmini/snow.png"), pygame.image.load("templates/templatesmini/finishflag.png"), pygame.image.load("templates/templatesmini/start.png"), pygame.image.load("templates/templatesmini/lava.png"), ] bumpers = [ pygame.image.load("templates/templatesmini/ArrowUp.png"), pygame.image.load("templates/templatesmini/ArrowDown.png"), pygame.image.load("templates/templatesmini/ArrowLeft.png"), pygame.image.load("templates/templatesmini/ArrowRight.png"), pygame.image.load("templates/templatesmini/Levier.png"), ] switchers = [ pygame.image.load("templates/templatesmini/SwitcherLR.png"), pygame.image.load("templates/templatesmini/SwitcherUD.png"), pygame.image.load("templates/templatesmini/leverOff.png"), pygame.image.load("templates/templatesmini/leverOn.png"), ] class listLevels: nbrNormalLevels = 0 nbrPersoLevels = 0 def __init__(self, name, level, record, typelevel, i): self.name = name self.level = level self.x = 100 self.i = i self.wr = record self.font = pygame.font.Font("fonts/PixelOperatorMono8-Bold.ttf", 16) if typelevel == "normal": self.y = 50 + 150 * listLevels.nbrNormalLevels self.typeLevel = "normal" listLevels.nbrNormalLevels += 1 if typelevel == "perso": self.y = 50 + 150 * listLevels.nbrPersoLevels self.typeLevel = "perso" listLevels.nbrPersoLevels += 1 def show(self, fen, buttons): for col in range(15): for lig in range(15): x, y = miniConvert(lig, col) if self.level[lig][col] == 0: pygame.draw.rect( fen, (0, 0, 0), (self.x + x, self.y + y, 10, 10) ) if self.level[lig][col] == 1: fen.blit(blocks[0], (self.x + x, self.y + y)) if self.level[lig][col] == 2: fen.blit(blocks[3], (self.x + x, self.y + y)) if self.level[lig][col] == 3: fen.blit(blocks[2], (self.x + x, self.y + y)) if self.level[lig][col] == 4: fen.blit(blocks[1], (self.x + x, self.y + y)) if self.level[lig][col] == 5: fen.blit(blocks[4], (self.x + x, self.y + y)) if self.level[lig][col] == 6: fen.blit(bumpers[0], (self.x + x, self.y + y)) if self.level[lig][col] == 7: fen.blit(bumpers[1], (self.x + x, self.y + y)) if self.level[lig][col] == 8: fen.blit(bumpers[2], (self.x + x, self.y + y)) if self.level[lig][col] == 9: fen.blit(bumpers[3], (self.x + x, self.y + y)) if self.level[lig][col] == 10: fen.blit(bumpers[4], (self.x + x, self.y + y)) if self.level[lig][col] == 11: fen.blit(switchers[0], (self.x + x, self.y + y)) if self.level[lig][col] == 12: fen.blit(switchers[1], (self.x + x, self.y + y)) if self.level[lig][col] == 13: fen.blit(switchers[2], (self.x + x, self.y + y)) if self.level[lig][col] == 14: fen.blit(switchers[3], (self.x + x, self.y + y)) pygame.draw.rect(fen, (255, 255, 255), (self.x, self.y, 400, 150), 1) pygame.draw.rect(fen, (255, 255, 255), (self.x, self.y, 150, 150), 1) if buttons: fen.blit(buttons[6], (self.x + 150, self.y + 100)) fen.blit(buttons[5], (self.x + 350, self.y + 100)) textname = self.font.render(self.name, True, (255, 255, 255)) fen.blit(textname, (self.x + 275 - (8 * len(self.name)), self.y + 60)) recordText = self.font.render( "WR : {}".format(convertShortTime(self.wr)), True, (245, 176, 65) ) if self.typeLevel == "normal": fen.blit(recordText, (self.x + 165, self.y + 120)) else: fen.blit(recordText, (self.x + 165, self.y + 80)) def scroll(dir, levels): for lvl in levels: lvl.y += dir def show(fen, imgs, status): pygame.draw.rect(fen, (0, 0, 0), (0, 0, 600, 50)) fen.blit(imgs[4], (550, 550)) if status == "normal": fen.blit(imgs[1], (0, 0)) fen.blit(imgs[2], (300, 0)) if status == "perso": fen.blit(imgs[0], (0, 0)) fen.blit(imgs[3], (300, 0)) win = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() pygame.display.set_caption("SLIDE - Level Selector") scrollspeed = 20 buttons = [ pygame.image.load("menuframes/normallevel.png"), pygame.image.load("menuframes/normallevel_selected.png"), pygame.image.load("menuframes/editorlevel.png"), pygame.image.load("menuframes/editorlevel_selected.png"), pygame.image.load("MenuFrames/editor_exit.png"), pygame.image.load("MenuFrames/trash.png"), pygame.image.load("MenuFrames/edit.png"), ] listNormalLevel = [] listPersoLevel = [] actualLevelDisplay = "normal" with open("level_data/normal_level.json") as f: normal_levels = json.load(f) i = 0 for data in normal_levels: if data["level_name"] != "pattern" and data["level_name"] != "Secret Level": listNormalLevel.append( listLevels( data["level_name"], data["level_composition"], data["WR"], "normal", i, ) ) i += 1 with open("level_data/editor_level.json") as f: editor_levels = json.load(f) i = 0 for data in editor_levels: if data["level_name"] != "pattern": listPersoLevel.append( listLevels( data["level_name"], data["level_composition"], data["WR"], "perso", i, ) ) i += 1 levelselector = True while levelselector: win.fill((0, 0, 0)) clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: levelselector = False return if ( event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and event.pos[0] > 0 and event.pos[0] < 300 and event.pos[1] > 0 and event.pos[1] < 50 ): actualLevelDisplay = "normal" if ( event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and event.pos[0] > 300 and event.pos[0] < 600 and event.pos[1] > 0 and event.pos[1] < 50 ): actualLevelDisplay = "perso" if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 4: if actualLevelDisplay == "normal": if listNormalLevel[0].y < 50: scroll(scrollspeed, listNormalLevel) elif actualLevelDisplay == "perso": if len(listPersoLevel) > 0 and listPersoLevel[0].y < 50: scroll(scrollspeed, listPersoLevel) elif event.button == 5: if actualLevelDisplay == "normal": if listNormalLevel[-1].y > 450: scroll(-scrollspeed, listNormalLevel) elif actualLevelDisplay == "perso": if len(listPersoLevel) > 0 and listPersoLevel[-1].y > 450: scroll(-scrollspeed, listPersoLevel) if ( event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and event.pos[0] > 100 and event.pos[0] < 500 and event.pos[1] > 50 and event.pos[1] < 600 ): if actualLevelDisplay == "normal": for lvl in listNormalLevel: if event.pos[1] > lvl.y and event.pos[1] < lvl.y + 150: jeu.level = lvl.level jeu.testLevel() if actualLevelDisplay == "perso": for lvl in listPersoLevel: if event.pos[1] > lvl.y and event.pos[1] < lvl.y + 150: if event.pos[0] > 450 and event.pos[1] > lvl.y + 100: listPersoLevel = deleteLevel(listPersoLevel, lvl.i) elif ( event.pos[0] > 250 and event.pos[0] < 300 and event.pos[1] > lvl.y + 100 ): jeu.level = lvl.level jeu.runEditor() else: jeu.level = lvl.level jeu.testLevel("editor") if ( event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and event.pos[0] > 550 and event.pos[0] < 600 and event.pos[1] > 550 and event.pos[1] < 600 ): levelselector = False return if actualLevelDisplay == "normal": for lvl in listNormalLevel: lvl.show(win, None) elif actualLevelDisplay == "perso": for lvl in listPersoLevel: lvl.show(win, buttons) show(win, buttons, actualLevelDisplay) pygame.display.update()
def create_game(): game_id = uuid() GAMES[game_id] = Game() LOGGER.info(f'Created game {game_id}. GAMES is now {GAMES}') join_room(game_id) return {'game_id': game_id}
def __init__(self, state): self.simulator = Game() self.simulator.reset(*state) #using * to unpack the state tuple self.root = Node(state, self.simulator.get_actions())
def game_loop(args): ## Create Client Process client = Client() if args.exe.endswith('.py'): client.CreateChildProcess('python', args.exe) elif args.exe.endswith('.sh'): client.CreateChildProcess('sh', args.exe) else: client.CreateChildProcess('sh', args.exe) ## Connect Client with Server client.Connect2Server(args.ip, args.port) server_string = client.RecvDataFromServer() if(server_string is None): print('ERROR IN SETTING UP CONNECTIONS. SORRY') sys.exit(0) ## Initialize Client server_string_list = server_string.strip().split() player_id = server_string_list[0] rows = int(server_string_list[1]) cols = int(server_string_list[2]) game_timer = int(server_string_list[3]) client.setGameTimer(game_timer) print('***********************************\n') print('-> You are player ' + str(player_id)) print('-> You are alloted a time of ' + str(game_timer) + 's\n') print('***********************************\n') game = Game(rows, cols, args.mode, game_timer) client.SendData2Process(server_string) ## Initialize Process ''' Execute Game Moves ''' if player_id == '2': move = client.RecvDataFromServer() if move: move = move.strip() print("Player 1 played : " + move) success = game.execute_move(move) client.SendData2Process(move) else: sys.exit(0) while(True): ### Execute Current Player's Move move = client.RecvDataFromProcess() if move['action'] == 'KILLPROC': move['meta'] = move['meta'] + ' BY PLAYER ' + player_id + \ ' : Player ' + str(player_id) + ' SCORE : ' + str(game.get_score(player_id, player_id)) + \ ' : Player ' + str(int(player_id)%2+1) + ' SCORE : ' + str(game.get_score(int(player_id)%2+1, player_id)) client.SendData2Server(move) break if move['action'] == 'FINISH': # TIMEOUT move['meta'] = move['meta'] + ' BY PLAYER ' + player_id + \ ' : Player ' + str(player_id) + ' SCORE : ' + str(game.get_score(player_id, player_id)) + \ ' : Player ' + str(int(player_id)%2+1) + ' SCORE : ' + str(game.get_score(int(player_id)%2+1, player_id)) client.SendData2Server(move) break move['data'] = move['data'].strip() print("You played : " + move['data']) success = game.execute_move(move['data']) message = {} ### Success # 0: Invalid State # 1: Normal State # 2: Game Over (Someone Wins) Note) Even Drawn State Will result in Game Over if success == 0: message['data'] = '' message['action'] = 'KILLPROC' message['meta'] = 'INVALID MOVE BY PLAYER ' + player_id + \ ' : Player ' + str(player_id) + ' SCORE : ' + str(game.get_score(player_id, player_id)) + \ ' : Player ' + str(int(player_id)%2+1) + ' SCORE : ' + str(game.get_score(int(player_id)%2+1, player_id)) print('INVALID MOVE ON THIS CLIENT') elif success == 1: message = move elif success == 2: message['action'] = 'FINISH' message['data'] = move['data'] message['meta'] = 'Player ' + str(player_id) + ' SCORE : ' + str(game.get_score(player_id)) + \ ' : Player ' + str(int(player_id)%2+1) + ' SCORE : ' + str(game.get_score(int(player_id)%2+1)) print('YOU WIN!') if player_id == '1': print('Your Score : ' + str(game.get_score(1))) print('Opponent\'s Score : ' + str(game.get_score(2))) else: print('Your Score : ' + str(game.get_score(2))) print('Opponent\'s Score : ' + str(game.get_score(1))) client.SendData2Server(message) if message['action'] == 'FINISH' or message['action'] == 'KILLPROC': break ## Listen to Other Player's Move move = client.RecvDataFromServer() if move: move = move.strip() if player_id == '1': print("Player 2 played : " + move) else: print("Player 1 played : " + move) success = game.execute_move(move) if success == 2: print('OTHER PLAYER WINS!') if player_id == '1': print('Your Score : ' + str(game.get_score(1))) print('Opponent\'s Score : ' + str(game.get_score(2))) else: print('Your Score : ' + str(game.get_score(2))) print('Opponent\'s Score : ' + str(game.get_score(1))) break else: client.SendData2Process(move) else: break client.closeChildProcess() client.closeSocket()
def __init__(self, name="TestPlayer", money=0, default_bet=1): super(TestPlayer, self).__init__(name, money) self.default_bet = default_bet def play(self, dealer, players): print("STAND\n") return "s" def bet(self, dealer, players): return 10 if __name__ == '__main__': players = [TestPlayer("test", 100)] print(players) g = Game(players, debug=True, shoe=TestShoe( [Card(3, 9), Card(1, 8), Card(1, 7), Card(2, 4), Card(3, 9)])) g.run() print("OVERALL: ", players) if str(players) == "[test (100€)]": sys.exit(0) sys.exit(1)
def loadLevel(self, level): self.screen.clear() self.game.stop() self.game = Game(self, level) self.game.start()
def __init__(self, games = []): self._games = games if len(games) is not 0 else\ [Game(g['name'], g['choices'], g['max']) for g in GAMES]
def setUp(self) -> None: self.config = GameConfig(sandbox=False, must_include=[Bandit]) self.players = [Mock(), Mock()] self.game = Game(self.config, self.players)
from game import Game game = Game() # Objects of the class Game are Talk of the Town simulations print "Simulating a town's history..." # Simulate until the summer of 1979, when gameplay takes place try: game.establish_setting() # This is the worldgen procedure except KeyboardInterrupt: # Enter "ctrl+C" (a keyboard interrupt) to end worldgen early pass print "\nPreparing for gameplay..." game.enact_no_fi_simulation( ) # This will tie up a few loose ends in the case of worldgen being terminated early print '\nIt is now the {date}, in the town of {city}, pop. {population}.\n'.format( date=game.date[0].lower() + game.date[1:], city=game.city.name, population=game.city.population) # Print out businesses in town print '\nThe following companies currently operate in {city}:\n'.format( city=game.city.name) for c in game.city.companies: print c # Print out former businesses in town to briefly explore its history for c in game.city.former_companies: print c # Procure and print out a random character in the town p = game.random_person print '\nRandom character: {random_character}\n'.format(random_character=p) # Print out this character's relationships with every other resident in town for r in game.city.residents: print p.relation_to_me(r) # Explore this person's mental models
from game import Game import pandas as pd pygame.init() # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) # Create window size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Pong neural network") game = Game(screen) game.load(0) # try: # x = pd.read_csv("x.csv", delimiter=',').to_numpy().T # y = pd.read_csv("y.csv", delimiter=',').to_numpy().T # for i in range(1): # game.feed(x, y) # game.save(0) # game.show_cost() # except Exception: # print("Error loading data and training") # End loop flag
from game import Game new_game = Game() new_game.game()
from game import Game from board import Board if __name__ == "__main__": board = Board(5) game = Game(board) game.play()
############################################################ ## Solving tic-tac-toe using deep reinforcement learning.(accessed 14 April, 2019).url:https://github.com/yanji84/tic-tac-toe-rl. ############################################################ import tensorflow as tf import numpy as np import random from collections import deque from rl.deep_q_network import DeepQNetwork from game import Game from game import penalty # initialize game env env = Game() # initialize tensorflow sess = tf.Session() optimizer = tf.train.RMSPropOptimizer(learning_rate=0.0001, decay=0.9) writer = tf.summary.FileWriter("logs/value_network", sess.graph) # prepare custom tensorboard summaries episode_reward = tf.Variable(0.) tf.summary.scalar("Last 100 Episodes Average Episode Reward", episode_reward) summary_vars = [episode_reward] summary_placeholders = [tf.placeholder("float") for i in range(len(summary_vars))] summary_ops = [summary_vars[i].assign(summary_placeholders[i]) for i in range(len(summary_vars))] # define policy neural network state_dim = 9 num_actions = 9
from game import Game if __name__ == '__main__': g = Game() g.new_simulation()
from game import Game if __name__ == '__main__': newGame = Game() newGame.start()
import pygame from game import Game if __name__ == "__main__": game = Game() game.loop() game.end()
import pygame from settings import Settings from game import Game pygame.mixer.pre_init(44100, -16, 2, 2048) pygame.init() game = Game(pygame.display.set_mode(Settings.initialWindowSize)) pygame.display.set_caption(Settings.caption) pygame.display.set_icon(pygame.image.load(Settings.mainWindowIconPath)) clock = pygame.time.Clock() while True: game.handleEvents() game.updateAndDraw() clock.tick(Settings.maxFPS)
def move(self, state): game = Game(state) dirs = ['Stay', 'North', 'South', 'East', 'West']
from states import * from game import Game #note: widths greater that 80 are only allowed in windows 10 options = { 'width': 80, 'height': 40, 'tick': 100, 'title': 'pipes' } #initialize the game object game = Game(options) #start the InitialState game state game.start(PipesState)
def duel(self, first_net='checkpoint', second_net='best'): """ Let two models dual to see which one is better. """ # Random seed, otherwise all workers have the same random actions random.seed() np.random.seed() from connect_net import ConnectNet first = ConnectNet(self.net_name) first.load(first_net) second = ConnectNet(self.net_name) second.load(second_net) # Take turns playing nets = [first, second] shuffle(nets) turns = cycle(nets) # Create a new empty game game = Game() done = False move_count = 0 while not done and game.moves() != []: net = next(turns) # Create a new root node root = Node(game=game) # Encoded board # encoded_board = deepcopy(game.encoded()) # Run MCTS root = Simulation.mcts(root, self.moves_per_game, net) # Get the next policy temperature = 1.3 if move_count <= 7 else 0.1 policy = Simulation.get_policy(root, temperature) print('Turn for:', net.version) print('Visits: ', root.child_number_visits) print('Policy: ', policy, '\n') # policy_pred, value_pred = net.predict(encoded_board) # print('Net policy:', policy_pred) # print('Value pred:', value_pred) # Decide the next move based on the policy move = np.random.choice(np.array([0, 1, 2, 3, 4, 5, 6]), p=policy) # print('Q value: ', root.child_Q()[move], '\n') # Make the move game.play(move) game.presentation() print() # If somebody won if game.won(): # print('Winner', net.version) return net.version # Mark game as done done = True move_count += 1 return 'draw'
def setUp(self): self.test_game = Game()
from game import Game wn = turtle.Screen() wn.bgcolor('black') wn.setup(width=1600, height=900) wn.tracer(0) enemyTHEM = enemy.Boomyzoomy() enemyTHEM2 = enemy.Boomyzoomy() enemyTHEM3 = enemy.Boomyzoomy() enemies = [enemyTHEM, enemyTHEM2, enemyTHEM3] playerME = player.Player() wn.listen() wn.onkeypress(playerME.left, 'a') wn.onkeypress(playerME.right, 'd') game = Game(playerME, enemies) loopCounter = 0 while True: loopCounter += 1 if loopCounter >= 100000: loopCounter = 0 game.moveEnemies(loopCounter) wn.update()
def begin_game(): psdo = input("Entrez un pseudo:") pygame.init() # generer la fenetre du jeu pygame.display.set_caption("SPACE GAME- Player: ") screen = pygame.display.set_mode((1080, 620)) background = pygame.image.load('im/bg1.jpg') # importer et charger la banière banner = pygame.image.load('im/project.png') banner = pygame.transform.scale(banner, (250, 250)) banner_rect = banner.get_rect() banner_rect.x = screen.get_width() / 2.65 # math.ceil banner_rect.y = screen.get_height() / 4.7 # importer et charger un bouton pour lancer la partie play_button = pygame.image.load('im/button.png') play_button = pygame.transform.scale(play_button, (400, 150)) play_button_rect = play_button.get_rect() play_button_rect.x = screen.get_width() / 3.25 play_button_rect.y = screen.get_height() / 2 # importer et charger les 2 boutons restart save_button = pygame.image.load('im/save.png') save_button_rect = save_button.get_rect() save_button_rect.x = screen.get_width() / 1.3 save_button_rect.y = screen.get_height() / 1.5 rest_button = pygame.image.load('im/arrows.png') rest_button_rect = rest_button.get_rect() rest_button_rect.x = screen.get_width() / 5.3 rest_button_rect.y = screen.get_height() / 1.5 # charger le joueuer # charger jeu game = Game() running = True # boucle tant que cette condition est vraie while running: # appliquer arriere plan screen.blit(background, (0, -400)) # verifier si le jeu a commencé if game.is_playing and game.is_playing != "transition": # declencher les instructions game.update(screen) # verifier si le jeu n'a pas commencé elif game.is_playing == "transition": font = pygame.font.Font(None, 30) save_score = font.render("Save score & Restart ?", True, (255, 255, 255)) just_retry = font.render("Don't save & Restart ?", True, (255, 255, 255)) current_score = pygame.font.Font(None, 36).render( "You scored " + str(game.score.local_score) + " points", True, (255, 255, 255)) screen.blit(current_score, (410, 50)) screen.blit(just_retry, (125, 485)) screen.blit(save_score, (750, 485)) screen.blit(banner, banner_rect) screen.blit(rest_button, rest_button_rect) screen.blit(save_button, save_button_rect) else: # ajouter l'ecran de bienvenue screen.blit(banner, banner_rect) screen.blit(play_button, play_button_rect) # mettre à jour l'ecran pygame.display.flip() # si le joueur ferme cette fenetre for event in pygame.event.get(): # verifier que l'evenet est fermeture de fene if event.type == pygame.QUIT: running = False pygame.quit() print("Fermeture. Aurevoir ") print("Vous avez: " + str(game.score.best_score) + " points") # print(score.store_score()) # si joueur lache une touche du clavier elif event.type == pygame.KEYDOWN: game.pressed[event.key] = True # detecter si la touche espace est enclenchée if event.key == pygame.K_SPACE: game.player.launch_projectile() elif event.type == pygame.KEYUP: # touche plus utilisée game.pressed[event.key] = False elif event.type == pygame.MOUSEBUTTONDOWN: # verifier si la souris est en collision avec le bouton joué if play_button_rect.collidepoint( event.pos) and not game.is_playing: # mettre le jeu en mode lancé game.start() elif rest_button_rect.collidepoint( event.pos) and game.is_playing == "transition": game.start() elif save_button_rect.collidepoint( event.pos) and game.is_playing == "transition": game.start() data_base.save_to_db(psdo, game.score.local_score)