def run(self): """ Check whether each group is ready to start a game. Start a game for a particular group if it is ready. Check if players have disconnected from a game, terminate connections and remove group if so. Clean up any games and groups that have finished. :return: None """ while not self.is_terminal_event_set: with self.lock: for group in [g for g in self.groups if not g.in_game]: if not self.all_players_connected: self.logger.info( f"""Players from {group} are no longer connected. Clearing group... src={SRC}/run:21""") group.close_all() self.groups.remove(group) continue if GroupManager.is_ready(group): group.start() self.logger.info(f"{group}, ready... src={SRC}/run:28") game_thread = Game(group, self.lock) self.games.append(game_thread) game_thread.start() self.logger.info("Game started... src={SRC}/run:35") self.clean_finished_games() self.terminal_event.wait(P.CYCLE_TIMEOUT) self.logger.warning('Shutting down manager thread. src={SRC}/run:45')
class GameApplication(web.Application): def __init__(self, *args, **kwargs): super(GameApplication, self).__init__(*args, **kwargs) negotiation.setup(self) aiohttp_jinja2.setup( self, loader=jinja2.FileSystemLoader('/vagrant/templates/')) self.setup_routes() path_norm.setup(self) self.game = Game(self) def setup_routes(self): self.router.add_route('GET', '/', self.index) self.router.add_static('/static/', '/vagrant/static/', name='static') sockjs.add_endpoint(self, self.sockjs_handler, name="game", prefix="/sockjs/") @aiohttp_jinja2.template('index.html') def index(self, request): return { 'title': 'Whats up ' + request.GET.get('name', 'World'), 'app': self, } def sockjs_handler(self, msg, session): if msg.tp == sockjs.MSG_OPEN: session.manager.broadcast("Someone Joined") self.game.player_joined(session) if msg.tp == sockjs.MSG_MESSAGE: session.manager.broadcast(msg.data) if msg.tp == sockjs.MSG_CLOSED: session.manager.broadcast("Someone Left")
def __client_thread(self, player: Player) -> None: """Thread for handling a single client""" player.send('id_confirm', str(player.id)) opponent = None # looking for opponent while not opponent: opponent = self.__search_opponent(player) if opponent is None: time.sleep(1) # if player is no more waiting finish this loop if player not in self.waiting_players: player = None break continue # removing player and his opponent from the waiting list self.waiting_players.remove(player) self.waiting_players.remove(opponent) break if player: # starting a new game new_game = Game(self.logger, player, opponent) try: new_game.start() except Exception as e: self.logger.error('Game {} vs {} finished by error'.format( player.id, opponent.id))
def __init__(self, players, width=5, height=5, extra=50, wc=WinType.ROW | WinType.COL | WinType.DIAG): Game.__init__(self, players) self.lotto = Lotto.getLotto(width, height, extra) for player in self.players: player.createBoard(width, height, extra) player.wc = wc
def __init__(self, *args, **kwargs): super(GameApplication, self).__init__(*args, **kwargs) negotiation.setup(self) aiohttp_jinja2.setup( self, loader=jinja2.FileSystemLoader('/vagrant/templates/')) self.setup_routes() path_norm.setup(self) self.game = Game(self)
def set_up(): global game global player_1 global player_2 player_1 = Player(name="Pascal") player_2 = Player(name="Alina") game = Game([player_1, player_2]) game.word = ['n', 'a', 'm', 'e']
def make_server(self, name): address = self.settings.setting(name, "address") username = self.settings.setting(name, "username") password = self.settings.setting(name, "password") game_password = self.settings.setting(name, "game_password") url_extras = self.settings.setting(name, "url_extras") refresh_rate = float(self.settings.setting(name, "refresh_rate")) web_interface = WebInterface(address, username, password, name) chat = Chat(web_interface) chat.start() web_admin = WebAdmin(web_interface, chat) database = ServerDatabase(name) game = Game(GameMap(), GAME_TYPE_UNKNOWN) server = Server(web_admin, database, game, name) if game_password: server.game_password = game_password if url_extras: server.url_extras = url_extras tracker = GameTracker(server, refresh_rate) tracker.start() self.stop_list.append(server) self.stop_list.append(chat) self.stop_list.append(tracker) return server
def __init__(self, name, address, username, password, game_password, max_players, level_threshhold=0): self.name = name self.address = address self.max_players = max_players self.username = username self.password = password self.password_hash = "$sha1$" + \ sha1(password.encode("iso-8859-1", "ignore") + username.encode("iso-8859-1", "ignore"))\ .hexdigest() self.game_password = game_password self.database = ServerDatabase(name) print("Connecting to: {} ({})...".format(self.name, self.address)) self.session = self.new_session() message = "Connected to: {} ({})".format(self.name, self.address) print(colored(message, 'green')) self.general_settings = self.load_general_settings() self.game = Game(GameMap("kf-default"), game.MODE_SURVIVAL) self.trader_time = False self.players = [] self.level_threshhold = level_threshhold self.chat = ChatLogger(self) self.chat.start() self.mapper = ServerMapper(self) self.mapper.start() logger.debug("Server " + name + " initialised")
def __init__(self, player_queue, info_queue, server_id): lobby = Lobby(player_queue, info_queue, server_id) self.server_id = server_id self.players = lobby.wait() # shuffle order? player_names = [] for player in self.players: player_names.append(player.nickname) for i, player in enumerate(self.players): player.start_game(i, player_names) self.removed_players = [] self.game = Game(len(self.players)) self.run_game()
def create_game(): game_params = request.json user_id = game_params['user_id'] if user_id not in users: return jsonify(status='error', message='User not found'), 404 broker = users[user_id] salt = game_params['salt'] commitment = game_params['commitment'] cups_count = game_params['cups_count'] players_count = game_params['players_count'] if broker.balance < players_count * REWARD: return jsonify( status='error', message='Broker does not have enough fund for deposit'), 422 broker.balance -= players_count * REWARD game = Game(clock.current_cycle(), broker, salt, commitment, cups_count, players_count) games.append(game) return jsonify(game_id=len(games))
async def create_game(sid, data, client): match = Game(name=data["name"], public=data["public"]) await LobbyManager().add_game(match) try: await match.join_client(client) except ValueError: # Already joined return
def _reset(self): print(self.count, '試合目') self.count += 1 self.game = Game() self.player = DQN(id=0, game=self.game) self.game.start_game(player=self.player) self.game.start_kyoku() self.reward = 0 self.game_end = False while self.game.next(): pass time_step = ts.restart(self.board()) return nest_utils.batch_nested_array(time_step)
def test_from_dict_missing_keys(self): """Generate a Game object with a dict missing some required keys.""" self.assertRaises( KeyError, lambda: Game.from_dict({ 'id': None, 'players': None, 'time_controls': None }))
def __init__(self, name, address, username, password): self.name = name info("Connecting to {} ({})...".format(name, address)) self.web_admin = api.WebAdmin(address, username, password, name) info("Connected to {} ({})".format(name, address)) self.database = ServerDatabase(name) self.game_password = None self.dosh_threshold = None self.game = Game(GameMap(), GAME_TYPE_UNKNOWN) self.trader_time = False self.players = [] # Initial game's record data is discarded because some may be missed self.record_games = True self.tracker = GameTracker(self) self.tracker.start()
def setUp(self): # Game with no players or time controls self.game = Game('1') # Game with time controls self.game_wt = Game('1', time_controls=60) # Finished game (zero time) self.game_ft = Game('1', time_controls=0) # Game with players (and no time controls) self.game_wp = Game('1', public=True) self.game_wp.add_player('1', side=WHITE) self.game_wp.add_player('2', side=BLACK) # Game with players and time controls self.game_wpt = Game('1', '1', time_controls=60, public=False) self.game_wpt.add_player('1', side=WHITE) self.game_wpt.add_player('2', side=BLACK) # (Fool's Mate) (2 move checkmate for black) (Checkmate) self.test_game_1 = copy.deepcopy(self.game_wpt) for san in GameTest.moves['fools_mate']: self.test_game_1.move(san) # (Yates–Znosko-Borovsky) (First capture on move 40) (Resignation) self.test_game_2 = copy.deepcopy(self.game_wpt) for san in GameTest.moves['yates_znosko_borovsky']: self.test_game_2.move(san) self.test_game_2.resign() # (Andreikin-Karjakin) (Short checkmate) (Checkmate) self.test_game_3 = copy.deepcopy(self.game_wpt) for san in GameTest.moves['andreikin_karjakin']: self.test_game_3.move(san) # En passant with promotions self.test_game_4 = copy.deepcopy(self.game_wpt) for san in GameTest.moves['ep_promotions']: self.test_game_4.move(san) # (Scholar's Mate) (4 move checkmate for white) (Checkmate) self.test_game_5 = copy.deepcopy(self.game_wpt) for san in GameTest.moves['scholars_mate']: self.test_game_5.move(san) # Quickest stalemate self.test_game_6 = copy.deepcopy(self.game_wpt) for san in GameTest.moves['quickest_stalemate']: self.test_game_6.move(san)
def add_client(self, socket): user = User(socket, self.user_counter) self.users.append(user) self.user_counter += 1 socket.listeners.append(self.handle_message) # Automatically join first unstarted game, or create a new one game = None for g in self.games: if not g.started: game = g break if not game: self.games.append(Game(user, self.game_counter, 'Game ' + str(self.game_counter))) self.game_counter += 1 else: game.add_player(user)
def validate_resignation(self, data): # Check if game exists game_ref = self.db.collection(GAME_COLLECTION).document( data['game_id']).get() if not game_ref.exists: raise ValidationError('Game doesn\'t exist!') # Create a game object for validation game = Game.from_dict(game_ref.to_dict()) # Check if user exists assert_player_exists(data['user_id']) # Check if user is one of the players of the game if data['user_id'] not in game.players.values(): raise ValidationError( f"User {data['user_id']} is not a player in this game.")
def validate_move(self, data): # Validate 'game_id' game_ref = self.db.collection(GAME_COLLECTION).document( data['game_id']).get() if not game_ref.exists: raise ValidationError(f"Game {data['game_id']} doesn\'t exist!") # Create a game object for validation game = Game.from_dict(game_ref.to_dict()) # Validate 'user_id' if data['user_id'] == OPEN_SLOT or data['user_id'] == AI: pass else: assert_player_exists(data['user_id']) # Check if user is one of the players of the game if data['user_id'] not in game.players.values(): raise ValidationError( f"User {data['user_id']} is not a player in this game.") # Check that it's the user's turn if data['user_id'] != game.players[game.turn]: raise ValidationError( f"User {data['user_id']} cannot move when it is not their turn." ) # Check that game is not over if not game.in_progress: raise ValidationError(f"Game {data['game_id']} is over.") # Validate 'move' try: # Check move is valid SAN and applicable to the board game.move(data['move']) except ValueError: raise ValidationError( f"Invalid move {data['move']} in current context.")
def client_print(self, to_print): Game.client_print(self.client, to_print) print("Sent this to", self.name, ":", to_print)
from time import sleep, time from server.game import Game game = Game(debug=True) game.start_game() def draw_board(): H = W = 24 board = [[' '] * W for _ in range(H)] tehai_start = ((H - 1, 1), (H - 2, W - 1), (0, W - 2), (1, 0)) kawa_start = ((H - 5, W // 2 - 2), (H // 2 + 2, W - 5), (5, W // 2 + 1), (H // 2 - 1, 5)) move = ((0, 1), (-1, 0), (0, -1), (1, 0)) shift = ((1, -6), (6, 1), (-1, 6), (-6, -1)) color = ( '\033[31m{}\033[0m', '\033[37m{}\033[0m', '\033[32m{}\033[0m', '\033[36m{}\033[0m', ) print('{}{}局\n {} {} {} {}'.format( '東南西北'[game.kyoku // 4], game.kyoku % 4 + 1, game.scores[0], game.scores[1], game.scores[2], game.scores[3],
if request.method == 'GET': return json.dumps({ "board": game_server.game_board.board(), "width": game_server.game_board.board_width, "height": game_server.game_board.board_height }) elif request.method == 'POST': msg = json.loads(request.get_data()) player = msg["player"] x = msg["x"] y = msg["y"] if player in {ChessBoard.BLACK, ChessBoard.WHITE, ChessBoard.YELLOW}: ret_code = game_server.put_down_chess(x, y, player) if ret_code >= 0: succ = True msg = "下棋成功" elif ret_code == -1: succ = False msg = "该位置已有棋子,请更换位置" else: succ = False msg = "请等待其他用户下棋" return json.dumps({"succ": succ, "msg": msg}) else: return json.dumps({"succ": False, "msg": "该用户不在棋局内"}) if __name__ == '__main__': game_server = Game() sever_ip = '127.0.0.1' app.run(host='0.0.0.0', port='8088', debug=True)
await asyncio.wait([player.send(message) for player in PLAYERS.keys()]) async def handler(websocket, path): """handler function for incoming messages""" await register(websocket) try: await websocket.send(json.dumps(game.get_game_state())) while True: async for message in websocket: print(message) data = json.loads(message) if data["type"] == "GUESS": res = game.guess(data["data"]) if res: PLAYERS[websocket].increment_correct() else: PLAYERS[websocket].increment_incorrect() await notify_players() elif data["type"] == "SET_NAME": PLAYERS[websocket].set_name(data["data"]) finally: await unregister(websocket) if __name__ == "__main__": game = Game() start_server = websockets.serve(handler, 'localhost', 8080) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
class ClientManager: def __init__(self, port, terminate, initialData): self._terminate = terminate self._terminateConnetion = None self._port = port self._game = Game(initialData["amount"]) def start(self): self._terminateConnetion = listen(self._port, self._listener_handler) print("Client started on port {}".format(self._port)) def terminate(self): self._terminateConnetion() self._terminate() print("Client stopped on port {}".format(self._port)) @property def initialResponse(self): return { "round": self._game.rounds, "amountLeft": self._game.amount, "originalAmount": self._game.originalAmount, "dealt": self._game.playersCard.toDict() } def _listener_handler(self, data): switcher = {} switcher[ClientApis.tie_break.value] = self._tie_break_handler switcher[ClientApis.bet.value] = self._bet_handler switcher[ClientApis.play_again.value] = self._play_again_handler res = None handler = switcher.get(data["api"]) resData = handler(data["data"]) res = Response(ResponseTypes.accept, resData) # try: # except Exception as err: # res = Response(ResponseTypes.reject, { # "message": str(err) # }) return res.toDict() def _bet_handler(self, data): bet = data["bet"] self._game.set_bet(bet) return self._game_progress_res() def _tie_break_handler(self, data): isWar = data["isWar"] self._game.tie_break(isWar) return self._game_progress_res() def _play_again_handler(self, data): isPlayingAgain = data["isPlayingAgain"] if (isPlayingAgain): self._game.reshuffle() return self.initialResponse else: self.terminate() return {} def _game_progress_res(self): res = { "round": self._game.rounds, "dealersCard": self._game.dealersCard.toDict(), "playersCard": self._game.playersCard.toDict(), "result": self._game.result.toStr(), "bet": self._game.bet, "originalBet": self._game.originalBet, "playerEarn": self._game.playerEarn, "dealerEarn": self._game.dealerEarn, "isWar": self._game.isWar, "autoSurrender": self._game.autoSurrender, "cardsDiscarded": self._game.cardsDiscarded, "amountLeft": self._game.amount, "originalAmount": self._game.originalAmount, "ended": self._game.ended, "dealt": None } if (self._game.result != GameResults.tie): self._game.nextRound() res["ended"] = self._game.ended res["dealt"] = self._game.playersCard.toDict() return res
def endSequence(self): Game.endSequence(self) for player in self.players: if player.checkWin(self.lotto.history): print("Winner: %s" % player)
def __init__(self, port, terminate, initialData): self._terminate = terminate self._terminateConnetion = None self._port = port self._game = Game(initialData["amount"])
def client_prompt(self, prompt, options=None, timeout=5 * 60): return Game.client_prompt(self.client, prompt, options, timeout)
from server.game import Game game = Game() # Serve requests until Ctrl+C is pressed try: game.run_forever() except KeyboardInterrupt: pass # Close the game game.shutdown()
def endSequence(self): Game.endSequence(self) print("%s turns / %s max turns" % (self.turns, self.max_turns)) for player in self.players: if player.score > self.max_score: print("score: %s %s" % (player.score, player))
def __init__(self, players, max_score=19, max_turns=5): Game.__init__(self, players) self.max_turns = max_turns self.max_score = max_score for player in self.players: player.score = 0
async def run(): log.info("Star server") async with trio.open_nursery() as nursery: Game(nursery) log.info("Exiting server")