Adding guns to your 2D fighting game involves introducing a shooting mechanism where players can fire bullets, manage these bullets on both the client and server sides, and handle collisions between bullets and players or the environment. Below is the enhanced code for both game.py and server.py with full integration of guns functionality.
Overview of Changes
Client (game.py)
-
Bullet Management:
- Introduce a
Bullet class to represent individual bullets.
- Maintain a list of active bullets received from the server.
-
Shooting Mechanism:
- Handle shooting input (e.g., mouse clicks or pressing a key like
F).
- Calculate the direction of the bullet based on the player's facing direction or mouse position.
- Send shooting events to the server with the necessary bullet information.
-
Rendering:
- Render bullets on the screen based on the bullet data received from the server.
Server (server.py)
-
Bullet Management:
- Introduce a
Bullet class to represent bullets.
- Maintain a list of active bullets.
-
Shooting Handling:
- When a client fires a bullet, add it to the server's bullet list.
- Update bullet positions over time.
- Check for collisions between bullets and players or the environment.
- Remove bullets upon collision or when they go out of bounds.
-
Broadcasting:
- Continuously send updated bullet data to all connected clients.
Let's delve into the detailed code changes.
Enhanced game.py
import time
import pygame
import socket
import pickle
import threading
import struct
import sys
import math
# 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('2dFight Game with Guns')
# 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) # Bullet color
# 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, SCREEN_WIDTH // 2, 225)
draw_text(server_ip, SMALL_FONT, BLACK, screen, SCREEN_WIDTH // 2, 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)
# Bullet class to represent bullets
class Bullet:
def __init__(self, x, y, direction):
self.x = x
self.y = y
self.direction = direction # Radians
self.speed = 15 # Pixels per frame
self.radius = 5 # Bullet size
def update(self):
self.x += self.speed * math.cos(self.direction)
self.y += self.speed * math.sin(self.direction)
def get_position(self):
return (int(self.x), int(self.y))
# Initialize player data and map layout
players = {}
bullets = []
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
# Function to draw a bullet
def draw_bullet(bullet):
pygame.draw.circle(screen, RED, bullet.get_position(), bullet.radius)
# Networking setup
player_name, server_ip = get_user_input_pygame()
try:
if ':' in server_ip:
HOST, PORT = server_ip.split(':')
PORT = int(PORT) if PORT else 25566
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': (375, 375), 'action': 'join'})
except socket.error as e:
print(f"Unable to connect to the server: {e}")
sys.exit()
def receive_data():
global players, map_layout, bullets_list, running
while running:
try:
data = receive_message(client)
players = data.get('players', {})
map_layout = data.get('map_layout', [])
bullets_list = data.get('bullets', [])
except Exception as e:
print(f"Disconnected from server: {e}")
running = False
break
# Start a thread to receive data from the server
bullets_list = []
running = True
threading.Thread(target=receive_data, daemon=True).start()
# Main game loop
# Set up the character
character = pygame.Rect(375, 375, 50, 50) # Initial position
character_velocity_x = 0
character_velocity_y = 0
is_jumping = False
facing_direction = 0 # Angle in radians
clock = pygame.time.Clock()
while running:
dt = clock.tick(60) # Frame rate
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left click to shoot
mouse_x, mouse_y = pygame.mouse.get_pos()
dx = mouse_x - (character.x + character.width / 2)
dy = mouse_y - (character.y + character.height / 2)
angle = math.atan2(dy, dx)
# Send shoot event to server
send_data({
'action': 'shoot',
'position': (character.x + character.width / 2, character.y + character.height / 2),
'direction': angle
})
if not running:
break
# Get keys pressed
keys = pygame.key.get_pressed()
# Handle horizontal movement
if keys[pygame.K_LEFT]:
character_velocity_x = -SPEED
facing_direction = math.pi # Left
elif keys[pygame.K_RIGHT]:
character_velocity_x = SPEED
facing_direction = 0 # Right
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
# 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 > SCREEN_WIDTH:
character.right = SCREEN_WIDTH
if character.top < 0:
character.top = 0
if character.bottom > SCREEN_HEIGHT:
character.bottom = SCREEN_HEIGHT
character_velocity_y = 0
is_jumping = False
# Update bullets on client side (optional visual smoothing)
# Here, bullets are managed by the server, so client just renders them
# bullets = [Bullet(b['x'], b['y'], b['direction']) for b in bullets_list]
# Update character position to send to server
try:
send_data({'name': player_name, 'position': (character.x, character.y), 'action': 'move'})
except socket.error as e:
print(f"Failed to send data to server: {e}")
running = False
# Light blue background
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.get('color', BLACK)
pygame.draw.rect(screen, color, (pos[0], pos[1], 50, 50))
text_surface = SMALL_FONT.render(info['name'], True, BLACK)
screen.blit(text_surface, (pos[0], pos[1] - 20)) # Display name above player
# Draw all bullets
for b in bullets_list:
bullet_pos = b.get('position', (0, 0))
bullet_dir = b.get('direction', 0)
bullet_rect = pygame.Rect(bullet_pos[0]-5, bullet_pos[1]-5, 10, 10)
pygame.draw.circle(screen, RED, (int(bullet_pos[0]), int(bullet_pos[1])), 5)
# Update the display
pygame.display.flip()
# Clean up
client.close()
pygame.quit()
sys.exit()
Explanation of Changes in game.py:
-
Bullet Representation:
- A
Bullet class is introduced to encapsulate bullet properties and behaviors. However, in this simplified client-side implementation, bullets are primarily rendered based on server data.
-
Shooting Mechanism:
- When a player left-clicks (
pygame.MOUSEBUTTONDOWN with event.button == 1), the client calculates the direction of the shot based on the mouse position relative to the player’s position.
- This shooting event is sent to the server with the player's current position and the calculated shooting direction.
-
Bullet Rendering:
- Bullets received from the server are rendered as red circles on the screen.
- The bullets' positions are updated based on the data received from the server.
-
Data Handling:
- The client continuously sends player movement data and shooting events to the server.
- The client also receives updates about player positions, map layout, and active bullets from the server.
Enhanced server.py
import random
import socket
import threading
import pickle
import struct
import time
import math
# Server settings
HOST = '0.0.0.0' # Listen on all interfaces
PORT = 25566
# Store player positions and colors
players = {}
# Store active bullets
bullets = []
# 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], # Row 0 (Top)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 1
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 2
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 3
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 4
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], # Row 5
[0, 0, 0, 0, 1, 1, 1, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 6
[0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 1, 1, 0, 0, 0], # Row 7
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 8
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Row 9 (Ground)
],
# 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], # Row 0
[0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0], # Row 1
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 2
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1], # Row 3
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 4
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0], # Row 5
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 6
[0, 1, 1, 0, 1, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 0, 1, 0], # Row 7
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # Row 8
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # Row 9 (Ground)
]
]
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
# Bullet class to represent bullets
class Bullet:
def __init__(self, x, y, direction, owner):
self.x = x
self.y = y
self.direction = direction # Radians
self.speed = 15 # Pixels per update
self.owner = owner # Player's address
self.radius = 5 # Bullet size
self.active = True
def update(self):
self.x += self.speed * math.cos(self.direction)
self.y += self.speed * math.sin(self.direction)
# Check if bullet is out of bounds
if self.x < 0 or self.x > 1280 or self.y < 0 or self.y > 720:
self.active = False
def get_position(self):
return (int(self.x), int(self.y))
# Core game functions
def handle_client(conn, addr):
print(f"Connected by {addr}")
try:
initial_data = receive_message(conn)
if initial_data.get('action') != 'join':
raise Exception("First message must be 'join' action")
player_name = initial_data.get('name', 'Unknown')
spawn_position = get_random_spawn_position()
players[addr] = {
'name': player_name,
'position': spawn_position,
'color': generate_color()
}
# Send initial data to the client
send_data(conn, {
'players': players,
'map_layout': current_map_layout,
'bullets': [{'position': b.get_position(), 'direction': b.direction} for b in bullets if b.active]
})
while True:
data = receive_message(conn)
action = data.get('action')
if action == 'move':
players[addr]['position'] = data.get('position', players[addr]['position'])
elif action == 'shoot':
shoot_pos = data.get('position')
direction = data.get('direction')
if shoot_pos and direction is not None:
bullet = Bullet(shoot_pos[0], shoot_pos[1], direction, addr)
bullets.append(bullet)
else:
print(f"Unknown action from {addr}: {action}")
# Prepare bullets data
active_bullets = [{'position': b.get_position(), 'direction': b.direction} for b in bullets if b.active]
# Update bullets positions
for bullet in bullets:
if bullet.active:
bullet.update()
# Check collision with players
for player_addr, info in players.items():
if player_addr != bullet.owner:
player_rect = pygame.Rect(info['position'][0], info['position'][1], 50, 50)
if player_rect.collidepoint(bullet.x, bullet.y):
print(f"{info['name']} was hit by {players[bullet.owner]['name']}'s bullet!")
# Handle player hit (e.g., reduce health, respawn)
# For simplicity, we'll just remove the player
send_data(player_conn_map[player_addr], {'action': 'hit', 'message': f"You were hit by {players[bullet.owner]['name']}"})
disconnect_client(conn, player_addr)
bullet.active = False
break # Bullet is inactive now
# Remove inactive bullets
bullets[:] = [b for b in bullets if b.active]
# Update active bullets to send
active_bullets = [{'position': b.get_position(), 'direction': b.direction} for b in bullets if b.active]
# Prepare data to broadcast
broadcast_data = {
'players': players,
'map_layout': current_map_layout,
'bullets': active_bullets
}
broadcast(broadcast_data)
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 within the map bounds."""
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: # Empty space
return x * tile_size, y * tile_size - tile_size # Adjust y to place player above the ground
def generate_color():
"""Generate a random color for a player."""
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.")
# Notify all clients about the map change
broadcast({'players': players, 'map_layout': current_map_layout, 'bullets': [{'position': b.get_position(), 'direction': b.direction} for b in bullets if b.active]})
# 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=None):
"""Remove a client from the player list and notify others."""
if addr is None:
addr = client_addr_map.get(conn)
if addr in players:
print(f"Disconnected {players[addr]['name']} from {addr}")
del players[addr]
if conn in connections:
connections.remove(conn)
conn.close()
# Notify all clients about the disconnection
broadcast({'players': players, 'map_layout': current_map_layout, 'bullets': [{'position': b.get_position(), 'direction': b.direction} for b in bullets if b.active]})
if conn in client_conn_map:
del client_conn_map[conn]
if addr in player_conn_map:
del player_conn_map[addr]
# Server setup
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
print(f"Server started on {HOST}:{PORT}, waiting for connections...")
connections = []
client_addr_map = {}
client_conn_map = {} # Maps address to connection for easy lookup
player_conn_map = {} # Maps address to connection
current_map_layout = map_layouts[0]
# Start the map layout change thread
threading.Thread(target=change_map_layout_periodically, daemon=True).start()
while True:
conn, addr = server.accept()
print(f"Accepted connection from {addr}")
connections.append(conn)
client_addr_map[conn] = addr
player_conn_map[addr] = conn
threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()
Explanation of Changes in server.py:
-
Bullet Representation:
- A
Bullet class is introduced to encapsulate bullet properties, including position, direction, speed, owner, and active status.
-
Handling Shooting Events:
- When a client sends a
shoot action, the server creates a new Bullet instance with the provided position and direction.
- The bullet is added to the server's bullet list for tracking and updating.
-
Bullet Updates and Collision Detection:
- For each active bullet, the server updates its position based on its direction and speed.
- The server checks if the bullet collides with any player other than its owner. If a collision is detected:
- The server sends a
hit action to the hit player (you can expand this to reduce health, implement respawning, etc.).
- The bullet is deactivated and removed from the active bullets list.
- Bullets that move out of the game bounds are also deactivated and removed.
-
Broadcasting Bullet Data:
- The server continuously broadcasts updated player positions, map layouts, and bullet positions to all connected clients.
- This ensures that all clients have a consistent view of the game state.
-
Client Management Enhancements:
- Added mappings (
client_addr_map and player_conn_map) to efficiently handle connections and associate them with player addresses.
- Enhanced error handling to ensure that disconnected clients are properly removed from the game state.
-
Map Layout Synchronization:
- Updated the map layout change mechanism to include bullet data in the broadcast, ensuring that all clients are aware of active bullets even when the map changes.
Additional Notes:
-
Collision Handling: In this implementation, when a bullet hits a player, the server prints a message and sends a hit action to the player client. You can expand this to handle player health, death, and respawning as needed.
-
Bullet Lifetime: Bullets are automatically removed when they go out of bounds or collide with a player, ensuring efficient management of active bullets.
-
Security Considerations: For a production environment, consider implementing more robust security measures, such as validating client actions, handling malicious inputs, and securing data transmission.
Conclusion
With the above enhancements, your game now supports a basic shooting mechanism where players can fire bullets, and these bullets are managed and synchronized across all connected clients. This setup provides a foundation for further expansion, such as adding different weapon types, implementing bullet trajectories, adding player health systems, and more sophisticated collision responses.
Ensure that both game.py and server.py are updated accordingly and that you have the necessary assets (e.g., grass.png) in the specified directories. Additionally, install any required libraries if not already present using pip, for example:
pip install pygame
Feel free to further customize and expand upon this foundation to create a more engaging and feature-rich multiplayer 2D fighting game.