import socket import threading import json import random import time Server…
- User
import socket import threading import json import random import time
Server configuration
HOST = '0.0.0.0' PORT = 5555
Global variables
rooms = {} room_id_counter = 1 lock = threading.Lock()
class Player: def init(self, conn, addr, name): self.conn = conn self.addr = addr self.name = name self.snake = [] self.direction = 'UP' self.alive = True self.current_room = None # Track the room the player is currently in
class Room: def init(self, room_id, host_player): self.room_id = room_id self.players = [host_player] self.game_state = { 'snakes': {}, 'food': (random.randint(0, 39), random.randint(0, 39)) # Adjusted for larger game size } self.running = False self.lock = threading.Lock() self.host = host_player # The host player
def start_game(self): self.running = True threading.Thread(target=self.game_loop).start() def game_loop(self): while self.running: self.update_game_state() self.send_game_state() alive_players = [player for player in self.players if player.alive] if len(alive_players) <= 1: self.running = False self.send_game_over() break time.sleep(0.05) # Reduced sleep time for smoother updates # Notify players that the game has ended and reset their states self.reset_players() # Remove room after game over with lock: if self.room_id in rooms: del rooms[self.room_id] def update_game_state(self): with self.lock: for player in self.players: if not player.alive: continue head_x, head_y = player.snake[0] direction = player.direction if direction == 'UP': head_y -= 1 elif direction == 'DOWN': head_y += 1 elif direction == 'LEFT': head_x -= 1 elif direction == 'RIGHT': head_x += 1 # Adjusted for larger game size head_x %= 40 head_y %= 40 new_head = (head_x, head_y) if new_head in player.snake: player.alive = False continue for other_player in self.players: if other_player != player and new_head in other_player.snake: player.alive = False break if not player.alive: continue player.snake.insert(0, new_head) if new_head == self.game_state['food']: self.game_state['food'] = (random.randint(0, 39), random.randint(0, 39)) else: player.snake.pop() self.game_state['snakes'] = {player.name: player.snake for player in self.players if player.alive} def send_game_state(self): with self.lock: game_state_message = { 'type': 'GAME_UPDATE', 'data': self.game_state } message = json.dumps(game_state_message) for player in self.players: try: player.conn.sendall((message + '\0').encode()) except: pass def send_game_over(self): game_over_message = { 'type': 'GAME_OVER' } message = json.dumps(game_over_message) for player in self.players: try: player.conn.sendall((message + '\0').encode()) except: pass def reset_players(self): for player in self.players: player.alive = True player.direction = 'UP' player.snake = [] player.current_room = None # Reset current room # Notify player to return to menu reset_message = { 'type': 'RETURN_TO_MENU' } try: player.conn.sendall((json.dumps(reset_message) + '\0').encode()) except: passdef handle_client(conn, addr): global room_id_counter player = None try: buffer = '' while True: data = conn.recv(4096).decode() if not data: break buffer += data while '\0' in buffer: message_data, buffer = buffer.split('\0', 1) if not message_data: continue message = json.loads(message_data) if message['type'] == 'SET_NICKNAME': nickname = message['nickname'] player = Player(conn, addr, nickname) elif message['type'] == 'CREATE_ROOM': if player is None: # Must set nickname first response = {'type': 'ERROR', 'message': 'Set nickname first'} conn.sendall((json.dumps(response) + '\0').encode()) continue with lock: room_id = str(room_id_counter) room_id_counter += 1 room = Room(room_id, player) rooms[room_id] = room player.current_room = room player.snake = [(20, 20)] # Starting position adjusted for larger game size response = { 'type': 'ROOM_CREATED', 'room_id': room_id } conn.sendall((json.dumps(response) + '\0').encode()) # Wait for host to start the game elif message['type'] == 'JOIN_ROOM': if player is None: response = {'type': 'ERROR', 'message': 'Set nickname first'} conn.sendall((json.dumps(response) + '\0').encode()) continue room_id = message['room_id'] with lock: if room_id in rooms: room = rooms[room_id] if len(room.players) < 5 and not room.running: room.players.append(player) player.current_room = room player.snake = [(20 + len(room.players), 20)] response = { 'type': 'JOINED_ROOM', 'room_id': room_id } conn.sendall((json.dumps(response) + '\0').encode()) # Notify host that a new player has joined notify_message = { 'type': 'PLAYER_JOINED', 'player_name': player.name } room.host.conn.sendall((json.dumps(notify_message) + '\0').encode()) else: response = { 'type': 'ERROR', 'message': 'Room is full or game already started' } conn.sendall((json.dumps(response) + '\0').encode()) else: response = { 'type': 'ERROR', 'message': 'Room not found' } conn.sendall((json.dumps(response) + '\0').encode()) elif message['type'] == 'LIST_ROOMS': with lock: room_list = [] for room_id, room in rooms.items(): room_info = { 'room_id': room_id, 'players': len(room.players), 'running': room.running } room_list.append(room_info) response = { 'type': 'ROOM_LIST', 'rooms': room_list } conn.sendall((json.dumps(response) + '\0').encode()) elif message['type'] == 'START_GAME': if player.current_room and player == player.current_room.host and not player.current_room.running: player.current_room.start_game() elif message['type'] == 'INPUT': direction = message['direction'] if direction in ['UP', 'DOWN', 'LEFT', 'RIGHT']: player.direction = direction else: pass elif message['type'] == 'EXIT_ROOM': if player.current_room: with lock: if player in player.current_room.players: player.current_room.players.remove(player) if len(player.current_room.players) == 0: # Remove room if empty del rooms[player.current_room.room_id] player.current_room = None else: response = { 'type': 'ERROR', 'message': 'Invalid message type' } conn.sendall((json.dumps(response) + '\0').encode()) except Exception as e: print(f"Exception in handle_client: {e}") finally: if player and player.current_room and player in player.current_room.players: with lock: player.current_room.players.remove(player) if len(player.current_room.players) == 0: # Remove room if empty del rooms[player.current_room.room_id] conn.close()
def main(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() print(f"Server listening on {HOST}:{PORT}") while True: conn, addr = s.accept() print(f"Connected by {addr}") threading.Thread(target=handle_client, args=(conn, addr)).start()
if name == 'main': main()
Check the code and says if it's work correctly
- Assistant
Your code for the multiplayer snake game server is a strong foundation and demonstrates a good understanding of socket programming, threading, and game logic. However, there are several issues and potential bugs that need to be addressed to ensure it works correctly and provides a smooth gaming experience for players.
Key Issues and Suggestions:
-
Player Disconnects During Game:
- Issue: If a player disconnects during the game, their snake remains in the game, and their
alivestatus is not updated. This can cause problems because other players might collide with the remaining snake of a disconnected player. - Suggestion: Implement logic to detect when a player disconnects during the game. You can achieve this by handling exceptions during data send operations or by regularly checking if the player's connection is still active. When a disconnection is detected:
- Remove the player from the room's player list.
- Remove the player's snake from the game state.
- If desired, notify the remaining players about the disconnection.
- Issue: If a player disconnects during the game, their snake remains in the game, and their
-
Collision Detection With Dead Snakes:
- Issue: In
update_game_state, when checking for collisions with other snakes, you consider all players' snakes regardless of whether the other players are alive or dead. This means players can collide with snakes of dead or disconnected players, which might not be the intended behavior. - Suggestion: Decide whether you want dead players' snakes to remain as obstacles:
- If yes: Include dead players' snakes in
self.game_state['snakes']and keep the collision detection as is. - If no: Remove dead players' snakes from the game state by updating
self.playersandself.game_state['snakes']accordingly.
- If yes: Include dead players' snakes in
- Issue: In
-
Preventing Opposite Direction Changes:
- Issue: Currently, players can change direction to the opposite of their current direction (e.g., from 'UP' to 'DOWN'), which causes the snake to collide with itself immediately.
- Suggestion: Implement logic to prevent players from reversing direction directly. In the
INPUTmessage handling, before updatingplayer.direction, check if the new direction is not directly opposite to the current direction. For example:
This ensures that a snake cannot reverse onto itself.opposite_directions = {'UP': 'DOWN', 'DOWN': 'UP', 'LEFT': 'RIGHT', 'RIGHT': 'LEFT'} if direction != opposite_directions[player.direction]: player.direction = direction
-
Thread Safety and Locking:
- Issue: Inconsistent use of locks can lead to race conditions and unpredictable behavior. You use both a global
lockand a room-specificself.lock, which can cause confusion. - Suggestion:
- Use the room-specific lock (
self.lock) consistently whenever accessing or modifying the room's shared resources, such asplayersandgame_state. - Replace instances of
with lock:that modify room-specific data withwith self.lock:. - Ensure that all parts of the code that access shared resources are properly synchronized.
- Use the room-specific lock (
- Issue: Inconsistent use of locks can lead to race conditions and unpredictable behavior. You use both a global
-
Food Placement:
- Issue: The new food position is generated randomly and may overlap with existing snakes, which can be frustrating for players.
- Suggestion: When generating new food, ensure it does not overlap with any part of any snake. You can do this by:
- Creating a set of all occupied positions (all snake segments).
- Generating a random position and checking if it's in the occupied positions.
- Repeat the random generation until you find an unoccupied position.
-
Exception Handling When Sending Data to Players:
- Issue: In
send_game_stateandsend_game_over, you catch exceptions when sending data to players and pass without handling them. This can hide issues such as player disconnections. - Suggestion: When an exception occurs while sending data to a player:
- Assume the player has disconnected.
- Remove the player from
self.players. - Update the game state accordingly.
- Optionally, notify other players about the disconnection.
- Issue: In
-
Initial Snake Positions:
- Issue: There's a risk that initial snake positions for players could overlap, especially as new players join the room.
- Suggestion:
- Define a set of predefined starting positions that are spaced out to prevent overlap.
- Assign these positions to players when they join based on availability.
- Ensure that the starting positions wrap around or limit the maximum number of players accordingly.
-
Handling Room Removal and Cleanup:
- Issue: There might be cases where rooms are not properly removed from the global
roomsdictionary, leading to memory leaks or stale data. - Suggestion: Ensure that rooms are removed from the
roomsdictionary when:- All players have left the room.
- The game has ended, and there are no plans to restart.
- Use the room-specific lock when modifying the
roomsdictionary to prevent race conditions.
- Issue: There might be cases where rooms are not properly removed from the global
-
User Feedback and Error Messages:
- Issue: Users might not receive clear feedback when errors occur, such as attempting to join a non-existent room.
- Suggestion: Improve error handling by providing detailed and user-friendly error messages. Ensure that all possible error scenarios are covered, and users are informed about what went wrong and how they might fix it.
-
Code Readability and Maintainability:
- Issue: While the code is functional, improving readability can help with future maintenance and scalability.
- Suggestion:
- Use consistent naming conventions and code formatting.
- Add comments and docstrings to explain complex sections.
- Organize the code into separate modules or classes if necessary.
Conclusion:
By addressing these issues, you can enhance the reliability, performance, and user experience of your multiplayer snake game server. The key is to ensure robust error handling, consistent locking for thread safety, and clear communication with clients. Testing the server with multiple clients and simulating various scenarios (e.g., sudden disconnections, rapid direction changes) will help you identify and fix any additional bugs.
Feel free to ask if you need further clarification or assistance with specific parts of your code!
-