def gameLost(): score = session['player_score'] game = Game() theme = game.getRandomTheme() hint = game.getHint(theme) word = game.getWord(theme) return jsonify(hint=hint, word=word, score=score)
def display(genome, config): fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5)) x = randint(-7, 7) y = randint(-7, 7) game = Game(Ponyo(genome, config), Shark(), (x, y)) im1 = ax1.imshow(game.board(100), cmap=cmap, norm=norm, interpolation='none') im2 = ax2.imshow(game.ponyo_vision(), cmap=cmap, norm=norm, interpolation='none') # Helper function that updates the board and returns a new image of # the updated board animate is the function that FuncAnimation calls def update(frame): game.move_ponyo() game.move_shark() # print(game.shark_position) if game.catched(): game.finished = True im1.set_data(game.board(50)) im2.set_data(game.ponyo_vision()) ax1.title.set_text(f'frame: {game.frame} energy: {game.ponyo.energy}') return ax1, ax2 ani = animation.FuncAnimation(fig, update, frames=game.generator, blit=False, repeat = False) plt.show()
def tree_sim(self, state, player_names): players = [] for name in player_names: players.append(CNNPlayer(name, tree=self.tree, model=self.model)) game = Game(players) game.set_state(state) for player in game.play(): yield game
def test_move_one_step(self): """ This map can be done in one step. ##### 01110 ##@## 01@10 ##### 01110 """ mine_map = Map(5, 5, mine_pos_list=[(2, 2)]) game = Game(mine_map) state = game._sweep((0, 0)) self.assertEqual(state, 2)
def hangman(): try: score = session['player_score'] except Exception as e: return redirect(url_for('index')) game = Game(); theme = game.getRandomTheme(); hint = game.getHint(theme); word = game.getWord(theme); return render_template("hangman.html",hint=hint, word=word, score=score)
class TicTacToeGameGrid(StackLayout): MAPPING = ["00","01","02","10","11","12","20","21","22"] xo_cell_0 = ObjectProperty(None) xo_cell_1 = ObjectProperty(None) xo_cell_2 = ObjectProperty(None) xo_cell_3 = ObjectProperty(None) xo_cell_4 = ObjectProperty(None) xo_cell_5 = ObjectProperty(None) xo_cell_6 = ObjectProperty(None) xo_cell_7 = ObjectProperty(None) xo_cell_8 = ObjectProperty(None) grid = '---------' def __init__(self, **kwargs): super(TicTacToeGameGrid, self).__init__(**kwargs) self.game = Game() self.cells = { 0: self.xo_cell_0, 1: self.xo_cell_1, 2: self.xo_cell_2, 3: self.xo_cell_3, 4: self.xo_cell_4, 5: self.xo_cell_5, 6: self.xo_cell_6, 7: self.xo_cell_7, 8: self.xo_cell_8 } self.new_game() def new_game(self): for key, btn in self.cells.items(): btn.background_normal = 'images/blank.png' self.current_player = 1 def click(self, cell_num): if self.current_player == 1: response = self.game.add_cross(self.MAPPING[cell_num]) if response != False: self.set_symbol(cell_num, "doge%d" % (self.current_player)) self.game.check_win() # computer play res = self.game.computer_play() self.set_symbol(self.MAPPING.index(str(res)), "doge2") def set_symbol(self, cell, symbol): self.cells[cell].background_normal = 'images/%s.png' % symbol.lower()
def deletePlayer(cls, playerId): player = Player.get_by_id(playerId, parent=None) parentGame = Game.get_by_id(player.parentId) parentGame.playerIds.remove(playerId) parentGame.put() memcache.delete(str(playerId), namespace='players') player.key.delete()
def createGame(cls, name, description, private, lat, lon): game = Game() game.name = name game.description = description game.private = private game.center = ndb.GeoPt(lat, lon) gameController = BasicGameController() gameController.put() game.gameControllerId = gameController.key.id() game.put() return game
def opened(self): # req = '{"event":"subscribe", "channel":"eth_usdt.deep"}' # self.send(req) print("连接成功") # 第一步随机下 self.send('1') self.agent = MinMaxAgent(env=Game())
def random_sim(self, state, player_names): players = [] for name in player_names: players.append(RandomPlayer(name, tree=self.tree)) game = Game(players) game.set_state(state) game.next_player() for player in game.play(): pass return game.winner().name
def run_game(self): mainloop = True on_load = True while mainloop: pygame.time.wait(Globals.WAIT_TIME) flags_n_key = Funcs.event_handler(pygame.event.get()) if not flags_n_key[0] & Globals.K_NONE or on_load: if flags_n_key[0] & Globals.K_QUIT: World.save_world(self.world) pygame.quit() sys.exit(0) if flags_n_key[0] & Globals.E_RESIZE: self.screen = pygame.display.set_mode(flags_n_key[1], pygame.RESIZABLE) self.render_map_x = self.screen.get_width() // Globals.FONT_X // 2 self.render_map_y = self.screen.get_height() // Globals.FONT_Y self.screen.fill(Globals.BG_COLOR) if on_load: self.objects.clear() self.draw_queue.clear() self.screen.fill(Globals.BG_COLOR) if self.link == 'main_menu': #Main_menu.load_menu(self) pass if self.link == 'continue': self.link = 'game' self.world = World.load_world() g.load_game(self) elif self.link == 'game': Main_menu.text_screen(self, 'generating...', (255, 255, 255)) pygame.display.flip() self.world = World.World(Globals.FIELD_NUM_X, Globals.FIELD_NUM_Y) g.load_game(self) on_load = False self.link, on_load = self.scenes[self.link](self, flags_n_key) Graphics.draw_all(self) pygame.display.flip()
def __init__(self, rect: Rect, color: Optional[Color], sock, connection_list, receive_list, parent_conn, child_conn, send_process, nicks): mod_loader.import_mods() super().__init__(rect, color) fps_font = Font('assets/fonts/arial.ttf', 20) sub_elem = UIElement(Rect(50, 50, 50, 50), None) sub_elem.append_child(FPSCounter(Rect(50, 50, 0, 0), fps_font)) self.append_child(sub_elem) self.sock = sock self.connection_list = connection_list self.receive_list = receive_list self.child_conn = child_conn self.parent_conn = parent_conn self.send_process = send_process self.game = Game(Game.Side.SERVER, mod_loader, self.parent_conn, nicks, -1, connection_list=self.connection_list) self.minimap_elem = UIImage( Rect(0, config['screen']['size'][1] - 388, 0, 0), 'assets/sprite/minimap.png') self.minimap = Minimap(self.game) self.minimap_elem.append_child(self.minimap) self.append_child(self.minimap_elem) self.game.create_unit('warrior', (0, 0)) self.game.create_unit('fortress', (500, 0)) self.game.create_unit('fortress', (-500, 0)) self.game.create_unit('archer', (-25, -25)) self.game.create_unit('archer', (25, -25)) self.game.create_unit('archer', (-25, 25)) self.game.create_unit('archer', (25, 25))
def __init__(self, rect: Rect, color: Optional[Color], sock, receive_list, socket_process, parent_conn, child_conn, send_process, nicks, team_id): super().__init__(rect, color) self.sock = sock self.receive_list = receive_list self.socket_process = socket_process self.parent_conn = parent_conn self.child_conn = child_conn self.send_process = send_process mod_loader.import_mods() config.reload() fps_font = Font('assets/fonts/arial.ttf', 20) sub_elem = UIElement(Rect(50, 50, 50, 50), None) sub_elem.append_child(FPSCounter(Rect(50, 50, 0, 0), fps_font)) self.append_child(sub_elem) self.game = Game(Game.Side.CLIENT, mod_loader, self.parent_conn, nicks, team_id) self.minimap = Minimap(self.game) self.minimap_elem = UIImage( Rect(0, config['screen']['size'][1] - 388, 0, 0), 'assets/sprite/minimap.png') self.minimap_elem.append_child(self.minimap) self.minimap_elem.append_child( ResourceMenu(self.game.current_player, Rect(45, 108, 0, 0), Font('assets/fonts/arial.ttf', 25))) menu_parent = UIElement(Rect(0, 0, 0, 0), None) self.append_child(menu_parent) menu_parent.append_child(self.minimap_elem) menu_parent.append_child(BuildMenu(self.relative_bounds, self.game)) menu_parent.append_child(ProduceMenu(self.relative_bounds, self.game))
def evaluate(board, moves): score = 0 b = Game(board=board) b.display() for m in moves: score += getScore(b.click(*m)) print m print score b.display() print "score", score print "penalty", penalty(b.board) score -= penalty(b.board) b.display() return score
def __init__(self): from creatures import Player from core import Game, SpriteGroup, load_image from uis import HealthBar from room import Room self.rooms_seeds_dict = {} self.start_time = time() self.player = Player((460, 230)) self.gameover = False # door_cords (450, 25), (80, 210), (450, 455), (820, 210) self.room = Room((0, 0), self) self.interface = SpriteGroup(HealthBar(self), RoomsCounterText(f'Комнат пройдено: ' f'{len(self.rooms_seeds_dict.keys()) - 1}', (0, 40), 36, (180, 180, 180))) self.background = load_image('assets/room/room-background.png') self.create_new_room((0, 0), 'any') Game.__init__(self)
class VacuumEnv(gym.Env): def __init__(self, size=8, max_episodes=100, gen_proba=0.5, collide='sym'): self.viewer = None self.done = None self.game = Game(max_episodes, gen_proba, size, collide) self.action_space = spaces.Discrete(4) self.observation_space = spaces.Box(0, 1, shape=(4, ), dtype=np.uint8) def step(self, action=None): obs = self.game.step(action) self.done = self.game.finished() reward = -self.game.garbage_count if self.done else 0 info = { 'garbage_count': self.game.garbage_count, 'gathered': self.game.agent.gathered, 'episodes_left': self.game.episodes_left } return np.array(obs), reward, self.done, info def reset(self): obs = self.game.reset() self.done = False return np.array(obs) def render(self, mode='window', size='small'): if self.viewer is None: if mode == 'window': self.viewer = WindowVisualizer(self.game, size) elif mode == 'terminal': self.viewer = TerminalVisualizer(self.game) self.viewer.render() def close(self): if self.viewer: self.viewer.close() self.viewer = None
def test_move_a(self): mine_map = Map(3, 4, mine_pos_list=[(0, 0)]) test_data_cases = [{ 'click_trace': [(0, 1), (1, 0)], 'state': 1, 'cur_step': 2 }, { 'click_trace': [(0, 1), (1, 0), (1, 1), (1, 2)], 'state': 2, 'cur_step': 4 }] for data in test_data_cases: game = Game(mine_map) self.batch_click(game, data['click_trace']) self.assertEqual(game.state, data['state']) self.assertEqual(game.cur_step, data['cur_step'])
def __init__(self, **kwargs): super(TicTacToeGameGrid, self).__init__(**kwargs) self.game = Game() self.cells = { 0: self.xo_cell_0, 1: self.xo_cell_1, 2: self.xo_cell_2, 3: self.xo_cell_3, 4: self.xo_cell_4, 5: self.xo_cell_5, 6: self.xo_cell_6, 7: self.xo_cell_7, 8: self.xo_cell_8 } self.new_game()
def play(): players = (Player(), Player()) game = Game(15, 15) while True: for player in players: move = player.random_search(game) game.make_move(move) game.display() if game.terminal_test(): print("Game over") return sleep(1)
def eval_genomes(genomes, config): games = [] sharks = [] for i in range(10): x = randint(-7, 7) y = randint(-7, 7) if (x, y) != (0, 0): sharks.append((x, y)) for genome_id, genome in genomes: genome.fitness = 0 for shark_position in sharks: games.append(Game(Ponyo(genome, config), Shark(), shark_position)) frame = 0 while len(games) > 0: frame += 1 if frame == 500: print("Aborted") for x, game in enumerate(games): game.ponyo.genome.fitness += 0.1 break for x, game in enumerate(games): game.move_ponyo() game.move_shark() for x, game in enumerate(games): if game.catched(): game.ponyo.genome.fitness -= 1 games.pop(x) if game.escaped(): game.ponyo.genome.fitness += 1 games.pop(x)
def post(self): try: card_set_indices = map(int, self.request.arguments['card_sets']) except ValueError as exc: raise APIError(Codes.NOT_AN_INTEGER, exc) if min(card_set_indices) < 0 or \ max(card_set_indices) >= len(self.application.card_sets): raise APIError(Codes.ILLEGAL_RANGE, card_set_indices) card_sets = [self.application.card_sets[i] for i in card_set_indices] password = self.get_argument('password', '') # not yet implemented if password: password = hash_obj(password) name = self.get_argument('name', '') if not name: name = 'Jogo %d' % (len(self.application.games) + 1) max_score = self.get_argument('max_score') if not max_score: max_score = INFINITY try: max_score = int(max_score) max_players = int(self.get_argument('max_players')) max_clue_length = int(self.get_argument('max_clue_length')) except ValueError as exc: raise APIError(Codes.NOT_AN_INTEGER, exc) if (not Limits.MIN_NAME <= len(name) <= Limits.MAX_NAME) or \ (not Limits.MIN_PLAYERS <= max_players <= Limits.MAX_PLAYERS) or \ (not Limits.MIN_SCORE <= max_score <= Limits.MAX_SCORE) or \ (not Limits.MIN_CLUE_LENGTH <= max_clue_length <= Limits.MAX_CLUE_LENGTH): raise APIError(Codes.ILLEGAL_RANGE) auto = self.get_argument('auto') if not auto: auto = 0 game = Game(self.user, card_sets, password, name, max_players, max_score, max_clue_length, int(self.get_argument('auto')), int(self.get_argument('time_clue')), int(self.get_argument('time_choose')), int(self.get_argument('time_vote'))) self.application.games.append(game) self.write(str(len(self.application.games) - 1))
def getPlayersForGame(cls, gameId): game = Game.get_by_id(int(gameId)); # Initialize string representations of player and entity IDs game.makeStringValuedIds() # Get all cached buddies buddyDictionary = memcache.get_multi( game.playerIdStrings, key_prefix='player' ) # Go through all buddy-keys of the parent game for playerId in game.playerIdStrings: # if one is missing, reload from the database and add to the buddy dictionary if playerId not in buddyDictionary: buddyDictionary[playerId] = Player.get_by_id( int(playerId), parent=None ) # Now we're sure everybody is there. No Child Left Behind. # Everybody is in the dictionary. A good time to write it to the cache again memcache.set_multi(buddyDictionary) # The caller is only interested in the values of the dictionary. return buddyDictionary.values()
def getPlayersForGame(cls, gameId): game = Game.get_by_id(int(gameId)) # Initialize string representations of player and entity IDs game.makeStringValuedIds() # Get all cached buddies buddyDictionary = memcache.get_multi(game.playerIdStrings, key_prefix='player') # Go through all buddy-keys of the parent game for playerId in game.playerIdStrings: # if one is missing, reload from the database and add to the buddy dictionary if playerId not in buddyDictionary: buddyDictionary[playerId] = Player.get_by_id(int(playerId), parent=None) # Now we're sure everybody is there. No Child Left Behind. # Everybody is in the dictionary. A good time to write it to the cache again memcache.set_multi(buddyDictionary) # The caller is only interested in the values of the dictionary. return buddyDictionary.values()
def main(): # For avoiding sound delay - thanks to BigglesW at StackOverflow pygame.mixer.pre_init(44100, -16, 1, 512) # Initialization ====================== pygame.init() # frames per second setting FPS = 60 fpsClock = pygame.time.Clock() # set up the window screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption('CometZ') # Setting window icon icon = pygame.image.load("iconShip.png") pygame.display.set_icon(icon) # gameState # States available: # menu, pause, game, gameOver # Create game instance game = Game() # ===================================== # Main game loop while True: # =========================================================== # EVENTS ================================================ # =========================================================== # check all events in event list for event in pygame.event.get(): game.handle(event) # for continuously pressed keys keys = pygame.key.get_pressed() game.keys(keys) # =========================================================== # GAME LOGIC ================================================ # =========================================================== # update game game.update() # =========================================================== # DRAWING ================================================ # =========================================================== # draw to the screen game.draw(screen) pygame.display.update() # =========================================================== # OTHER ================================================ # =========================================================== fpsClock.tick(FPS)
def getGameForPlayer(cls, playerId): player = Player.get_by_id(playerId, parent=None) return Game.get_by_id(player.parentId, parent=None)
def showGameList(games, anchorName="RecentGames", headerName="Recent Games", gameListStartParamName="gameListStart"): form = cgi.FieldStorage() gameListStart = 0 if form.has_key(gameListStartParamName): gameListStart = int(form[gameListStartParamName].value) #TODO guard against daft limits if gameListStart > len(games) - 10: gameListStart = len(games) - 10 if gameListStart < 0: gameListStart = 0 print "<h3><a id='%s'></a>%s</h3><table>" %(anchorName, headerName) print Game.tableHeadings() if len(games) < 10: listLength = len(games) else: listLength = 10 if gameListStart == 0: gamesToList = games[-listLength:] #last ten games else: gamesToList = games[-(listLength + gameListStart): -gameListStart] #ten games before gameStartList gamesToList.reverse() for game in gamesToList: print " <tr class='%s'>" % game.tableClass(), game.toTableRow(), "</tr>" print " </table>" #prev/next links if len(games) > 10: qs = os.environ["QUERY_STRING"] qsDict = cgi.parse_qs(qs) gamesLeft = len(games) - 10 - gameListStart if gamesLeft > 10: qsDict[gameListStartParamName] = [gameListStart + 10] print " <a href='?%s#%s'>Prev</a>" % (urlencodeXHTML(qsDict), anchorName) elif gamesLeft > 0: # we aren't at the start but we shouldn't go back a full 10. qsDict[gameListStartParamName] = [len(games) - 10] print " <a href='?%s#%s'>Prev</a>" % (urlencodeXHTML(qsDict), anchorName) else: # there is none left. print "Prev" print "<span class='navNumInert'>F</span>" if gameListStart < len(games) - 10: #o's for games past of gameListStart for i in range(100 + gameListStart, gameListStart, -10): if i >= len(games) - 10: #this is too far back if i < len(games): #but only just, put a link to the very end. qsDict[gameListStartParamName] = [len(games) - 10] print " <a href='?%s#%s' class='navNumFuture'>o</a>" % (urlencodeXHTML(qsDict), anchorName) continue else: #we can go back farther qsDict[gameListStartParamName] = [i] print " <a href='?%s#%s' class='navNumFuture'>o</a>" % (urlencodeXHTML(qsDict), anchorName) #the current o print "<span class='navNumCur'>o</span>" if gameListStart > 0: #o's for games future of gameListStart for i in range(gameListStart - 10, gameListStart - 110, -10): if i <= 0: #this is as far forward as we can go. qsDict[gameListStartParamName] = [0] print " <a href='?%s#%s' class='navNumFuture'>o</a>" % (urlencodeXHTML(qsDict), anchorName) break else: #we can go forward farther qsDict[gameListStartParamName] = [i] print " <a href='?%s#%s' class='navNumFuture'>o</a>" % (urlencodeXHTML(qsDict), anchorName) print "<span class='navNumInert'>tball</span>" if gameListStart > 10: qsDict[gameListStartParamName] = [gameListStart - 10] print "<a href='?%s#%s'>Next</a>" % (urlencodeXHTML(qsDict), anchorName) elif gameListStart > 0: # we aren't at the end but we shouldn't go forward a full 10. qsDict[gameListStartParamName] = [0] print "<a href='?%s#%s'>Next</a>" % (urlencodeXHTML(qsDict), anchorName) else: # there is none left. print "Next"
def getById(cls, id): return Game.get_by_id(id, parent=None)
#!/usr/bin/env python from core import Game from strategies.random_strategy import RandomStrategy from strategies.lowest_column import LowestColumnStrategy from strategies.vertical_search import VerticalSearcher from strategies.human_play import HumanPlay random = RandomStrategy() lowest = LowestColumnStrategy() human = HumanPlay() vertical = VerticalSearcher() game = Game(lowest,vertical) game.play(2) #game.repeated_play(10)
def main(): # initialize the pygame module pygame.init() pygame.display.set_caption("Learning car") # create a surface on screen that has the size of 720 x 480 screen = pygame.display.set_mode((1000, 500)) # initialize game game = Game() force = pygame.math.Vector2() # initialize rendering input_state = DRAWING checkpoint_start = None # variables # update_buttons = True # update_track = False # update_background = False segoe_print = pygame.font.SysFont('segoe print', 25) text_buttons = [ segoe_print.render(t, True, (127, 127, 127)) for t in ['Save current track', 'Load track 0', 'Clear active track', 'Start'] ] text_cycler = [ segoe_print.render(t, True, (127, 127, 127)) for t in ['Drawing', 'Checkpoints', 'Start', 'Idle'] ] buttons = [] right_bar_x = screen.get_rect().width * 0.75 right_bar_width = screen.get_rect().width * 0.25 button_height = 50 for index, line in enumerate(text_buttons): buttons.append( Button( pygame.Rect(right_bar_x, (index + 1) * button_height, right_bar_width, button_height), line)) cycler_buttons = [ Button(pygame.Rect(right_bar_x, 0, right_bar_width, button_height), line) for line in text_cycler ] input_state_cycler = Cycler(cycler_buttons) # main loop running = True while running: # event handling, gets all event from the event queue for event in pygame.event.get(): # red cross handling if event.type == pygame.QUIT: # change the value to False, to exit the main loop running = False # mouse presses handling if event.type == pygame.MOUSEBUTTONDOWN: if event.button == pygame.BUTTON_LEFT: # if it is LMB pressed if event.pos[0] < right_bar_x: if input_state == DRAWING: update_track = True game.track_m.active_track.add_vertex( pygame.math.Vector2(event.pos)) elif input_state == CHECKPOINTS: if checkpoint_start: game.track_m.active_track.add_checkpoint( checkpoint_start, pygame.math.Vector2(event.pos)) checkpoint_start = None else: checkpoint_start = pygame.math.Vector2( event.pos) elif input_state == START: game.track_m.active_track.set_start( pygame.math.Vector2(event.pos)) else: # update_buttons = True if input_state_cycler.is_inside(event.pos): input_state = (input_state + 1) % 4 if buttons[0].is_inside(event.pos): print('saved') game.track_m.save_active_track() if buttons[1].is_inside(event.pos): print('loaded') # update_background = True # update_track = True game.track_m.load_to_active_track('track_0.pickle') if buttons[2].is_inside(event.pos): # update_background = True game.track_m.clear_active_track() if buttons[3].is_inside(event.pos): game.start() # controls handling if event.type == pygame.KEYDOWN: # print('down a key') if event.key == pygame.K_RIGHT: force.x += 1 if event.key == pygame.K_LEFT: force.x -= 1 if event.key == pygame.K_DOWN: force.y += 1 if event.key == pygame.K_UP: force.y -= 1 if event.type == pygame.KEYUP: # print('up a key') if event.key == pygame.K_RIGHT: force.x -= 1 if event.key == pygame.K_LEFT: force.x += 1 if event.key == pygame.K_DOWN: force.y -= 1 if event.key == pygame.K_UP: force.y += 1 if force.length() > 0: force_ = force.normalize() force_.scale_to_length(0.0001) game.agent.add_force(force_, 0) game.update() # print(int(game.agent.pos.x), int(game.agent.pos.y)) # drawing pygame.draw.rect(screen, (0, 0, 0), screen.get_rect()) draw_track(screen, game.track_m.active_track) draw_button(screen, input_state_cycler.get_active_button()) for button in buttons: draw_button(screen, button) pygame.draw.circle(screen, (255, 255, 0), (int(game.agent.pos.x), int(game.agent.pos.y)), 12) pygame.display.flip()
def __init__(self, size=8, max_episodes=100, gen_proba=0.5, collide='sym'): self.viewer = None self.done = None self.game = Game(max_episodes, gen_proba, size, collide) self.action_space = spaces.Discrete(4) self.observation_space = spaces.Box(0, 1, shape=(4, ), dtype=np.uint8)
def post(self): global totalGames tp = int(self.get_argument('type')) username = self.get_argument('nickname') roomname = self.get_argument('room') password = self.get_argument('password') if tp == Commands.createRoom: #To create a new room notFound = -1 for i, gm in self.application.games.items(): if gm.name == roomname: notFound = i break if notFound != -1: #Room already exists self.write(json.dumps({'game': 'exists'})) else: game = Game(self.user, [self.application.card_sets[0]], password, roomname, 12, 40, 100) self.user.set_name(username) self.user.gid = totalGames game.add_player(self.user, 'RED') self.application.games[totalGames] = game self.write(json.dumps({'game': str(totalGames)})) totalGames += 1 #ADDING EXTRA PLAYERS TO HELP TEST #x1 = self.application.users.add_user('2dfsgsdfg', '2dsgsdfg') #x2 = self.application.users.add_user('3dfgsfdfg', '3dfgdfgd') #x3 = self.application.users.add_user('4dsfgsdfg', '4fsfoias') #game.add_player(x1, display.BunnyPalette.allColors[1]) #game.add_player(x2, display.BunnyPalette.allColors[2]) #game.add_player(x3, display.BunnyPalette.allColors[3]) elif tp == Commands.enterRoom: #He is trying to enter room print(roomname, password) notFound = -1 for i, gm in self.application.games.items(): if gm.name == roomname and gm.password == password: print('game exists, add him in', i, gm.name, gm.password) notFound = i break if notFound == -1: self.write(json.dumps({'game': 'na'})) else: #add into game given by totalGames = i blob = {'game': str(notFound)} self.user.set_name(username) self.user.gid = notFound i = 0 for col in display.BunnyPalette.allColors: if col not in list( self.application.games[notFound].colours.values()): i = col self.application.games[notFound].add_player(self.user, i) #players = {} #for i in self.application.games[notFound].players: # players.update({'name': i.name , 'color': i}) #blob.update({'players':players}) self.write(json.dumps(blob)) else: print(self.request.arguments)
import json import sys import curses from core import Game output = sys.stdin.read() data = json.loads(output) try: game = Game(data) game.play() finally: curses.endwin()
# -*- coding:utf-8 -*- import random import time from core import Game, Grid from agents import RandomAgent, MinMaxAgent if __name__ == '__main__': env = Game() # agent = RandomAgent(action_num=4, env=env) agent = MinMaxAgent(env=env, maxSearchTime=100) while not env.isOver: act, move = agent.step() print("当前下法:", move) env.step(act) print("当前棋盘:\n{}".format(env.state)) print("当前最大值:{}\n".format(env.maxValue)) print("最终得分:", env.score)
def menu_loop(self): m = Menu(self.engine) m.menu_start() while True: s = m.update() m.render() self.engine.render() if s['clicked'] is not None: break if s['clicked'] in ['Campaign', 'Skirmish']: game = Game('Test 1', FutureWar) worldmap = Map.from_csv("World map", "textures", MAP_PATH + r"\worldmap.csv") #worldmap = Map.from_csv("World map", "textures", MAP_PATH + r"\smallmap.csv") print("worldmap width = ", worldmap.width) print("worldmap height = ", worldmap.height) world = game.set_world(worldmap) player = game.create_player("Bob", "RedScum", Colors.YELLOW, 100, 100, 0, 0) game.create_player("Hicks", "BlueAngels", Colors.SKY_BLUE, 0, 0, 0, 0) game.create_player("Neutral", "BlueAngels", Colors.GREY, 20, 20, 0, 0) game.create_unit("Bob", "Soldier", 1, 1, 1.0) game.create_unit("Bob", "Elite", 3, 3, 0.5) game.create_unit("Bob", "Heavy", 2, 5, 0.5) game.create_unit("Neutral", "Defender", 20, 20, 1.0) #plant = Building(Hicks, x=4, y=4, profile=FutureWar.get_profile("barracks"), constructed=1, plife=0.50) #s1 = Unit(Hicks, x=9, y=9, profile=FutureWar.get_profile("soldier"), plife=0.50) #writeln(f"plant life = {plant.life}") self.camera = Camera(800, 600, world, player, self.engine) self.handler = InputHandler(self.camera, auto_scroll_zone=-1) self.audio = AudioHandler(AUDIO_PATH) #self.audio.play("ds.ogg") r = self.game_loop(game) return r elif s['clicked'] == 'Options': pass elif s['clicked'] == 'Quit': return False
def allGames(cls): return Game.query()
from core import Game start = Game(lang="en_English", category="colors") start.play_rounds(10)
def make_move(self, game: Game) -> int: return random.choice(list(game.legal_moves()))
import json import sys import os import pygame from core import Game import settings if __name__ == "__main__": output = sys.stdin.read() data = json.loads(output) screen_size = settings.get_screen_size(data['grid_size']) os.environ['SDL_VIDEO_CENTERED'] = '1' pygame.init() pygame.display.set_mode(screen_size) game = Game(data) game.main_loop() pygame.quit() sys.exit()
class ClientGameWindow(UIElement): def __init__(self, rect: Rect, color: Optional[Color], sock, receive_list, socket_process, parent_conn, child_conn, send_process, nicks, team_id): super().__init__(rect, color) self.sock = sock self.receive_list = receive_list self.socket_process = socket_process self.parent_conn = parent_conn self.child_conn = child_conn self.send_process = send_process mod_loader.import_mods() config.reload() fps_font = Font('assets/fonts/arial.ttf', 20) sub_elem = UIElement(Rect(50, 50, 50, 50), None) sub_elem.append_child(FPSCounter(Rect(50, 50, 0, 0), fps_font)) self.append_child(sub_elem) self.game = Game(Game.Side.CLIENT, mod_loader, self.parent_conn, nicks, team_id) self.minimap = Minimap(self.game) self.minimap_elem = UIImage( Rect(0, config['screen']['size'][1] - 388, 0, 0), 'assets/sprite/minimap.png') self.minimap_elem.append_child(self.minimap) self.minimap_elem.append_child( ResourceMenu(self.game.current_player, Rect(45, 108, 0, 0), Font('assets/fonts/arial.ttf', 25))) menu_parent = UIElement(Rect(0, 0, 0, 0), None) self.append_child(menu_parent) menu_parent.append_child(self.minimap_elem) menu_parent.append_child(BuildMenu(self.relative_bounds, self.game)) menu_parent.append_child(ProduceMenu(self.relative_bounds, self.game)) def update(self, event): self.game.update(event) if event.type == EVENT_UPDATE: while self.receive_list: args = self.receive_list.pop(0) self.game.handle_command(args[0], args[1:]) return super().update(event) def draw(self, screen): super().draw(screen) self.game.draw(screen) def shutdown(self): self.sock.close() self.send_process.terminate() self.socket_process.terminate() self.parent_conn.close() self.child_conn.close() print('Closed')
max_len = 6 max_a_len = 12 print("") for i1,s1 in enumerate(strategies): max_len = max(max_len,len(s1.__class__.__name__)+2) max_a_len = max(max_a_len,len(s1.author)+2) for i2,s2 in enumerate(strategies): if i1!=i2: #sleep(2) print(s1.__class__.__name__+" vs. "+s2.__class__.__name__) #sleep(2) try: game = Game(s1,s2) game.repeated_play(100,0) if game.r_winner==0: points[i1]+=1 points[i2]+=1 print(" It's a draw!") if game.r_winner==1: points[i1]+=3 print(" "+s1.__class__.__name__+" wins!") if game.r_winner==2: points[i2]+=3 print(" "+s2.__class__.__name__+" wins!") except Alarm: if game.turn == 1: print(" "+game.s1.__class__.__name__+" took too long to move")
class ServerGameWindow(UIElement): def __init__(self, rect: Rect, color: Optional[Color], sock, connection_list, receive_list, parent_conn, child_conn, send_process, nicks): mod_loader.import_mods() super().__init__(rect, color) fps_font = Font('assets/fonts/arial.ttf', 20) sub_elem = UIElement(Rect(50, 50, 50, 50), None) sub_elem.append_child(FPSCounter(Rect(50, 50, 0, 0), fps_font)) self.append_child(sub_elem) self.sock = sock self.connection_list = connection_list self.receive_list = receive_list self.child_conn = child_conn self.parent_conn = parent_conn self.send_process = send_process self.game = Game(Game.Side.SERVER, mod_loader, self.parent_conn, nicks, -1, connection_list=self.connection_list) self.minimap_elem = UIImage( Rect(0, config['screen']['size'][1] - 388, 0, 0), 'assets/sprite/minimap.png') self.minimap = Minimap(self.game) self.minimap_elem.append_child(self.minimap) self.append_child(self.minimap_elem) self.game.create_unit('warrior', (0, 0)) self.game.create_unit('fortress', (500, 0)) self.game.create_unit('fortress', (-500, 0)) self.game.create_unit('archer', (-25, -25)) self.game.create_unit('archer', (25, -25)) self.game.create_unit('archer', (-25, 25)) self.game.create_unit('archer', (25, 25)) def update(self, event): self.game.update(event) if event.type == EVENT_UPDATE: while self.receive_list: sender, command = self.receive_list.pop(0) self.game.handle_command(command[0], command[1:], sender=sender) return super().update(event) def draw(self, screen): super().draw(screen) self.game.draw(screen) def shutdown(self): print('Shutdown') self.send_process.terminate() self.parent_conn.close() self.sock.close()
def run(size, player): game = Game(size) while not game.is_over(): move = player.make_move(game) game.move(move) return game.first_wins()