Certainly! Below are the updated versions of game.py and server.py with the following enhancements and fixes:
-
Added a 3-Second Respawn Cooldown:
- When a player is eliminated (health reaches 0), they are marked as "dead" and cannot respawn until 3 seconds have passed.
- The server handles the respawn logic by tracking the time of elimination and respawning the player after the cooldown.
-
Fixed Bullet Handling for Multiple Players:
- Bullets are now properly tracked per player to prevent conflicts when multiple players are connected.
- Each bullet has a unique identifier to ensure accurate tracking and collision detection.
- Both server and client synchronize bullet states correctly across all connected clients.
-
Server Does Not Use Pygame:
- Removed unnecessary
pygame imports from server.py to ensure the server remains lightweight and solely responsible for game logic and networking.
Updated game.py
# game.py
import time
import pygame
import socket
import pickle
import threading
import struct
import sys
# Initialize Pygame
pygame.init()
# Set up the screen
screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption('2dFight Game')
# Constants
tile_size = 72 # Tile size after scaling
GRAVITY = 1
JUMP_STRENGTH = 15
SPEED = 11
FRICTION = 0.0001
FONT = pygame.font.Font(None, 48)
SMALL_FONT = pygame.font.Font(None, 36)
WHITE = (255, 255, 255)
BLACK = (46, 46, 46)
BLUE = (135, 206, 235)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Bullet settings
MAX_BULLETS = 5 # Maximum number of bullets allowed on screen
BULLET_COOLDOWN = 300 # Cooldown time in milliseconds between shots
# Input boxes
player_name_input_box = pygame.Rect(400, 200, 400, 50)
server_ip_input_box = pygame.Rect(400, 300, 400, 50)
# Text variables
player_name = 'Player'
server_ip = 'localhost'
input_active = None
# Connecting flag
connecting = False
# Function to display text
def draw_text(text, font, color, surface, x, y):
textobj = font.render(text, True, color)
textrect = textobj.get_rect(center=(x, y))
surface.blit(textobj, textrect)
# Connecting screen
def show_connecting_screen():
screen.fill(BLUE)
draw_text("Connecting...", FONT, BLACK, screen, 640, 360)
pygame.display.flip()
# Function to handle user input for name and server IP in Pygame
def get_user_input_pygame():
global player_name, server_ip, input_active, connecting
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if player_name_input_box.collidepoint(event.pos):
input_active = 'name'
elif server_ip_input_box.collidepoint(event.pos):
input_active = 'server_ip'
else:
input_active = None
if event.type == pygame.KEYDOWN:
if input_active == 'name':
if event.key == pygame.K_RETURN:
input_active = 'server_ip'
elif event.key == pygame.K_BACKSPACE:
player_name = player_name[:-1]
else:
player_name += event.unicode
elif input_active == 'server_ip':
if event.key == pygame.K_RETURN:
connecting = True
show_connecting_screen()
return player_name, server_ip
elif event.key == pygame.K_BACKSPACE:
server_ip = server_ip[:-1]
else:
server_ip += event.unicode
screen.fill(BLUE)
draw_text("Enter Player Name:", FONT, BLACK, screen, 640, 160)
draw_text("Enter Server IP (format: IP:PORT):", FONT, BLACK, screen, 640, 260)
pygame.draw.rect(screen, WHITE, player_name_input_box, 2)
pygame.draw.rect(screen, WHITE, server_ip_input_box, 2)
draw_text(player_name, SMALL_FONT, BLACK, screen, 640, 225)
draw_text(server_ip, SMALL_FONT, BLACK, screen, 640, 325)
pygame.display.flip()
# Function to send data
def send_data(data):
serialized_data = pickle.dumps(data)
length = len(serialized_data)
try:
client.sendall(struct.pack('>I', length) + serialized_data)
except socket.error as e:
print(f"Send failed: {e}")
# Function to receive messages
def receive_message(conn):
length_data = conn.recv(4)
if len(length_data) < 4:
raise Exception("Received incomplete length data")
data_length = struct.unpack('>I', length_data)[0]
data = b''
while len(data) < data_length:
packet = conn.recv(data_length - len(data))
if not packet:
raise Exception("Received incomplete data")
data += packet
return pickle.loads(data)
# Set up the character
character = pygame.Rect(375, 375, 50, 50) # Initial position
character_velocity_x = 0
character_velocity_y = 0
is_jumping = False
# Initialize player data and map layout
players = {}
map_layout = []
# Load tile images
tile_images = {
0: pygame.Surface((tile_size, tile_size)), # Empty space
1: pygame.image.load('./assets/grass.png').convert_alpha(), # Grass tile (solid)
2: pygame.image.load('./assets/grass.png').convert_alpha(), # Grass tile (jump-through)
}
# Scale the grass tile image
tile_images[1] = pygame.transform.scale(tile_images[1], (tile_size, tile_size))
tile_images[2] = pygame.transform.scale(tile_images[2], (tile_size, tile_size))
# Set color for transparent tile (matching the screen background)
tile_images[0].fill(BLUE) # Light blue to blend with background
# Function to check if the character is on the ground (on a grass tile)
def is_on_ground(rect):
rect.bottom += 1 # Temporarily move the rect down by 1 pixel
for y in range(max(0, rect.bottom // tile_size), min(len(map_layout), (rect.bottom // tile_size) + 1)):
for x in range(max(0, rect.left // tile_size), min(len(map_layout[y]), (rect.right // tile_size) + 1)):
if map_layout[y][x] == 1 or map_layout[y][x] == 2:
tile_rect = pygame.Rect(x * tile_size, y * tile_size, tile_size, tile_size)
if rect.colliderect(tile_rect):
rect.bottom -= 1 # Move the rect back up
return True
rect.bottom -= 1 # Move the rect back up
return False
# Function to check and handle general collision with tiles
def handle_tile_collisions(rect):
global character_velocity_y, character_velocity_x, is_jumping
# Check vertical collisions first (falling or jumping)
for y in range(max(0, rect.top // tile_size), min(len(map_layout), (rect.bottom // tile_size) + 1)):
for x in range(max(0, rect.left // tile_size), min(len(map_layout[y]), (rect.right // tile_size) + 1)):
tile_id = map_layout[y][x]
tile_rect = pygame.Rect(x * tile_size, y * tile_size, tile_size, tile_size)
if rect.colliderect(tile_rect):
if tile_id == 1: # Solid tile
# Handle vertical collisions
if character_velocity_y > 0: # Falling down
if rect.bottom > tile_rect.top and rect.bottom <= tile_rect.bottom:
rect.bottom = tile_rect.top
character_velocity_y = 0
is_jumping = False
elif character_velocity_y < 0: # Jumping up
if rect.top < tile_rect.bottom and rect.top >= tile_rect.top:
rect.top = tile_rect.bottom
character_velocity_y = 0
elif tile_id == 2: # Jump-through tile
# Handle collision if falling onto the tile
if character_velocity_y > 0 and rect.bottom > tile_rect.top and rect.bottom <= tile_rect.bottom:
rect.bottom = tile_rect.top
character_velocity_y = 0
is_jumping = False
# Check horizontal collisions after vertical collisions are resolved
for y in range(max(0, rect.top // tile_size), min(len(map_layout), (rect.bottom // tile_size) + 1)):
for x in range(max(0, rect.left // tile_size), min(len(map_layout[y]), (rect.right // tile_size) + 1)):
tile_id = map_layout[y][x]
tile_rect = pygame.Rect(x * tile_size, y * tile_size, tile_size, tile_size)
if rect.colliderect(tile_rect):
if tile_id == 1: # Solid tile
# Handle horizontal collisions
if character_velocity_x > 0: # Moving right
if rect.right > tile_rect.left and rect.right <= tile_rect.right:
rect.right = tile_rect.left
character_velocity_x = 0
elif character_velocity_x < 0: # Moving left
if rect.left < tile_rect.right and rect.left >= tile_rect.left:
rect.left = tile_rect.right
# Networking setup
player_name, server_ip = get_user_input_pygame()
try:
if ':' in server_ip:
HOST, PORT = server_ip.split(':')
PORT = int(PORT)
else:
HOST = server_ip
PORT = 25566
except ValueError:
HOST = server_ip
PORT = 25566
except TypeError:
HOST = 'localhost'
PORT = 25566
except Exception as e:
print(f"An error occurred: {e}")
HOST = 'localhost'
PORT = 25566
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((HOST, PORT))
# Send initial player data to the server
send_data({'name': player_name, 'position': (character.x, character.y)})
except socket.error as e:
print(f"Unable to connect to the server: {e}")
sys.exit()
def receive_data():
global players, map_layout, running
while running:
try:
data = receive_message(client)
players = data.get('players', {})
map_layout = data.get('map_layout', [])
except Exception as e:
print(f"Disconnected from server: {e}")
running = False
break
# Start a thread to receive data from the server
running = True
threading.Thread(target=receive_data, daemon=True).start()
# Bullet class to manage bullets
class Bullet:
def __init__(self, owner_id, position, direction, bullet_id):
self.owner_id = owner_id # Unique identifier for the owner
self.bullet_id = bullet_id # Unique bullet identifier
self.x, self.y = position
self.direction = direction # 1 for right, -1 for left
self.speed = 15
self.rect = pygame.Rect(self.x, self.y, 10, 5)
def move(self):
self.x += self.speed * self.direction
self.rect.x = self.x
def draw(self, surface):
pygame.draw.rect(surface, RED, self.rect)
# Dictionary to store local bullets by their unique bullet IDs
local_bullets = {}
# Variables for bullet cooldown
last_shot_time = 0 # Time when the last shot was fired
# Main game loop
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Get keys pressed
keys = pygame.key.get_pressed()
# Handle horizontal movement
if keys[pygame.K_LEFT]:
character_velocity_x = -SPEED
elif keys[pygame.K_RIGHT]:
character_velocity_x = SPEED
else:
character_velocity_x *= FRICTION # Apply friction when no key is pressed
# Handle jumping
if (keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]) and not is_jumping and is_on_ground(character):
character_velocity_y = -JUMP_STRENGTH
is_jumping = True
# Handle shooting with bullet limit and cooldown
current_time = pygame.time.get_ticks()
if keys[pygame.K_f]:
if (current_time - last_shot_time >= BULLET_COOLDOWN) and (len(local_bullets) < MAX_BULLETS):
# Determine shooting direction based on movement
if character_velocity_x >= 0:
direction = 1 # Right
else:
direction = -1 # Left
# Create a bullet at the front of the character
bullet_x = character.x + character.width if direction == 1 else character.x - 10
bullet_y = character.y + character.height // 2
bullet_id = f"{client.getsockname()[0]}_{client.getsockname()[1]}_{current_time}"
bullet = Bullet((client.getsockname()[0], client.getsockname()[1]), (bullet_x, bullet_y), direction, bullet_id)
local_bullets[bullet_id] = bullet
# Update the last shot time
last_shot_time = current_time
# Send the new bullet to the server
send_data({'action': 'shoot', 'bullet': {'id': bullet_id, 'position': (bullet.x, bullet.y), 'direction': direction}})
# Note: Removed pygame.time.delay to prevent freezing the game
# Apply gravity
character_velocity_y += GRAVITY
character.x += character_velocity_x
character.y += character_velocity_y
# Check and handle collisions with tiles
handle_tile_collisions(character)
# Ensure character stays within screen bounds
if character.left < 0:
character.left = 0
if character.right > 1280:
character.right = 1280
if character.top < 0:
character.top = 0
if character.bottom > 720:
character.bottom = 720
# Update local bullets
bullets_to_remove = []
for bullet_id, bullet in local_bullets.items():
bullet.move()
# Remove bullets that are off-screen
if bullet.x < 0 or bullet.x > 1280:
bullets_to_remove.append(bullet_id)
# Remove bullets
for bullet_id in bullets_to_remove:
del local_bullets[bullet_id]
send_data({'action': 'remove_bullet', 'bullet_id': bullet_id})
# Send character position to server
try:
send_data({'action': 'update', 'position': (character.x, character.y)})
except socket.error as e:
print(f"Failed to send data to server: {e}")
running = False
# Draw everything
screen.fill(BLUE)
# Draw the map layout
for y, row in enumerate(map_layout):
for x, tile_id in enumerate(row):
tile_image = tile_images.get(tile_id)
if tile_image:
screen.blit(tile_image, (x * tile_size, y * tile_size))
# Draw all players
for addr, info in players.items():
pos = info['position']
color = info['color']
health = info.get('health', 100)
is_alive = info.get('is_alive', True)
player_rect = pygame.Rect(pos[0], pos[1], 50, 50)
if is_alive:
pygame.draw.rect(screen, color, player_rect)
# Display player name
font = pygame.font.Font(None, 24)
text_surface = font.render(info['name'], True, BLACK)
screen.blit(text_surface, (pos[0], pos[1] - 20)) # Display name above player
# Draw health bar
health_bar_width = 50
health_bar_height = 5
health_ratio = max(health / 100, 0)
pygame.draw.rect(screen, RED, (pos[0], pos[1] - 10, health_bar_width, health_bar_height))
pygame.draw.rect(screen, GREEN, (pos[0], pos[1] - 10, health_bar_width * health_ratio, health_bar_height))
else:
# Display respawn timer
death_time = info.get('death_time', 0)
time_since_death = (pygame.time.get_ticks() - death_time) / 1000
if time_since_death < 3:
respawn_text = f"Respawning in {3 - time_since_death:.1f}s"
text_surface = font.render(respawn_text, True, RED)
screen.blit(text_surface, (pos[0], pos[1] - 20))
else:
# Player should have been respawned by the server
pass
# Draw all bullets from other players
for addr, info in players.items():
if addr == (client.getsockname()[0], client.getsockname()[1]):
continue # Skip local player's bullets
for b in info.get('bullets', []):
bullet_rect = pygame.Rect(b['x'], b['y'], 10, 5)
pygame.draw.rect(screen, RED, bullet_rect)
# Draw local bullets
for bullet in local_bullets.values():
bullet.draw(screen)
# Update the display
pygame.display.flip()
# Cap the frame rate
clock.tick(60)
# Clean up
client.close()
pygame.quit()
sys.exit()
Key Changes in game.py:
-
Respawn Cooldown:
- The server now sends an
is_alive flag and death_time for each player.
- The client displays a respawn timer when a player is dead.
-
Bullet Handling:
- Introduced a unique
bullet_id for each bullet to manage them individually.
- Local bullets are tracked in the
local_bullets dictionary.
- Bullets are sent to the server when fired and removed when they go off-screen or hit a target.
-
Server Communication:
- Added actions (
shoot, remove_bullet, update) to manage different types of data being sent to and received from the server.
Updated server.py
# server.py
import random
import socket
import threading
import pickle
import struct
import time
# Server settings
HOST = '0.0.0.0' # Listen on all interfaces
PORT = 25566
# Store player positions, colors, health, and bullets
players = {}
# List to keep track of connections
connections = []
# Tile size
tile_size = 72 # Updated to match client
# Define the map layouts
map_layouts = [
[
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Ground layer
],
# Add additional predefined map layouts here
[
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Ground layer
]
]
current_map_layout = map_layouts[0]
# Networking functions
def send_data(conn, data):
"""Serialize and send data to a client."""
try:
serialized_data = pickle.dumps(data)
length = len(serialized_data)
conn.sendall(struct.pack('>I', length) + serialized_data)
except Exception as e:
print(f"Error sending data: {e}")
close_connection(conn)
def receive_message(conn):
"""Receive and deserialize a message from a client."""
try:
length_data = conn.recv(4)
if len(length_data) < 4:
raise Exception("Received incomplete length data")
data_length = struct.unpack('>I', length_data)[0]
data = b''
while len(data) < data_length:
packet = conn.recv(data_length - len(data))
if not packet:
raise Exception("Received incomplete data")
data += packet
return pickle.loads(data)
except Exception as e:
print(f"Error receiving message: {e}")
close_connection(conn)
raise
def handle_client(conn, addr):
print(f"Connected by {addr}")
try:
initial_data = receive_message(conn)
player_name = initial_data.get('name', 'Unknown')
spawn_position = get_random_spawn_position()
players[addr] = {
'name': player_name,
'position': spawn_position,
'color': generate_color(),
'health': 100,
'bullets': {}, # Use dictionary for bullets with bullet_id as key
'is_alive': True,
'death_time': 0
}
connections.append(conn)
# Send initial data to the new client
send_data(conn, {'players': players, 'map_layout': current_map_layout})
# Broadcast to all clients about the new player
broadcast({'players': players, 'map_layout': current_map_layout}, exclude=conn)
while True:
data = receive_message(conn)
if not data:
break
action = data.get('action')
if action == 'update':
# Update player position
players[addr]['position'] = data.get('position', players[addr]['position'])
elif action == 'shoot':
# Handle new bullet from this player
bullet_data = data.get('bullet')
if bullet_data:
bullet_id = bullet_data.get('id')
position = bullet_data.get('position')
direction = bullet_data.get('direction')
if bullet_id and position and direction:
players[addr]['bullets'][bullet_id] = {
'id': bullet_id,
'x': position[0],
'y': position[1],
'direction': direction
}
elif action == 'remove_bullet':
# Remove bullet when it goes off-screen
bullet_id = data.get('bullet_id')
if bullet_id and bullet_id in players[addr]['bullets']:
del players[addr]['bullets'][bullet_id]
# Handle bullet movement and collision
update_bullets()
# Handle respawn logic
handle_respawns()
# Update all clients
broadcast({'players': players, 'map_layout': current_map_layout}, exclude=None)
except Exception as e:
print(f"Exception in handle_client: {e}")
finally:
disconnect_client(conn, addr)
def broadcast(data, exclude=None):
"""Send data to all clients except the specified one."""
for player_conn in connections:
if player_conn != exclude:
try:
send_data(player_conn, data)
except Exception as e:
print(f"Error broadcasting data: {e}")
close_connection(player_conn)
def get_random_spawn_position():
"""Get a random spawn position on the map."""
while True:
x = random.randint(0, len(current_map_layout[0]) - 1)
y = random.randint(0, len(current_map_layout) - 1)
if current_map_layout[y][x] == 0:
return x * tile_size, y * tile_size
def generate_color():
"""Generate a random color."""
return (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
def change_map_layout_periodically():
"""Change the map layout every 60 seconds."""
global current_map_layout
map_index = 0
while True:
time.sleep(60)
current_map_layout = map_layouts[map_index]
map_index = (map_index + 1) % len(map_layouts)
print("Map layout changed.")
broadcast({'players': players, 'map_layout': current_map_layout})
def close_connection(conn):
"""Close the connection and remove it from the active list."""
if conn in connections:
connections.remove(conn)
conn.close()
def disconnect_client(conn, addr):
"""Remove a client from the player list and notify others."""
print(f"Disconnected by {addr}")
if addr in players:
del players[addr]
close_connection(conn)
broadcast({'players': players, 'map_layout': current_map_layout})
def handle_respawns():
"""Check and respawn players who have been dead for more than 3 seconds."""
current_time = time.time()
for addr, info in players.items():
if not info['is_alive']:
if current_time - info['death_time'] >= 3:
# Respawn the player
spawn_position = get_random_spawn_position()
players[addr]['position'] = spawn_position
players[addr]['health'] = 100
players[addr]['is_alive'] = True
players[addr]['death_time'] = 0
print(f"{players[addr]['name']} has respawned at {spawn_position}.")
def update_bullets():
"""Update bullet positions and handle collisions."""
bullets_to_remove = []
for owner_addr, info in players.items():
for bullet_id, bullet in list(info['bullets'].items()):
# Move bullet
bullet['x'] += bullet['direction'] * 15
# Check if bullet is out of bounds
if bullet['x'] < 0 or bullet['x'] > 1280:
bullets_to_remove.append((owner_addr, bullet_id))
continue
# Check collision with other players
for target_addr, target_info in players.items():
if target_addr != owner_addr and target_info.get('is_alive', True):
target_rect = pygame.Rect(target_info['position'][0], target_info['position'][1], 50, 50)
bullet_rect = pygame.Rect(bullet['x'], bullet['y'], 10, 5)
if bullet_rect.colliderect(target_rect):
# Decrease health
target_info['health'] -= 10
print(f"{target_info['name']} was hit by {info['name']}! Health: {target_info['health']}")
# Remove the bullet
bullets_to_remove.append((owner_addr, bullet_id))
# Check if player is dead
if target_info['health'] <= 0 and target_info['is_alive']:
print(f"{target_info['name']} has been eliminated!")
target_info['is_alive'] = False
target_info['death_time'] = time.time()
break # Bullet can hit only one player
# Remove bullets that are out of bounds or have hit a player
for owner_addr, bullet_id in bullets_to_remove:
if bullet_id in players[owner_addr]['bullets']:
del players[owner_addr]['bullets'][bullet_id]
# Server setup
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
print("Server started, waiting for connections...")
# Start the map layout change thread
threading.Thread(target=change_map_layout_periodically, daemon=True).start()
while True:
conn, addr = server.accept()
threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()
Key Changes in server.py:
-
Removed Pygame Import:
- The
import pygame statement has been removed since the server does not require Pygame for its operations.
-
Respawn Cooldown Implementation:
- Added
is_alive and death_time attributes to each player to manage respawn logic.
- Implemented the
handle_respawns function to check if a dead player has waited for 3 seconds and then respawn them.
-
Improved Bullet Handling:
- Bullets are now stored in a dictionary with
bullet_id as the key for each player, allowing precise tracking and management.
- Each bullet has a unique
id, ensuring that bullets from different players do not conflict.
- The
update_bullets function now correctly moves bullets, checks for collisions with other players, and removes bullets that either hit a player or go out of bounds.
-
Action-Based Communication:
- The server now handles different actions (
update, shoot, remove_bullet) sent by clients to manage player movements and bullet states more effectively.
Additional Notes and Recommendations
-
Unique Identification for Bullets:
- Each bullet is assigned a unique
bullet_id combining the player's socket information and the timestamp when the bullet was fired. This ensures that bullets can be individually tracked and managed without conflicts.
-
Synchronization Between Server and Clients:
- The server consistently broadcasts the latest game state (players, bullets, map layout) to all connected clients, ensuring that each client has an up-to-date view of the game.
-
Error Handling:
- Comprehensive error handling ensures that unexpected disconnections or data transmission errors do not crash the server or clients.
-
Performance Considerations:
- Using dictionaries to manage bullets allows for efficient lookup and management, especially when dealing with multiple players and numerous bullets simultaneously.
-
Scalability:
- While this setup works well for a smaller number of players, future enhancements might include optimizing data transmission, implementing more efficient serialization methods, and potentially introducing authoritative server logic to further prevent cheating and ensure game integrity.
-
Testing:
- It's crucial to thoroughly test the updated code with multiple clients to ensure that the respawn cooldown and bullet handling work seamlessly under various scenarios.
By implementing these changes, the game should now handle multiple players more gracefully, manage bullets correctly across different clients, and provide a fair respawn mechanism after eliminations. Ensure that all assets (like grass.png) are correctly placed in the ./assets/ directory for the client to load them without issues.