def lobby(): lobby = Lobby() ans = '' machines_list = lobby.getMachines() for machine_id, machine in machines_list.iteritems(): ans += "<h1>" + str(machine.getBallsResult()) + "</h1>\n" return ans
def __init__(self): self.game_master = None self.players = [] self.current_phase = Lobby(self) self.phase_stack = [] self.night_cycle = [] self.day_cycle = []
async def create(self, ctx, num_players: int): '''Starts up the lobby, use number of TOTAL players.''' self.lobby = Lobby(num_players) await ctx.send( "Lobby created for " + str(num_players) + " total players. Use ?join to enter now or ?add NAME_HERE to add someone!" )
def find_lobby(client_id: int, username: str): """ Finds a lobby with a free place and create a new lobby if necessary :param client_id: int :param username: str :return: lobby in which player will play """ global lobbies lobbyFound = False new_lobby = set() for lobby in lobbies: if not lobby.is_full(): lobby.add_player(player_id=client_id, username=username) lobbyFound = True new_lobby = lobby break if not lobbyFound: new_id_lobby = len(lobbies) print(f"[LOBBY] Creating new lobby with id {new_id_lobby}.") new_lobby = Lobby(new_id_lobby, MAX_PLAYERS_LOBBY) new_lobby.add_player(client_id, username) lobbies.append(new_lobby) return new_lobby
def build_menu(dimensions): name_input_menu = InputWindow(dimensions, 'Enter player name:', 'screen_name', InputWindow.ALPHANUMERIC, 10) server_input_menu = InputWindow(dimensions, 'Enter server address and port (host:port)', 'server_name', InputWindow.HOST, 25) server_input_menu.value = DEFAULT_SERVER lobby_server_input_menu = InputWindow(dimensions, 'Enter server address and port (host:port)', 'lobby_server_name', InputWindow.HOST, 25) lobby_server_input_menu.value = DEFAULT_SERVER game_type_selection = GatewayWindow(dimensions, 'game_type') single_game_config = MenuWindow(dimensions) single_game_config.add_items(MenuItem('dimensions', GAME_DIMENSIONS_OPTIONS), MenuItem('duck_prob', DUCK_PROB_OPTIONS)) create_game_config = MenuWindow(dimensions) create_game_config.add_items(MenuItem('dimensions', GAME_DIMENSIONS_OPTIONS), MenuItem('size', PLAYER_NUMBER_OPTIONS), MenuItem('duck_prob', DUCK_PROB_OPTIONS)) lobby = Lobby() # Now build a successor/predecessor tree from the constructed menus name_input_menu.set_successor(game_type_selection) game_type_selection.add_item_with_successor('single', 'Single player game', single_game_config) game_type_selection.add_item_with_successor('create', 'Create online game', create_game_config) game_type_selection.add_item_with_successor('join', 'Join online game', lobby_server_input_menu) create_game_config.set_successor(server_input_menu) lobby_server_input_menu.set_successor(lobby) lobby.server_info_func = lambda: lobby_server_input_menu.value return name_input_menu
def main(): lobby_obj = Lobby() usernames = [ "AustinA69", "sirseerin", "CrazyAntXS", "Buuub", "lingzhixin", "jiangzhua", "bluehao1" ] for u in usernames: lobby_obj.add_player(u) print(order_dict_by_value(lobby_obj.total_uses))
def parseMessage(self, msg, client): print("parsing message: {} from {}".format(msg, client.address)) if msg == "create_lobby": lobbyID = len(self.lobbies) print("{} created new lobby: {}".format(client.address, lobbyID)) self.lobbies.append( Lobby(lobbyID, GameData(), client, self.serverSocket)) self.sendMessage("Lobby created", client) return None if msg.__contains__("join_lobby_"): lobbyID = int(msg[msg.index("lobby_") + 6:]) if len(self.lobbies) > lobbyID: lobby = self.lobbies[lobbyID] lobby.join(client) self.sendMessage("Lobby joined", client) else: self.sendMessage("Lobby doesn't exist", client) return None if msg.__contains__("lID_"): # lobby specific package and parse lobbyID first tmp = msg[msg.index("lID_") + 4:] lobbyID = int(tmp[:tmp.index("_")]) if len(self.lobbies) > lobbyID: # redirect package to responsible lobby self.lobbies[lobbyID].receivePackage(tmp[tmp.index("_") + 1:], client)
def create_lobby(): lobbyId = lobby_key_gen.new_key() lobby = Lobby(lobbyId) lobbies[lobbyId] = lobby #Deletes the lobby if no one joines after 5 seconds delete_unused_lobby_timeout(lobby, 5) print(f"Created lobby {lobbyId}") return jsonify({'lobbyId': lobbyId})
def createLobby(self): newID = "room" + str(len(self.lobbies)) self.lobbies.append(Lobby(newID)) #lobbyIndex = len(self.lobbies) - 1 #self.lobbyTable[request.sid] = lobbyIndex #self.lobbies[lobbyIndex].join(name) # return new ID to be emitted self.broadcastLobbyChange() return newID
async def start(ctx, *args): #split the arguments to get params for a new lobby try: owner = ctx.message.author parsed_args = _parse_arguments(args) title, description = parsed_args[0], parsed_args[1] new_lobby = Lobby(owner, title, description) _add_to_lobbies(new_lobby) except IncorrectTitleFormat: await ctx.send(TITLE_FORMAT_INCORRECT) except DescriptionTooLong: await ctx.send(DESCR_TOO_LONG) except LobbyAlreadyExists: await ctx.send(LOBBY_ALREADY_EXISTS) else: await ctx.send(embed=new_lobby.embed())
def close_mm(self, event): if event is True: self.lobby = Lobby(self) self.update_lobby_chat.connect(self.lobby.update_chatbox) self.update_lobby_player_list.connect(self.lobby.update_playerlist) self.init_lobby_countdown.connect(self.lobby.init_countdown) self.update_lobby_countdown.connect(self.lobby.update_countdown) self.update_lobby_host_widgets.connect(\ self.lobby.update_host_widgets) self.update_msg_color_update.connect(self.lobby.update_msg_color)
class Server: def __init__(self, HOST='', PORT=33221): if HOST is None: raise ValueError('HOST cannot be None') self.running = False self.serverSock = None self.HOST = HOST self.PORT = PORT self.BUFFSIZE = 8096 self.gamesThread = [] self.lobby = Lobby(self.gamesThread) return def _clientConnected(self, clientInfo): if not self.running: return print('client connected from {}.'.format(clientInfo[1])) client = Client(Connection(clientInfo, self.BUFFSIZE)) self.lobby.listeningClients.append(client) return def start(self): self.running = True self.serverSock = socket.socket() self.serverSock.bind((self.HOST, self.PORT)) self.HOST, self.PORT = self.serverSock.getsockname() self.serverSock.listen(5) print('Awaiting connections. . .') while self.running: newClient = self.serverSock.accept() self._clientConnected(newClient) return def stopGracefully(self): self.running = False for game in self.gamesThreads: game.interrupt() del game self.lobby.close() self.serverSock.close() print('Shutting down the server.') return
def __init__(self, HOST='', PORT=33221): if HOST is None: raise ValueError('HOST cannot be None') self.running = False self.serverSock = None self.HOST = HOST self.PORT = PORT self.BUFFSIZE = 8096 self.gamesThread = [] self.lobby = Lobby(self.gamesThread) return
class Main(ShowBase): start = None lobby = None round = None def __init__(self): ShowBase.__init__(self) self.start = Start(self) def goToLobby(self): self.start.cleanup() self.start = None self.lobby = Lobby(self) self.lobby.show() def startRound(self): self.lobby.hide() self.round = Round(self) def endRound(self): self.round.destroy() del self.round self.round = None self.lobby.show() def quit(self): sys.exit()
async def connect(ws, _): current_lobby_id = None global lobbies global next_user_num user_num = next_user_num next_user_num += 1 game = None print(f"User {user_num} connected") async for message in ws: parsed = json.loads(message) print(f"User {user_num} received {parsed}") if parsed["message_type"] == "join": to_join = parsed["lobby"] if to_join != current_lobby_id: if current_lobby_id: lobbies[current_lobby_id].disconnect(ws) if lobbies[current_lobby_id].empty(): print(f"Closing empty lobby {current_lobby_id}") del lobbies[current_lobby_id] else: await lobbies[current_lobby_id].broadcast(PlayerLeftMessage()) current_lobby_id = to_join print(f"User {user_num} joined room {to_join}") if to_join in lobbies: lobbies[to_join].join(ws) await lobbies[to_join].broadcast(PlayerJoinedMessage()) await ws.send(JoinedMessage(to_join, lobbies[to_join].num_players()).serialize()) else: print(f"Opening lobby {to_join}") lobbies[to_join] = Lobby(to_join, ws) await ws.send(CreatedMessage(to_join).serialize()) elif parsed["message_type"] == "start": lobby = lobbies[current_lobby_id] if not lobby.can_start(): print(f"Cannot start game with {lobby.num_players()} players") else: print(f"User {user_num} started ready checks for {current_lobby_id} with {lobby.num_players()} players") await lobby.send_ready_checks() elif parsed["message_type"] == "ready": game = lobbies[current_lobby_id].ready(ws) break if game: print(f"All players ready, starting game {current_lobby_id}") del lobbies[current_lobby_id] await game.run() else: await ws.wait_closed()
class Manager: def __init__(self): self.game_master = None self.players = [] self.current_phase = Lobby(self) self.phase_stack = [] self.night_cycle = [] self.day_cycle = [] def start_game(self): pass def new_night(self, previous_day): pass def new_day(self, previous_night): pass def next_phase(self): if not self.phase_stack: if isinstance(self.current_phase, self.night_cycle[-1]): new_cycle = self.day_cycle else: new_cycle = self.night_cycle for phase in new_cycle: self.phase_stack.insert(0, phase(self)) if self.phase_stack: self.current_phase = self.phase_stack.pop() for player in [p for p in self.players + [self.game_master] if p]: self.current_phase.send_page(player) # elif isinstance(self.current_phase, Lobby): def reset(self): self.__init__()
def update(self, dt): for msg in self.received(): if msg.connectTransaction: if not self.cconfirmed and msg.msg == self.connectseed: self.uid = msg.uid print(msg.uid) self.cconfirmed = True print("Got one") elif msg.msg != self.connectseed: print("Created:") print(msg.uid) self.objects[msg.uid] = Lobby.create_sprite(img=self.icon, red=msg.msg[0], green=msg.msg[1], blue=msg.msg[2]) elif msg.uid in self.objects: pos = np.fromstring(msg.msg, dtype=float) print(pos) #print(msg.uid) #print(pos) self.objects[msg.uid].position = pos if self.cconfirmed: updated = False if self.keys[key.RIGHT]: self.objects['me'].x += 80.0 * dt updated = True if self.keys[key.LEFT]: self.objects['me'].x += -80.0 * dt updated = True if self.keys[key.UP]: self.objects['me'].y += 80.0 * dt updated = True if self.keys[key.DOWN]: self.objects['me'].y += -80.0 * dt updated = True if self.keys[key.SPACE]: self.objects['me'].x = 0.0 self.objects['me'].y = 0.0 updated = True if updated: #print(self.objects['me'].position) self.send(np.array([self.objects['me'].x, self.objects['me'].y]).tostring(), uid=self.uid) else: self.time_since_attempt += dt if self.time_since_attempt >= 1: self.time_since_attempt = 0 self.send(self.connectseed, connectTransaction=True)
def run(self): value = self.state.run() input_value = self.input.run() if input_value == None: pass elif input_value == "leaving_game": self.running = False if value == None: pass elif value == "lobby": self.state = Lobby(self.UC, ras, bge) elif value == "game_start": bge.logic.sendMessage("change_scene") if str(bge.logic.getCurrentScene()) == "game_scene": self.state = Game(bge, self.UC, pickle) elif "menu_scene": print("going back to start!") self.state = Start(self.UC, bge, ras)
def __init__(self, length, hostname, port, nickname, devmode): from serverhandler import ServerHandler from udpdiscoverer import UDPDiscoverer self.__length = length self.lobby = Lobby(nickname) self.devmode = devmode self.__setup() # callback stuff self.__udpDiscoveryCallbacks = [] self.__udpServers = [] self.__clientStatusCallbacks = [] self.__lobbyCurrentPlayers = [] self.__lobbyCurrentGames = [] self.__lobbyUpdateGamesCallbacks = [] self.__joinGameCallbacks = [] self.__createGameCallbacks = [] self.__leaveGameCallbacks = [] self.__capitulateCallbacks = [] self.__connectCallbacks = [] self.__gamePreparationsEndedCallbacks = [] self.__gamePlayCallbacks = [] self.__shipUpdateCallbacks = [] self.__chatCallbacks = [] self.__joinGameCallbacks = [] self.__errorCallbacks = [] self.__opponentJoinedGameCallbacks = [] self.__repaintCallbacks = [] self.__specialAttackCallbacks = [] self.__playSoundCallback = [] self.__serverHandler = ServerHandler(self) if hostname and port and nickname: if self.connect(nickname, hostname, port): self.clientStatus = ClientStatus.NOGAMERUNNING self.__udpDiscoverer = UDPDiscoverer(self)
def setUp(self): self.lobby = Lobby(4)
class LobbyTest(unittest.TestCase): def setUp(self): self.lobby = Lobby(4) def test_add(self): self.lobby.add("Player") self.assertIn("Player", self.lobby.player_list) def test_multiple_add(self): self.lobby.add("Player1", "Player2") self.assertTrue("Player1" in self.lobby.player_list and "Player2" in self.lobby.player_list, msg=str(self.lobby.player_list)) def test_duplicate_add(self): self.lobby.add("Player") self.assertRaises(AssertionError, self.lobby.add, "Player") def test_lobby_max(self): self.lobby.add("1") self.lobby.add("2") self.lobby.add("3") self.lobby.add("4") self.assertRaises(AssertionError, self.lobby.add, "5") def test_remove(self): self.lobby.add("Player") self.lobby.remove("Player") self.assertNotIn("Player", self.lobby.player_list) def test_remove_nonexisting(self): self.assertRaises(ValueError, self.lobby.remove, "Player") def test_shuffle(self): self.lobby.add("1", "2", "3", "4") self.lobby.shuffle() self.assertTrue(self.lobby.get_team_one and self.lobby.get_team_two) def test_swap(self): self.lobby.add("Player1", "Player2") self.lobby.team_one.add("Player1") self.lobby.team_two.add("Player2") self.lobby.swap("Player1", "Player2") self.assertTrue("Player1" in self.lobby.team_two and "Player2" in self.lobby.team_one) def test_spots_left(self): self.lobby.add("Player1", "Player2") self.assertEqual(self.lobby.spots_left(), 2)
def reset_game(self): self.players = {} self.current_phase = Lobby() self.game_loop = None
def newLobby(): newLobby = Lobby() lobbies.append(newLobby) return jsonify({'success': True, 'lobbyId': newLobby.id})
READ_BUFFER = 4096 # definition port / adress server host = "0.0.0.0" port = 2213 MAX_CLIENTS = 30 listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # can re-use adress with option SO_REUSEADDR listen_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_sock.setblocking(0) listen_sock.bind((host,port)) # max clients listen_sock.listen(MAX_CLIENTS) print("Now listening at ", (host, port)) lobby = Lobby() connection_list = [] connection_list.append(listen_sock) while True: # Player.fileno() # utilisation of function select to have several clients read_players, write_players, error_sockets = select.select(connection_list, [], []) for player in read_players: if player is listen_sock: # new connection / one socket = one player new_socket, add = player.accept() new_player = Player(new_socket) connection_list.append(new_player) lobby.welcome_new(new_player) else: # nouveau message
def goToLobby(self): self.start.cleanup() self.start = None self.lobby = Lobby(self) self.lobby.show()
LOBBY_CONNECTING = 1 LOBBY_READY = 2 LOBBY_RUNNING = 3 LOBBY_CLOSED = 4 # Set Up Management Socket lobby_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lobby_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lobby_socket.bind((HOST, MGMT_PORT)) lobby_socket.listen(4) lobby_socket.setblocking(0) # Start Lobby System lobby_counter = 0 lobbies = [] lobby = Lobby(lobby_counter) lobbies.append(lobby) # Run Lobby System while True: # Check for Lobby Connections read_sockets, write_sockets, error_sockets = select.select([lobby_socket], [], [], 0.1) for sock in read_sockets: lobby_conn, addr = lobby_socket.accept() lobby_data = {"lobby_id": lobby_counter} # print(lobby_counter) json_data = json.dumps(lobby_data) lobby_conn.send(json_data.encode('ascii')) for lobby in lobbies:
class ScumInvaders: def __init__(self): pygame.init() self.width = 1024 self.height = 768 self.screen = pygame.display.set_mode((self.width, self.height)) self.screen.blit(sprites("Sprites").load("Loading"), (0, 0)) pygame.display.update() self.running = True self.AllSprites = sprites("Sprites") self.AllSprites.loadAll() self.clock = pygame.time.Clock() self.state = "Menu" self.sounds = soundManager("Sound") self.mainMenu = Main_Menu(self.screen, self.width, self.height, self.AllSprites, self.sounds) self.game = game(self.screen, self.width, self.height, self.AllSprites, self.sounds) self.lobby = None self.multiGame = None self.fontsize = 10 self.font = pygame.font.Font(os.path.join('Fonts', 'nasalization-rg.ttf'), self.fontsize) pygame.event.set_blocked(pygame.NOEVENT) def game_loop(self): while self.running: pygame.event.pump() if pygame.event.peek(pygame.QUIT): self.running = False if (self.state == "Menu"): self.mainMenu.draw() self.state = self.mainMenu.update() if self.state == "Exit": self.running = False elif self.state == "Lobby": self.mainMenu.state = "Login" self.lobby = Lobby(self.screen, self.width, self.height, self.AllSprites, self.sounds, self.mainMenu.username, self.mainMenu.socket) self.sounds.playNewMusic('newlobby.ogg') elif self.state == "Game": self.game.reset() elif (self.state == "Lobby"): self.lobby.draw() output = self.lobby.update() if "multiGame" in output: self.screen.blit(self.AllSprites.getSprite("Loading"), (0, 0)) self.state = "multiGame" self.multiGame = multiGame(self.screen, self.width, self.height, self.AllSprites,\ self.sounds, int(output[-2]), int(output[-1]), self.mainMenu.ip.input, self.lobby.currentRoom, self.lobby.socket) else: if output == "Menu": self.sounds.playNewMusic('mainMenu.ogg') self.mainMenu.socket.send("STOP") self.mainMenu.state = "Login" self.mainMenu.connected = False self.mainMenu.loginPressed = False self.mainMenu.loginStatus = "" self.state = output elif (self.state == "Game"): self.game.draw() self.state = self.game.update() if self.state == "Exit": self.running = False elif self.state == "Menu": self.mainMenu.state = "Main" self.sounds.playNewMusic('mainMenu.ogg') elif (self.state == "multiGame"): self.multiGame.draw() self.state = self.multiGame.update() if self.state == "Exit": self.running = False elif self.state == "Score": self.state = "Lobby" self.lobby.state = "Score" self.lobby.score = self.multiGame.playerList[self.multiGame.clientPlayerNum].score self.sounds.playNewMusic('mainMenu.ogg') elif self.state == "Lobby": self.lobby.state = "Room" self.sounds.playNewMusic('newlobby.ogg') self.screen.blit(self.font.render(str(int(self.clock.get_fps())), True, pygame.Color(255,255,255)), (0, 0)) pygame.display.update() self.clock.tick(60) try: self.mainMenu.socket.send("STOP") except: pass pygame.quit()
class Scrim(commands.Cog): pattern_object = re.compile(r"<@!(\d*)>") CREATE_LOBBY_MESSAGE = "Be sure to create a lobby first using the `?create NUMBER` command!" def __init__(self, bot): self.bot = bot self.lobby = None #--- helper functions ---# ########################## def stringify_teams(self, team1: list, team2: list): table = PrettyTable() table.add_column("Team 1", team1) table.add_column("Team 2", team2) table.align = "c" return table.get_string() def extract_id(self, players): new_list = [] for person in players: matched = re.match(Scrim.pattern_object, person) if matched: print("Searching for USER with this ID:", matched.group(1)) user = self.bot.get_user(int(matched.group(1))) new_list.append(user.name) else: new_list.append(person) return new_list #--- commands ---# ################## @commands.command() async def create(self, ctx, num_players: int): '''Starts up the lobby, use number of TOTAL players.''' self.lobby = Lobby(num_players) await ctx.send( "Lobby created for " + str(num_players) + " total players. Use ?join to enter now or ?add NAME_HERE to add someone!" ) @create.error async def create_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send( "You need to input the number of players on each team. For example, `?create 10`." ) elif isinstance(error.original, AssertionError): await ctx.send( "Uneven amount of players. This is the TOTAL amount of players, so it should be even!" ) else: await ctx.send("Unforeseen error.") print(str(type(error))) print(error) @commands.command() async def join(self, ctx): '''Join an existing lobby.''' self.lobby.add(str(ctx.author.name)) if self.lobby.spots_left() == 0: spots_message = "Lobby is now at max capacity (" + str( self.lobby.max) + ")." else: spots_message = str( self.lobby.spots_left()) + " player(s) can join." await ctx.send( str(ctx.author.name) + " has joined!" + " " + spots_message) @join.error async def join_error(self, ctx, error): if isinstance(error.original, AttributeError): await ctx.send(Scrim.CREATE_LOBBY_MESSAGE) elif isinstance(error.original, AssertionError): await ctx.send(error.original.args) else: print(error) await ctx.send("Unexpected error. Try again maybe?") @commands.command() async def add(self, ctx, player, *args): '''Add another player by @ing them or with a custom name.''' total_players = ( player, ) + args #to consider player a part of a tuple total_players = self.extract_id(total_players) self.lobby.add(*total_players) await ctx.send("Added " + str(total_players) + ".") @commands.command() async def clear(self, ctx): '''Reset the lobby.''' self.lobby = None await ctx.send("Lobby cleared.") @commands.command() async def remove(self, ctx, player): '''Removes another player. This command is case sensitive!''' self.lobby.remove(player) await ctx.send("Removed " + str(player)) @remove.error async def remove_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send("Make sure you include what player you're removing!" ) if isinstance(error.original, AttributeError): await ctx.send(Scrim.CREATE_LOBBY_MESSAGE) if isinstance(error.original, AssertionError): await ctx.send(error.original.args) elif isinstance(error.original, ValueError): await ctx.send( "Player can't be found! Usernames are case senstive. If you want to remove a player with spaces in their name, put quotation marks around it. `?remove \"Name With Spaces\"`" ) else: print(error) await ctx.send("Unexpected error. Try again maybe?") @commands.command() async def showlist(self, ctx): '''Outputs a list of the players in the lobby.''' row_numbers = [i for i in range(1, len(self.lobby.player_list) + 1)] await ctx.send("```\n" + tabulate({"Players": self.lobby.player_list}, headers="keys", showindex=row_numbers, tablefmt="psql") + "```") @showlist.error async def showlist_error(self, ctx, error): if isinstance(error.original, AttributeError): await ctx.send(Scrim.CREATE_LOBBY_MESSAGE) elif isinstance(error.original, AssertionError): await ctx.send(error.original.args) else: print(error) await ctx.send("Unexpected error. Try again maybe?") @commands.command() async def showteams(self, ctx): '''Outputs a table of the teams.''' table = { "Team 1": self.lobby.get_team_one(), "Team 2": self.lobby.get_team_two() } roll_string = "Roll #" + str(self.lobby.num_rolls()) await ctx.send(roll_string + "```\n" + tabulate(table, headers="keys", tablefmt="psql") + "```") @showteams.error async def showteam_error(self, ctx, error): if isinstance(error.original, AttributeError): await ctx.send(Scrim.CREATE_LOBBY_MESSAGE) elif isinstance(error.original, AssertionError): await ctx.send(error.original.args) else: print(error) await ctx.send("Unexpected error. Try again maybe?") @commands.command() async def swap(self, ctx, player1, player2): '''Swaps two players on opposite teams.''' self.lobby.swap(player1, player2) await ctx.invoke(self.showteams) @swap.error async def swap_error(self, ctx, error): if isinstance(error.original, AttributeError): await ctx.send(Scrim.CREATE_LOBBY_MESSAGE) if isinstance(error.original, AssertionError): await ctx.send(error.original.args) elif isinstance(error.original, ValueError): await ctx.send( "Player is not in the team(s)! Usernames are case senstive!") else: print(error) await ctx.send("Unexpected error. Try again maybe?") @commands.command() async def shuffle(self, ctx): '''Shuffles the lobby.''' self.lobby.shuffle() await ctx.invoke(self.showteams) @commands.command() async def tenmans(self, ctx): '''Teaches you how to use the bot.''' message = ''' Hey I heard you wanted to tenman? Here's how use the commands. 1. Create the lobby - `?create 10` 2. Add players / join the lobby - `?join` or `?add @username` or `?add random_name` - you can view who's in the lobby with `?showlist` - want to add a name with spaces in it? use quotation marks! `?add \"Name With Spaces\"` 3. Shuffle the players into teams, and I will provide the teams. - `?shuffle` ''' await ctx.send(message)
def game_loop(self): while self.running: pygame.event.pump() if pygame.event.peek(pygame.QUIT): self.running = False if (self.state == "Menu"): self.mainMenu.draw() self.state = self.mainMenu.update() if self.state == "Exit": self.running = False elif self.state == "Lobby": self.mainMenu.state = "Login" self.lobby = Lobby(self.screen, self.width, self.height, self.AllSprites, self.sounds, self.mainMenu.username, self.mainMenu.socket) self.sounds.playNewMusic('newlobby.ogg') elif self.state == "Game": self.game.reset() elif (self.state == "Lobby"): self.lobby.draw() output = self.lobby.update() if "multiGame" in output: self.screen.blit(self.AllSprites.getSprite("Loading"), (0, 0)) self.state = "multiGame" self.multiGame = multiGame(self.screen, self.width, self.height, self.AllSprites,\ self.sounds, int(output[-2]), int(output[-1]), self.mainMenu.ip.input, self.lobby.currentRoom, self.lobby.socket) else: if output == "Menu": self.sounds.playNewMusic('mainMenu.ogg') self.mainMenu.socket.send("STOP") self.mainMenu.state = "Login" self.mainMenu.connected = False self.mainMenu.loginPressed = False self.mainMenu.loginStatus = "" self.state = output elif (self.state == "Game"): self.game.draw() self.state = self.game.update() if self.state == "Exit": self.running = False elif self.state == "Menu": self.mainMenu.state = "Main" self.sounds.playNewMusic('mainMenu.ogg') elif (self.state == "multiGame"): self.multiGame.draw() self.state = self.multiGame.update() if self.state == "Exit": self.running = False elif self.state == "Score": self.state = "Lobby" self.lobby.state = "Score" self.lobby.score = self.multiGame.playerList[self.multiGame.clientPlayerNum].score self.sounds.playNewMusic('mainMenu.ogg') elif self.state == "Lobby": self.lobby.state = "Room" self.sounds.playNewMusic('newlobby.ogg') self.screen.blit(self.font.render(str(int(self.clock.get_fps())), True, pygame.Color(255,255,255)), (0, 0)) pygame.display.update() self.clock.tick(60) try: self.mainMenu.socket.send("STOP") except: pass pygame.quit()
def joinLobby(self): # For now just create one. return Lobby()
def createLobby(self): return Lobby()
if player.checkWin(self.lotto.history): return True return False def endSequence(self): Game.endSequence(self) for player in self.players: if player.checkWin(self.lotto.history): print("Winner: %s" % player) if __name__ == "__main__": from time import sleep from random import randint from player import Player from games import Games from lobby import Lobby lobby = Lobby() games = Games(lobby) G = [] for _ in range(5): players = [Player(name=None, sock=randint(3, 100)) for _ in range(3)] g = Bingo(players) g.games = games G.append(g) for g in G: print(g) games.addGame(g)
def start_lobby(self,task): self.mainmenu.hide() self.status.destroy() self.lobby=Lobby(self) return task.done
def setUp(self): self.lobby = Lobby.set_up_controller()
class Main(ShowBase): def __init__(self): self.created_client=False ShowBase.__init__(self) self.prelobby=PreLobby(self) def login(self,username,password): self.username=username self.status=OnscreenText(text = "Attempting to login...", pos = Vec3(0, -0.4, 0), scale = 0.05, fg = (1, 0, 0, 1), align=TextNode.ACenter) # simulate authentication by delaying before continuing # if authentication fails, create prelobby again with status text "LOGIN FAILED!" #self.prelobby=PreLobby(self,"LOGIN FAILED!") # else proceed to lobby state taskMgr.doMethodLater(0.01, self.start_mainmenu, 'Start MainMenu') def start_mainmenu(self,task): self.prelobby.destroy() self.status.destroy() self.mainmenu=MainMenu(self) return task.done def join_server(self,address): # Connect to our server self.client = Client(address, 9099, compress=True) if self.client.getConnected(): self.created_client=True data = {} data[0]="username" data[1]=self.username self.client.sendData(data) taskMgr.doMethodLater(0.01, self.start_lobby, 'Start Lobby') return True else: return False def start_lobby(self,task): self.mainmenu.hide() self.status.destroy() self.lobby=Lobby(self) return task.done def join_game(self): print "Game Starting" taskMgr.doMethodLater(0.01, self.start_game, 'Start Game') def start_game(self,task): self.lobby.hide() self.status.destroy() self.pregame=Pregame(self) return task.done def begin_round(self): print "Game Starting" taskMgr.doMethodLater(0.01, self.start_round, 'Start Round') def start_round(self,task): #self.pregame.hide() #self.status.destroy() self.playstate=Playstate(self) return task.done def quit(self): sys.exit()
if self.keys[key.DOWN]: self.objects['me'].y += -80.0 * dt updated = True if self.keys[key.SPACE]: self.objects['me'].x = 0.0 self.objects['me'].y = 0.0 updated = True if updated: #print(self.objects['me'].position) self.send(np.array([self.objects['me'].x, self.objects['me'].y]).tostring(), uid=self.uid) else: self.time_since_attempt += dt if self.time_since_attempt >= 1: self.time_since_attempt = 0 self.send(self.connectseed, connectTransaction=True) def place_tile(self, x, y): self.world.objects += WorldObject(self.tile, x, y) def dist_squared(self, obj, x, y): return (obj.x - x)**2 + (obj.y - y)**2 def on_mouse_press(self, x, y, button, modifiers): if self.me.dist_squared(x, y) < 900: self.place_tile(x, y) if __name__ == "__main__": window = Lobby(("0.0.0.0", 12801), LobbyHandler) window.connect("184.66.98.2", 12800) window.run() pyglet.app.run()
def launch_lobby(self): lobby = Lobby(self.window, self.world, self.renderer, self.factory) lobby.run() self.running = True self.run()