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 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')
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 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 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))
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)
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 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 __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 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 _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 __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 __init__(self, port, terminate, initialData): self._terminate = terminate self._terminateConnetion = None self._port = port self._game = Game(initialData["amount"])
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],
def test_init_invalid_id(self): """Invalid ID type.""" self.assertRaises(TypeError, lambda: Game(1))
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)
def StartGame(self): self.State = "Started" self.Game = Game() self.Game.Build(self.NumPlayers)
import settings from server.playerstub import PlayerStub from server.game import Game players = [] for uri in settings.players_uris: players.append(PlayerStub(uri)) Game(players)
from server.game import Game # Activate game poker = Game() active = poker.run_round() print() # Find the winner if len(active) == 1: winner = poker.fold_out(active[0]) else: winner = poker.determine_winner(active) # Print the winner print(winner)
def test_init_invalid_time_control_type(self): """Invalid time control type.""" self.assertRaises(TypeError, lambda: Game('1', time_controls='60'))
def __init__(self, addr, port): HTTPServer.__init__(self, (addr, port), RequestHandler) self.game = Game() self.running = True
async def run(): log.info("Star server") async with trio.open_nursery() as nursery: Game(nursery) log.info("Exiting server")
from flask_socketio import SocketIO, emit from flask import Flask, render_template, request from server import utils import random, string from server.game import Game, Player utils.init() app = Flask(__name__) app.config['SECRET_KEY'] = 'secret key' sio = SocketIO(app) thread = None game = Game(sio) clients = [] def random_key(length=64): return "".join(random.choice(string.ascii_letters + string.digits) for _ in range(length)) @app.route("/") def index(): global thread, game if thread is None: thread = sio.start_background_task(target=game.run) return render_template("index.html")
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()
def forRun( self ): yield self.verbose( "Commons", 0 ) yield self.verbose( "ids integrity", level=1 ) from common import ids #TODO compare unique ids to detect repetition, not vital but may be useful for debugging if self.testClient: yield self.verbose( "Client", 0 ) yield self.verbose( "Client sound mixer", level=1 ) from client.mixer import Mixer mixer = Mixer() yield self.verbose( "Setting volume to mute", level=2 ) mixer.setVolume(0) yield self.verbose( "Client displays", level=1 ) for name in self.displayNames: yield self.verbose( name.capitalize(), level=2 ) exec( "from client.displays.%s import %s as Display"%( name, name.capitalize() ) ) #from client.display import Display display = Display( resolution=(100,100) ) yield self.verbose( "Clearing", level=3 ) display.beginDraw() display.clear( (0,255,0) ) display.finalizeDraw() yield self.verbose( "Text", level=3 ) display.beginDraw() display.drawText( "test", (4,4) ) display.finalizeDraw() yield self.verbose( "Line", level=3 ) display.beginDraw() display.drawLine( (255,255,255), (0,100), (100,0) ) display.drawLine( (255,255,255), (0,0), (100,100) ) display.finalizeDraw() yield self.verbose( "Circle", level=3 ) display.beginDraw() display.drawCircle( (255,255,255), (50,50), 45 ) display.finalizeDraw() yield self.verbose( "Loading image", level=3 ) img = display.load( self.testImgPath ) yield self.verbose( "Drawing image", level=3 ) img = display.load( self.testImgPath ) display.beginDraw() display.draw( img, (0,0) ) display.finalizeDraw() yield self.verbose( "Drawing image rotated", level=3 ) img = display.load( self.testImgPath ) display.beginDraw() display.drawRo( img, (0,0), pi/3 ) display.finalizeDraw() yield self.verbose( "Client resources", level=1 ) yield self.verbose( "Images", level=2 ) from client.imgs import Imgs, Image, Animation imgs = Imgs( display ) yield self.verbose( "Loading images", level=3 ) for p in imgs.loadAll( display ): pass yield self.verbose( "Drawing images", level=3 ) import pygame # To be removed for other implementation for k, v in imgs.__dict__.items(): if isinstance( v, Image ) or isinstance( v, pygame.Surface ): display.beginDraw() if isinstance( v, Image ): display.draw( imgs[k], (0,0) ) if isinstance( v, pygame.Surface ): display.draw( v, (0,0) ) display.finalizeDraw() yield self.verbose( "Drawing animations", level=3 ) for k, v in imgs.__dict__.items(): if isinstance( v, Animation ): for j in xrange( 0, 500 ): imgs.updateAnimations() display.beginDraw() display.draw( v, (0,0) ) display.finalizeDraw() yield self.verbose( "Sounds", level=2 ) from client.snds import Snds yield self.verbose( "Loading sounds", level=3 ) snds = Snds( mixer ) for p in snds.loadAll( mixer ): pass yield self.verbose( "Playing sounds", level=3 ) for k, v in snds.__dict__.items(): if isinstance( v, pygame.mixer.Sound ): mixer.play( v ) yield self.verbose( "Texts", level=2 ) from client.texts import Texts texts = Texts() for p in texts.loadAll(): pass if self.testServer: yield self.verbose( "Server", 0 ) yield self.verbose( "Server stats", level=1 ) from server.stats import Stats stats = Stats() yield self.verbose( "Game from Scenarios", level=1 ) from server.game import Game games = [] yield self.verbose( "Scenarios", level=1 ) yield self.verbose( "Loading empty scenario", level=2 ) exec( "from scenarios import Scenario as Scenario" ) games.append( Game( Scenario ) ) for name in self.scenarioNames: yield self.verbose( "Loading scenario %s"%name, level=2 ) exec( "from scenarios.%s import %s as Scenario"%( name, name.capitalize() ) ) games.append( Game( Scenario ) ) # yield self.verbose( "Game from Sol", level=1 ) # from server.game import Game # game = Game( Scenario ) yield self.verbose( "Players", level=1 ) from server.players import Player yield self.verbose( "Computer", level=2 ) from server.players import Computer playerComputer0 = Computer( stats.R_HUMAN, "computer human" ) yield self.verbose( "Faction", level=2 ) from server.players import Faction playerFaction0 = Faction( stats.R_AI, "faction ai" ) yield self.verbose( "Human players", level=2 ) from server.players import Human playerHuman0 = Human( stats.R_NOMAD, "human nomad" ) yield self.verbose( "Objects", level=1 ) from server.objects import Object yield self.verbose( "Asteroid", level=2 ) from server.objects import Asteroid asteroids = [] while len( asteroids ) < 100: asteroids.append( Asteroid( games[0], 0, 0, 100 ) ) yield self.verbose( "Planet", level=2 ) from server.objects import Planet planet0 = Planet( stats.P_EARTH, 100, 0 ) yield self.verbose( "Sun", level=2 ) from server.objects import Sun sun0 = Sun( stats.S_SOL, 5000, 0 ) yield self.verbose( "Nebula", level=2 ) from server.objects import Nebula nebula0 = Nebula( stats.A_NEBULA, -1000, 0 ) yield self.verbose( "Blackhole", level=2 ) from server.objects import BlackHole blackhole0 = BlackHole( stats.BH_0, 0, 10000 ) yield self.verbose( "Ships", level=2 ) yield self.verbose( "Simple ship", level=3 ) from server.ships import Ship ship0 = Ship( stats.HUMAN_FIGHTER, None, 0, 0 ) yield self.verbose( "ShipWithTurrets", level=3 ) from server.ships import ShipWithTurrets ship0 = ShipWithTurrets( None, stats.HARVESTER, None, 0, 0 ) # yield self.verbose( "Turret instanciation", level=1 ) # yield self.verbose( "Turret building", level=1 ) # yield self.verbose( "Turret fire", level=1 ) # yield self.verbose( "AIs", level=1 ) yield self.verbose( "Server", level=1 ) from server.server import Server server = Server( scenarioName="Sol", force=True, adminPassword="******" ) yield True
async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) sess = Session(ws) user_parser = UserMessageParser() # test player # sess.player = Player(1, 32, 32, 1, ws, stats=0) logger.info('websocket opened') async for msg in ws: logger.info('msg received') if msg.type == WSMsgType.TEXT: # we shouldn't get those logger.info(msg.data) elif msg.type == WSMsgType.BINARY: logger.info(f'recvd:{msg.data.hex()}') usermsg = user_parser.from_binary(msg.data) if (sess.state == SessionState.NotJoined and usermsg['type'] == UserMessageType.Join): if usermsg['player_code'] != 0 and usermsg['room_id'] in ROOMS: logger.info('player rejoining game') sess.player = None for player in ROOMS[usermsg['room_id']].players: if player.code == usermsg['player_code']: sess.player = player user_parser.player = sess.player break if sess.player is not None: sess.player.ws = ws sess.player.disconnected = False sess.game = ROOMS[usermsg['room_id']] sess.state = SessionState.Joined else: sess.player = ROOMS[usermsg['room_id']] \ .add_player(ws, usermsg['player_nickname']) # sess.player.nickname = usermsg['player_nickname'] user_parser.player = sess.player sess.game = ROOMS[usermsg['room_id']] sess.state = SessionState.Joined elif usermsg['room_id'] in ROOMS: sess.player = ROOMS[usermsg['room_id']] \ .add_player(ws, usermsg['player_nickname']) # sess.player.nickname = usermsg['player_nickname'] user_parser.player = sess.player sess.game = ROOMS[usermsg['room_id']] sess.state = SessionState.Joined else: game = Game() sess.player = game.add_player(ws, usermsg['player_nickname']) # sess.player.nickname = usermsg['player_nickname'] user_parser.player = sess.player ROOMS[usermsg['room_id']] = game sess.game = game sess.state = SessionState.Joined # send joininfo logger.info(f"user joined room id: {usermsg['room_id']}") joininfo = ServerMessage( type=ServerMessageType.JoinInfo, room_id=usermsg['room_id'], player_id=sess.player.id, player_x=sess.player.x, player_y=sess.player.y, player_stats=sess.player.stats, player_color=sess.player.color, is_player_dead=sess.player.is_dead, time_left=int(sess.game.round_length - (time.time() - sess.game.start_time)), player_code=sess.player.code) logger.debug(f'player_code: {sess.player.code}') await sess.player.send_message(joininfo) if len(sess.game.players) > 1: # add existing players to new players context logger.info('synchronize players') for another_player in sess.game.players: if another_player is not sess.player: logger.info(f'sync p{another_player.id}' f' -> p{sess.player.id}') sync_player_msg = ServerMessage( type=ServerMessageType.NewPlayer, player_id=another_player.id, player_x=another_player.x, player_y=another_player.y, player_stats=another_player.stats, player_color=another_player.color, is_player_dead=another_player.is_dead, player_nickname=another_player.nickname) await sess.player.send_message(sync_player_msg) # send map to joining player map_update_msg = ServerMessage( type=ServerMessageType.MapUpdate, map_size=sess.game.map.size, map_tiles=sess.game.map.tiles) await sess.player.send_message(map_update_msg) logger.info('sent map update') elif sess.state == SessionState.Joined: logger.info('received new message from joined player') if not sess.player.is_dead: sess.game.received_messages.append(usermsg) else: logger.info( f'message from dead player[{sess.player.id}] ignored') elif msg.type == WSMsgType.ERROR: logger.error("error: {}".format(ws.exception())) logger.info("websocket closed") # set player to disconected, if disconected until new_game delete sess.player.disconnected = True return ws
def test_init_invalid_time_control_value(self): """Invalid time control value (negative int).""" self.assertRaises(ValueError, lambda: Game('1', time_controls=-60))