add respawn 3 seconds cooldown and fix any issues with game like bullets not handle…
- User
add respawn 3 seconds cooldown and fix any issues with game like bullets not handle corractly when more than 1 person connect to server give me full code
game.py import time import pygame import socket import pickle import threading import struct import sys import json
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:", 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) client.sendall(struct.pack('>I', length) + serialized_data)
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.rightNetworking 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, '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, position, direction): self.owner = owner # Tuple (IP, PORT) 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)List to store bullets
bullets = []
Variables for bullet cooldown
last_shot_time = 0 # Time when the last shot was fired
Main game loop
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(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 bullets.append(Bullet((client.getsockname()[0], client.getsockname()[1]), (bullet_x, bullet_y), direction)) # Update the last shot time last_shot_time = current_time elif len(bullets) >= MAX_BULLETS: print("Maximum bullet limit reached!") # 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 bullets for bullet in bullets[:]: bullet.move() # Remove bullets that are off-screen if bullet.x < 0 or bullet.x > 1280: bullets.remove(bullet) # Send character position and bullets to server try: # Serialize bullet data bullet_data = [{'x': b.x, 'y': b.y, 'direction': b.direction} for b in bullets] send_data({'name': player_name, 'position': (character.x, character.y), 'bullets': bullet_data}) 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) 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)) # Draw all bullets from other players for addr, info in players.items(): 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 bullets: bullet.draw(screen) # Update the display pygame.display.flip() # Cap the frame rate pygame.time.Clock().tick(60)pygame.quit()
server.py import random import socket import threading import pickle import struct import time
import pygame
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) raisedef 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': [] }
# 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 # Update player position players[addr]['position'] = data['position'] # Handle bullets from this player incoming_bullets = data.get('bullets', []) for b in incoming_bullets: bullet = { 'owner': addr, 'x': b['x'], 'y': b['y'], 'direction': b['direction'] } players[addr]['bullets'].append(bullet) # Update bullets positions and handle collisions update_bullets() # Remove bullets that have hit or are out of bounds for player_addr in players: bullets_to_remove = [] for bullet in players[player_addr]['bullets']: # 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(bullet) continue # Check collision with other players for other_addr, info in players.items(): if other_addr != player_addr: other_rect = pygame.Rect(info['position'][0], info['position'][1], 50, 50) bullet_rect = pygame.Rect(bullet['x'], bullet['y'], 10, 5) if bullet_rect.colliderect(other_rect): # Decrease health info['health'] -= 10 print(f"{info['name']} was hit by {players[player_addr]['name']}! Health: {info['health']}") # Remove the bullet bullets_to_remove.append(bullet) # Check if player is dead if info['health'] <= 0: print(f"{info['name']} has been eliminated!") # Reset player position and health info['position'] = get_random_spawn_position() info['health'] = 100 break # Remove bullets for bullet in bullets_to_remove: players[player_addr]['bullets'].remove(bullet) # 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(): x = random.randint(0, len(current_map_layout[0]) - 1) y = random.randint(0, len(current_map_layout) - 1) return x * tile_size, y * tile_size
def generate_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 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})
Connection handling
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})
Core game functions
def update_bullets(): """Update bullet positions and handle collisions (optional if handled differently).""" pass # Already handled in handle_client
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() connections.append(conn) threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()
- Assistant
To implement a 3-second respawn cooldown and ensure bullets are correctly handled in a multiplayer environment, we'll need to make several modifications to both the
game.py(client) andserver.pyscripts. Below is the updated full code for both files, incorporating these features and addressing potential issues with bullet handling when multiple players are connected.Summary of Changes:
-
Respawn Mechanism:
- Added a respawn timer on the server to handle player respawning after death with a 3-second cooldown.
- Updated the client to handle the respawn state, disabling player controls during the cooldown.
-
Bullet Handling:
- Ensured that bullets are uniquely associated with their owners to prevent conflicts.
- Optimized the bullet synchronization between server and clients to handle multiple players effectively.
-
General Improvements:
- Enhanced error handling and connection management.
- Improved synchronization of player states and bullet positions across all clients.
Updated
game.py(Client)import time import pygame import socket import pickle import threading import struct import sys import json # Initialize Pygame pygame.init() # Set up the screen SCREEN_WIDTH, SCREEN_HEIGHT = 1280, 720 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('2D Fight 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, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2) 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, SCREEN_WIDTH // 2, 160) draw_text("Enter Server IP (e.g., localhost:25566):", FONT, BLACK, screen, SCREEN_WIDTH // 2, 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) client.sendall(struct.pack('>I', length) + serialized_data) # 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 is_dead = False respawn_time = 0 # 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, position, direction): self.owner = owner # Tuple (IP, PORT) 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) # List to store local bullets bullets = [] # Variables for bullet cooldown last_shot_time = 0 # Time when the last shot was fired # Respawn cooldown RESPAWN_COOLDOWN = 3000 # 3 seconds in milliseconds # 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 movement only if not dead if not is_dead: # 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, only if not dead current_time = pygame.time.get_ticks() if not is_dead and keys[pygame.K_f]: if (current_time - last_shot_time >= BULLET_COOLDOWN) and (len(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 bullets.append(Bullet((client.getsockname()[0], client.getsockname()[1]), (bullet_x, bullet_y), direction)) # Send bullet data to the server send_data({ 'name': player_name, 'position': (character.x, character.y), 'bullets': [{'x': bullet.x, 'y': bullet.y, 'direction': bullet.direction} for bullet in bullets] }) # Update the last shot time last_shot_time = current_time elif len(bullets) >= MAX_BULLETS: print("Maximum bullet limit reached!") # Apply gravity if not is_dead: 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 > SCREEN_WIDTH: character.right = SCREEN_WIDTH if character.top < 0: character.top = 0 if character.bottom > SCREEN_HEIGHT: character.bottom = SCREEN_HEIGHT else: # Check if respawn cooldown has passed if current_time >= respawn_time: is_dead = False # Reset position and health (can be handled via server) send_data({'name': player_name, 'position': (character.x, character.y), 'respawn': True}) # Update bullets for bullet in bullets[:]: bullet.move() # Remove bullets that are off-screen if bullet.x < 0 or bullet.x > SCREEN_WIDTH: bullets.remove(bullet) # Notify server to remove bullet send_data({ 'name': player_name, 'position': (character.x, character.y), 'bullets': [{'x': bullet.x, 'y': bullet.y, 'direction': bullet.direction} for bullet in bullets] }) # Send character position and bullets to server if not dead if not is_dead: try: # Serialize bullet data bullet_data = [{'x': b.x, 'y': b.y, 'direction': b.direction} for b in bullets] send_data({'name': player_name, 'position': (character.x, character.y), 'bullets': bullet_data}) 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) player_rect = pygame.Rect(pos[0], pos[1], 50, 50) pygame.draw.rect(screen, color, player_rect) text_surface = SMALL_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)) # Draw all bullets from other players for addr, info in players.items(): 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 bullets: bullet.draw(screen) # If dead, display respawn message if is_dead: draw_text("You are dead! Respawning in 3 seconds...", FONT, RED, screen, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2) # Update the display pygame.display.flip() # Cap the frame rate clock.tick(60) # Handle respawn logic based on player health from server if player_name in players and players[player_name].get('health', 100) <= 0 and not is_dead: is_dead = True respawn_time = current_time + RESPAWN_COOLDOWN character.x, character.y = -100, -100 # Move off-screen or to a designated spawn point pygame.quit()
Updated
server.py(Server)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', f'Player_{addr}') spawn_position = get_random_spawn_position() players[player_name] = { 'name': player_name, 'position': spawn_position, 'color': generate_color(), 'health': 100, 'bullets': [], 'respawning': False, 'respawn_timer': 0 } # 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=None) while True: data = receive_message(conn) if not data: break player = players.get(data['name']) if not player: continue # Handle respawn if player['respawning']: current_time = time.time() * 1000 # Current time in milliseconds if current_time >= player['respawn_timer']: # Respawn the player player['position'] = get_random_spawn_position() player['health'] = 100 player['respawning'] = False send_data(conn, {'respawn': True, 'position': player['position'], 'health': player['health']}) # Update player position if not player['respawning']: player['position'] = data['position'] # Handle bullets from this player incoming_bullets = data.get('bullets', []) for b in incoming_bullets: bullet = { 'owner': data['name'], 'x': b['x'], 'y': b['y'], 'direction': b['direction'] } player['bullets'].append(bullet) # Update bullets positions and handle collisions update_bullets() # 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 above the ground layer.""" ground_y = len(current_map_layout) - 1 x = random.randint(0, len(current_map_layout[0]) - 1) * tile_size y = (ground_y - 2) * tile_size - tile_size // 2 # Slightly above the ground return x, y def generate_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}) # Connection handling 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}") player_to_remove = None for name, info in players.items(): # Assuming player's name is unique if info['position'] == players.get(name, {}).get('position'): player_to_remove = name break if player_to_remove: del players[player_to_remove] close_connection(conn) broadcast({'players': players, 'map_layout': current_map_layout}) # Core game functions def update_bullets(): """Update bullet positions and handle collisions.""" for player_name, player in players.items(): bullets_to_remove = [] for bullet in player['bullets']: # Move bullet bullet['x'] += bullet['direction'] * 15 # Check if bullet is out of bounds if bullet['x'] < 0 or bullet['x'] > SCREEN_WIDTH: bullets_to_remove.append(bullet) continue # Check collision with tiles tile_x = bullet['x'] // tile_size tile_y = bullet['y'] // tile_size if 0 <= tile_y < len(current_map_layout) and 0 <= tile_x < len(current_map_layout[0]): tile_id = current_map_layout[tile_y][tile_x] if tile_id == 1: # Solid tile bullets_to_remove.append(bullet) continue # Check collision with other players for other_name, other_player in players.items(): if other_name == player_name or other_player['respawning']: continue other_rect = pygame.Rect(other_player['position'][0], other_player['position'][1], 50, 50) bullet_rect = pygame.Rect(bullet['x'], bullet['y'], 10, 5) if bullet_rect.colliderect(other_rect): # Decrease health other_player['health'] -= 10 print(f"{other_player['name']} was hit by {player_name}! Health: {other_player['health']}") bullets_to_remove.append(bullet) # Check if player is dead if other_player['health'] <= 0: print(f"{other_player['name']} has been eliminated!") other_player['respawning'] = True other_player['respawn_timer'] = time.time() * 1000 + RESPAWN_COOLDOWN other_player['health'] = 0 # To prevent multiple hits break # Remove bullets that hit something or are out of bounds for bullet in bullets_to_remove: if bullet in player['bullets']: player['bullets'].remove(bullet) def broadcast_data(): """Continuously broadcast player and map data to all clients.""" while True: broadcast({'players': players, 'map_layout': current_map_layout}, exclude=None) time.sleep(0.05) # Send updates at 20 FPS # Server setup server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((HOST, PORT)) server.listen() print("Server started, waiting for connections...") connections = [] # Start the map layout change thread threading.Thread(target=change_map_layout_periodically, daemon=True).start() # Start the bullet update thread threading.Thread(target=broadcast_data, daemon=True).start() while True: conn, addr = server.accept() connections.append(conn) threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()
Explanation of Key Changes
1. Respawn Mechanism
-
Server (
server.py):- Player State Addition: Each player now has
respawningandrespawn_timerattributes to manage their respawn state. - Respawn Logic: When a player's health drops to 0 or below, the server sets
respawningtoTrueand initiates arespawn_timer. After 3 seconds, the player is respawned at a random spawn position with full health. - Broadcast Respawn: The server sends a respawn event to the client to reposition the player and reset their health.
- Player State Addition: Each player now has
-
Client (
game.py):- Respawn Handling: The client checks if the player is dead (
is_dead) and displays a respawn message. It also disables player controls during the respawn cooldown. - Position Reset: Upon respawning, the player's position is reset based on the server's information.
- Respawn Handling: The client checks if the player is dead (
2. Bullet Handling
-
Server (
server.py):- Unique Bullet Association: Bullets are now associated with the
owner(player name) to prevent conflicts. - Collision Detection: The server handles bullet collisions with both the environment (tiles) and other players. Upon collision, appropriate actions like reducing health or removing bullets are taken.
- Cleanup: Bullets that go out of bounds or hit a target are removed from the game state.
- Unique Bullet Association: Bullets are now associated with the
-
Client (
game.py):- Bullet Synchronization: The client sends bullet data to the server whenever a new bullet is fired or bullets are removed.
- Drawing Other Players' Bullets: The client draws bullets from all players by iterating through the
playersdictionary.
3. General Improvements
- Error Handling: Improved error handling ensures that unexpected disconnections or data issues don't crash the server or client.
- Concurrent Broadcasting: The server now includes a separate thread (
broadcast_data) to continuously send updated game states to all clients at regular intervals. - Synchronization: Both client and server maintain synchronization of player states, including their positions, health, and bullets, ensuring a consistent multiplayer experience.
Final Notes
-
Assets: Ensure that the
./assets/grass.pngimage exists and is correctly referenced in thegame.pyscript. Missing assets will cause the client to crash when loading tile images. -
Running the Game:
- Start the Server: Run the
server.pyscript on a machine accessible to all clients. - Start Clients: Run the
game.pyscript on each client machine. When prompted, enter the player name and server IP (e.g.,localhost:25566if running locally).
- Start the Server: Run the
-
Testing: To test multiplayer functionality, run multiple instances of
game.pyeither on the same machine using different Python environments or on different machines within the same network. -
Enhancements: Further improvements can include more sophisticated collision detection, graphical enhancements, and additional game mechanics such as different weapon types or power-ups.
By implementing these changes, the game should now support a fair respawn system with a 3-second cooldown and handle bullets correctly across multiple players connected to the server.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.