def enter_room(self, player_id, info, session): if not self.owner_info and player_id == self.owner: self.owner_info = info proto = game_pb2.EnterRoomResponse() proto.room_id = self.room_id proto.owner = self.owner if len(self.player_dict.keys()) >= self.chairs: proto.code = 5002 send(ENTER_ROOM, proto, session) if self.conf.is_aa(): self.request.aa_refund(player_id, 0) self.logger.warn( "room {0} is full, player {1} enter failed".format( self.room_id, player_id)) return player = Player(player_id, info, session, self) from state.player_state.init import InitState player.machine.trigger(InitState()) seat = -1 for seat in range(self.chairs): if seat in self.seat_dict.keys(): continue break player.seat = seat self.player_dict[player_id] = player self.seat_dict[seat] = player proto.code = 1 proto.kwargs = self.kwargs proto.rest_cards = self.cards_total for k, v in self.seat_dict.items(): p = proto.player.add() p.seat = k p.player = v.uuid p.info = v.info p.status = player_state_code_map[v.state] p.is_online = v.is_online p.total_score = v.total SessionMgr().register(player, session) send(ENTER_ROOM, proto, session) # print 'player cnt:', len(self.player_dict.keys()) proto = game_pb2.EnterRoomOtherResponse() proto.code = 1 proto.player = player_id player = self.player_dict[player_id] proto.info = player.info proto.seat = player.seat for i in self.player_dict.values(): if i.uuid == player_id: continue send(ENTER_ROOM_OTHER, proto, i.session) player.dumps() self.dumps() self.request.enter_room(player_id) self.logger.info("player {0} enter room".format(player_id)) if self.conf.is_aa(): self.request.aa_cons(player_id)
def move_players_chip(self, player: Player, steps: int) -> Player or None: """ Moves player chip by given amount of steps :param player: who is making this turn :param steps: number of steps to do :return: Player, if he wins the game during this action, None in other case """ rabbit = player.get_active_rabbit() # handle rare case when player had dropped last own rabbit on this turn if rabbit is None: return None destination_cell = self._rabbit_map[rabbit] while (steps > 0) and (not destination_cell.is_winning_cell): destination_cell = destination_cell.next if not self.is_busy(destination_cell): steps -= 1 if destination_cell != self._rabbit_map[rabbit]: self._rabbit_map[rabbit] = destination_cell print(f'Rabbit #{player.id}.{rabbit.number} moves to cell #{destination_cell.number}') if destination_cell.is_winning_cell: return player if destination_cell.is_hole: player.drop_active_rabbit() self._rabbit_map[rabbit] = None
def test_player_drop_rabbit(self): player = Player(player_id=1, rabbits=2, active_rabbits=1, lost_rabbits=1) player.drop_active_rabbit() self.assertEqual(len(player.lost_rabbits), 2) self.assertEqual(len(player.active_rabbits), 0) self.assertEqual(len(player.ready_rabbits), 0)
def test_player_reset(self): player = Player(player_id=1, rabbits=2, active_rabbits=1, lost_rabbits=1) player.reset_condition() self.assertEqual(len(player.lost_rabbits), 0, 'number of lost rabbits expected 0') self.assertLessEqual(len(player.active_rabbits), 1, 'number of act. rabbits expected <= 1') self.assertLessEqual(len(player.ready_rabbits), 2, 'number of ready rabbits expected <= 2') self.assertEqual( len(player.ready_rabbits) + len(player.active_rabbits), 2)
def test_get_joinable_room(self): lobby = Lobby() room = lobby.get_joinable_room() self.assertEqual(0, room.room_no) p1 = Player('p1') room.add_player(p1) room = lobby.get_joinable_room() self.assertEqual(0, room.room_no) p2 = Player('p2') room.add_player(p2) room = lobby.get_joinable_room() self.assertNotEqual(0, room.room_no)
def init_player(engine, load_type): lvl = engine.info.player_lvl stats = EntityStats(hp=10 * lvl, force=2 * lvl, defense=2 * lvl) player = Player(Inventory(3), int(engine.info.scr_wd * 0.03), int(engine.info.scr_ht * 0.14), screen_width=engine.info.scr_wd, screen_height=engine.info.scr_ht, char=203, color=tc.white, name='Bob', stats=stats) player.mv_handler = MoveDeco(MoveHandler(player)) player.stats.owner = player return player
def create_sport_room(msg_dict, session): table = TableMgr().create(msg_dict.get("room_id"), msg_dict.get("room_uuid"), "", 0, 0, 0, msg_dict.get("kwargs"), []) table.sport_id = msg_dict.get("sport_id") players = msg_dict.get("players", []) player_tokens = {} for p in players: player_id = p.get("id") info_dict = {"nick": p.get("nick", ""), "icon": p.get("icon", ""), "sex": 1, "game_count": 0, "reg_time": ""} info = json.dumps(info_dict, ensure_ascii=False) player = Player(player_id, info, None, table) from base.state_base.player.init import InitState player.machine.trigger(InitState()) table.lookon_player_dict[player_id] = player player.match_score = p.get("score", 0) player.is_wait = True player.ready() token = str(uuid4()) redis.set("token:{0}".format(player_id), token) player_tokens[player_id] = token table.dumps() table.set_timer("start_10", 10) # 发送给Center Server 创建成功的消息 msg_back = dict() msg_back["cmd"] = CG_CREATE_SPORT_ROOM msg_back["room_id"] = msg_dict.get("room_id") msg_back["state"] = 1 msg_back["host"] = options.host msg_back["port"] = options.server_port msg_back["sport_id"] = msg_dict.get("sport_id") msg_back["player_tokens"] = player_tokens session.send_message(msg_back) # 发送到游戏服务器
def test_player_init(self): player = Player(player_id=1, rabbits=2, active_rabbits=1, lost_rabbits=1) self.assertEqual(len(player.lost_rabbits), 1) self.assertEqual(player.lost_rabbits[0].player_id, 1) self.assertEqual(player.lost_rabbits[0].number, 1) print('lost rabbits are ok') self.assertEqual(len(player.active_rabbits), 1) self.assertEqual(player.active_rabbits[0].player_id, 1) self.assertEqual(player.active_rabbits[0].number, 2) self.assertEqual(len(player.ready_rabbits), 0)
def loads_player(uuid, table): raw = redis.get("player:{0}".format(uuid)) # print "player", uuid, raw if not raw: return data = pickle.loads(raw) player = Player(uuid, None, None, table) for k, v in data.items(): if k in ("table", "session", "machine", "round", "action", "room"): continue else: player.__dict__[k] = v state = data["machine"] # for k, v in player.action_dict.items(): # player.action_dict[int(k)] = v # del player.action_dict[k] player.machine.last_state = player_state[state[0]] if state[0] else None player.machine.cur_state = player_state[state[1]] if state[1] else None player.round.__dict__.update(data["round"]) player.action.__dict__.update(data["action"]) player.room.__dict__.update(data["room"]) return player
def loads_player(uuid, table): raw = redis.get("player:{0}".format(uuid)) # print "player", uuid, raw if not raw: return data = json.loads(raw) player = Player(uuid, None, None, table) for k, v in data.items(): if k in ("table", "session", "machine", "proto"): continue else: player.__dict__[k] = v proto = data.get("proto") if proto: player.proto.__dict__.update(proto) player.proto.load() state = data["machine"] for k, v in player.action_dict.items(): player.action_dict[int(k)] = v del player.action_dict[k] player.machine.last_state = player_state[state[0]] if state[0] else None player.machine.cur_state = player_state[state[1]] if state[1] else None return player
thorpy.store("screen", els) m = thorpy.Menu(els) m.play() game = Game(me) humans = Race("Coco", "human", LUNAR, me, "green", team=1) #LUNAR, STELLAR or SOLAR humans.dist_factor = 10 humans.finalize() #always call this function to finish initialize a race !!! humans2 = Race("Turtudur Buldur", "human", LUNAR, me, "blue", team=2) humans2.dist_factor = 10 humans2.finalize() players = [Player(1, humans.name, humans), Player(2, humans2.name, humans2)] game.set_players(players) #<fast> : quality a bit lower if true, loading time a bit faster. #<use_beach_tiler>: quality much better if true, loading much slower. Req. Numpy! #<load_tilers> : Very slow but needed if you don't have Numpy but still want hi quality. game.build_map(mi, fast=False, use_beach_tiler=True, load_tilers=False) def add_unit(pn, unit_type, near_what): nx, ny = game.get_map_size() unit = game.players[pn].race[unit_type] unit.team = game.players[pn].race.team for v in game.get_all_objects_by_str_type(near_what): flag = game.get_object("flag", v.cell.coord) if flag:
def test_player_out_of_the_game(self): player = Player(player_id=1, rabbits=0) self.assertFalse(player.is_active) self.assertEqual(player.get_active_rabbit(), None)
humans = Race("Green team", "human", LUNAR, me, "green", team=1) #LUNAR, STELLAR or SOLAR ##humans.base_material_cost["grass"] = 2 ##humans.base_material_cost["forest"] = 5 humans.dist_factor = 10 ##humans.base_terrain_attack["grass"] = 2. ##humans["infantry"].material_cost["sand"] = 4 ##humans["infantry"].terrain_attack["snow"] = 0.8 humans.finalize() #always call this function to finish initialize a race !!! humans2 = Race("Red team", "human", SOLAR, me, "red", team=2) ##humans2.base_material_cost["forest"] = 10 ##humans2.base_terrain_attack["grass"] = 0.8 humans2.dist_factor = 10 humans2.finalize() players = [ Player(1, "Helmut", humans), Player(2, "Jean", humans2)] game.set_players(players) #<fast> : quality a bit lower if true, loading time a bit faster. #<use_beach_tiler>: quality much better if true, loading much slower. Req. Numpy! #<load_tilers> : Very slow but needed if you don't have Numpy but still want hi quality. game.build_map(map_initializer, fast=True, use_beach_tiler=False, load_tilers=False) ##game.add_unit((15,5), humans["infantry"], 100, team=1) ##game.add_unit((14,6), humans["infantry"], 100, team=1) #14,6 ##game.add_unit((25,5), humans["infantry"], 100, team=1) ##game.add_unit((16,6), humans["wizard"], 1, team=1) ## ## ##game.add_unit((20,8), humans2["infantry"], 100, team=2)
from datetime import datetime import numpy as np from logic.engine.satsolver import SatSolverEngine from logic.game import Game from logic.player import Player # logging.basicConfig(level=logging.DEBUG) np.set_printoptions(linewidth=160) count = 0 with open("foo.csv", 'w') as fw: while True: count += 1 game = Game(24, 30, 217, (0, 0)) solver = SatSolverEngine() player = Player(game, solver) start = datetime.now() play = player.play() if play == 1: print("Done in {} tries".format(count)) count = 0 elapsed = (datetime.now() - start).total_seconds() print("Clear {}% in {}".format(100 * play, elapsed)) fw.write("{},{}\n".format(play, elapsed))
def client_socket(conn, game): conn.sendall("Tiny-PyRPG Server".encode()) data = json.loads(conn.recv(2048).decode()) request = data["request"] data = data["data"] if request != "JOIN LOBBY": send_client_error(conn, "INVALID REQUEST") return username = data if game.in_progress == True: send_client_error(conn, "GAME STARTED") return try: pnum = game.add_player(Player(username)) except NameTakenError: send_client_error(conn, "NAME TAKEN") return except LobbyFullError: send_client_error(conn, "LOBBY FULL") return data = {} data["response"] = "JOIN ACCEPT" jdata = {} jdata["player-number"] = pnum jdata["lobby"] = game.get_lobby_dict() data["data"] = jdata data = json.dumps(data).encode() conn.sendall(data) # The client has now joined the lobby. while not game.in_progress: data = json.loads(conn.recv(2048).decode()) request = data["request"] data = data["data"] if request == "UPDATE PROFESSION": profession = data if game.update_player_profession(pnum, profession): send_client_lobby(conn, game) continue else: send_client_error(conn, "SERVER ERROR") return elif request == "GET UPDATE": send_client_lobby(conn, game) continue elif request == "UPDATE READY": ready = data if game.update_player_ready(pnum, ready): send_client_lobby(conn, game) continue else: send_client_error(conn, "SERVER ERROR") return elif request == "TRY START": if game.start_game(): package = {} response = "GAME START" data = {} data["actions"] = game.get_player_profession(pnum).actions() data["game"] = game.to_dict() else: send_client_error(conn, "PLAYERS NOT READY") continue # The game has now started. while game.in_progress: pass
def enter_room(self, player_id, info, session): newinfo = info.replace("\\'", "") newinfo = newinfo.replace('\\"', "") newinfo = newinfo.replace('\\n', "") newinfo = newinfo.replace('\\t', "") if not self.owner_info and player_id == self.owner: self.owner_info = newinfo msg_dict = dict() msg_dict["room_id"] = self.room_id msg_dict["owner"] = self.owner msg_dict["owner_info"] = self.owner_info msg_dict["room_state"] = table_state_code_map[self.state] msg_dict["round"] = self.cur_round msg_dict["rounds"] = self.conf.rounds msg_dict["is_admin"] = (player_id in self.guild_admins) # if len(self.player_dict.keys()) + len(self.lookon_player_dict.keys()) >= self.chairs + 10: # if len(self.player_dict.keys()) >= self.chairs: # msg_dict["code"] = 2 # send(ENTER_ROOM, msg_dict, session) # self.logger.warn("room {0} is full, player {1} enter failed".format(self.room_id, player_id)) # return player = Player(player_id, newinfo, session, self) from base.match_mgr import MatchMgr MatchMgr().player_enter(player) from base.state_base.player.init import InitState player.machine.trigger(InitState()) player.is_wait = True self.lookon_player_dict[player_id] = player SessionMgr().register(player, session) msg_dict["code"] = 0 msg_dict["kwargs"] = self.kwargs msg_dict["rest_cards"] = self.cards_total msg_dict["state"] = player_state_code_map[player.state] msg_dict["player"] = list() msg_dict["dealer"] = self.dealer_seat msg_dict["player_status"] = player_state_code_map["InitState"] for k, v in self.seat_dict.items(): p = dict() p["seat"] = k p["player"] = v.uuid p["info"] = v.info p["state"] = player_state_code_map[v.state] p["is_online"] = v.is_online p["score"] = v.get_total_score() p["pledge"] = v.round.pledge p["loot_dealer"] = v.round.loot_dealer p["is_wait"] = v.is_wait p["niu_type"] = v.round.niu_type if v.session is not None: p["ip"] = v.session.address[0] msg_dict["player"].append(p) p["cards_in_hand"] = list() count = len(v.round.cards_in_hand) if v.state == "ShowCardState": p["cardsign_in_hand"] = list() cards_hand = copy.deepcopy(v.round.cards_in_hand) cardsign_in_hand = show_card_type2(v.round.cards_in_hand, v.round.niu_type) for w in cardsign_in_hand: p["cardsign_in_hand"].append(w) for c in cards_hand: p["cards_in_hand"].append(c) else: for _ in v.round.cards_in_hand: p["cards_in_hand"].append(0) send(ENTER_ROOM, msg_dict, session) ''' msg_dict = dict() msg_dict["player"] = player_id msg_dict["info"] = player.info msg_dict["seat"] = player.seat msg_dict["dealer"] = self.dealer_seat # 庄家位置 msg_dict["state"] = player_state_code_map[player.state] msg_dict["is_online"] = player.is_online msg_dict["score"] = player.room.score msg_dict["pledge"] = player.round.pledge msg_dict["loot_dealer"] = player.round.loot_dealer msg_dict["is_wait"] = player.is_wait msg_dict["ip"] = player.session.address[0] for i in self.player_dict.values(): if i.uuid == player_id: continue send(ENTER_ROOM_OTHER, msg_dict, i.session) ''' self.dumps() self.logger.info("player {0} enter room".format(player_id))
def join_game(self): if not isinstance(self.window, MainMenu): pass self.player = Player(-1, self.txt_username.text())