Adding guns to your 2D fighting game involves implementing a shooting mechanic where players can fire projectiles (bullets) that move across the screen, interact with the environment, and potentially affect other players. This requires modifications to both the client (game.py) and the server (server.py) to handle the creation, synchronization, and rendering of bullets.
Below is the complete modified code for both game.py and server.py with the gun functionality integrated. The changes include:
-
Client Side (game.py):
- Shooting Mechanism:
- Players can shoot bullets by pressing the
F key (to shoot right) or the G key (to shoot left).
- When a shoot event is triggered, the client sends a
shoot event to the server with the direction of the shot.
- Bullet Rendering:
- The client receives bullet data from the server and renders them on the screen.
- Bullet Management:
- Bullets are managed in a list and updated each frame based on their velocity.
-
Server Side (server.py):
- Bullet Tracking:
- The server maintains a list of active bullets, each with a unique ID, position, velocity, and owner.
- Bullet Updates:
- A separate thread updates the positions of all active bullets, checks for collisions with tiles and players, and removes bullets that collide or move off-screen.
- Bullet Synchronization:
- The server broadcasts the updated bullets list to all connected clients to ensure synchronization.
game.py (Client Side)
import time
import pygame
import socket
import pickle
import threading
import struct
import sys
import websocket # Make sure to install the websocket-client library
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('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)
BULLET_COLOR = (255, 0, 0) # Red bullets
BULLET_SPEED = 15
BULLET_SIZE = 5
# 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, 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)
try:
client.sendall(struct.pack('>I', length) + serialized_data)
except socket.error as e:
print(f"Failed to send data to server: {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 = []
bullets = []
# 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:
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()
# Bullet Management
bullets = []
bullets_lock = threading.Lock()
def receive_data():
global players, map_layout, bullets, running
while running:
try:
data = receive_message(client)
players = data.get('players', {})
map_layout = data.get('map_layout', [])
with bullets_lock:
bullets = 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
running = True
threading.Thread(target=receive_data, daemon=True).start()
# Main game loop
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle shooting input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_f:
# Shoot to the right
send_data({'shoot': {'direction': 'right'}})
if event.key == pygame.K_g:
# Shoot to the left
send_data({'shoot': {'direction': 'left'}})
# 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
# 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
# Check for collisions with other players
for addr, info in players.items():
if addr != (client.getsockname()[0], client.getsockname()[1]):
other_rect = pygame.Rect(info['position'][0], info['position'][1], 50, 50)
if character.colliderect(other_rect):
# Simple collision response
if keys[pygame.K_LEFT]:
character.x += SPEED
if keys[pygame.K_RIGHT]:
character.x -= SPEED
if keys[pygame.K_UP]:
character.y += SPEED
if keys[pygame.K_DOWN]:
character.y -= SPEED
# Send character position to server
try:
send_data({'position': (character.x, character.y)})
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['color']
pygame.draw.rect(screen, color, (pos[0], pos[1], 50, 50))
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 all bullets
with bullets_lock:
for bullet in bullets:
bullet_pos = bullet['position']
direction = bullet['direction']
pygame.draw.circle(screen, BULLET_COLOR, (int(bullet_pos[0]), int(bullet_pos[1])), BULLET_SIZE)
# Update the display
pygame.display.flip()
# Cap the frame rate
pygame.time.Clock().tick(60)
pygame.quit()
client.close()
server.py (Server Side)
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 and colors
players = {}
# Store active connections
connections = []
# Bullet management
bullets = []
bullets_lock = threading.Lock()
last_bullet_id = 0
# Tile size
tile_size = 72 # Match client tile size
# 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
]
]
# Initialize current map layout
current_map_layout = map_layouts[0]
map_lock = threading.Lock()
# 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
# Core game functions
def handle_client(conn, addr):
global last_bullet_id
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()}
send_data(conn, {'players': players, 'map_layout': current_map_layout, 'bullets': bullets})
while True:
data = receive_message(conn)
if not data:
break
# Update player position
if 'position' in data:
players[addr]['position'] = data['position']
# Handle shooting
if 'shoot' in data:
direction = data['shoot'].get('direction', 'right')
with bullets_lock:
bullet_id = last_bullet_id
last_bullet_id += 1
owner_pos = players[addr]['position']
if direction == 'right':
velocity = BULLET_SPEED = 15
else:
velocity = -15
bullet = {
'id': bullet_id,
'position': [owner_pos[0] + 25, owner_pos[1] + 25], # Center of the player
'velocity': velocity,
'owner': addr,
'direction': direction
}
bullets.append(bullet)
# Update all clients with the latest state
broadcast({'players': players, 'map_layout': current_map_layout, 'bullets': bullets}, 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)
with map_lock:
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, 'bullets': bullets})
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, 'bullets': bullets})
def update_bullets():
"""Update bullet positions, handle collisions, and remove bullets as necessary."""
global bullets
while True:
time.sleep(1/60) # 60 updates per second
with bullets_lock:
bullets_to_remove = []
for bullet in bullets:
# Update bullet position
bullet['position'][0] += bullet['velocity']
# Check if bullet is off-screen
if bullet['position'][0] < 0 or bullet['position'][0] > SCREEN_WIDTH:
bullets_to_remove.append(bullet)
continue
# Check collision with map tiles
bullet_rect = pygame.Rect(bullet['position'][0], bullet['position'][1], BULLET_SIZE, BULLET_SIZE)
collided = False
for y, row in enumerate(current_map_layout):
for x, tile_id in enumerate(row):
if tile_id == 1: # Solid tile
tile_rect = pygame.Rect(x * tile_size, y * tile_size, tile_size, tile_size)
if bullet_rect.colliderect(tile_rect):
bullets_to_remove.append(bullet)
collided = True
break
if collided:
break
if collided:
continue
# Check collision with players
for player_addr, info in players.items():
if player_addr == bullet['owner']:
continue # Don't collide with the owner
player_rect = pygame.Rect(info['position'][0], info['position'][1], 50, 50)
if bullet_rect.colliderect(player_rect):
print(f"Player {players[bullet['owner']]['name']} hit player {info['name']}!")
# Implement damage or other effects here
bullets_to_remove.append(bullet)
break
# Remove bullets that collided or went off-screen
for bullet in bullets_to_remove:
if bullet in bullets:
bullets.remove(bullet)
# Broadcast updated bullets to all clients
if bullets_to_remove:
broadcast({'players': players, 'map_layout': current_map_layout, 'bullets': bullets})
# 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...")
# Start the map layout change thread
threading.Thread(target=change_map_layout_periodically, daemon=True).start()
# Start the bullet update thread
threading.Thread(target=update_bullets, 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 the Changes
-
Client (game.py):
- Shooting Input:
- Added event handling for
KEYDOWN events where pressing F shoots to the right and pressing G shoots to the left.
- When a shoot event is detected, the client sends a
shoot event to the server with the direction.
- Bullet Rendering:
- Added a
bullets list to store incoming bullet data from the server.
- Rendered bullets as red circles at their respective positions.
- Bullet Synchronization:
- Modified the
receive_data function to also receive and store bullet data from the server.
-
Server (server.py):
- Bullet Tracking:
- Introduced a
bullets list to keep track of all active bullets.
- Each bullet has an
id, position, velocity, owner, and direction.
- Shooting Handling:
- Updated the
handle_client function to process shoot events from clients. When a shoot event is received, a new bullet is created and added to the bullets list.
- Bullet Updates:
- Created an
update_bullets thread that continuously updates the position of each bullet based on its velocity.
- Checks for collisions with solid tiles and other players. If a collision is detected, the bullet is removed, and appropriate actions (like damage) can be implemented.
- Removes bullets that have gone off-screen to prevent memory leaks.
- Bullet Synchronization:
- Ensures that all clients are updated with the latest bullet positions by broadcasting the updated
bullets list after each update.
- Thread Safety:
- Used a
bullets_lock to ensure that the bullets list is accessed safely across multiple threads.
-
General Enhancements:
Notes and Recommendations
-
Assets: Ensure that the ./assets/grass.png image exists and is properly scaled. You might need to adjust the path or add additional assets as needed.
-
Bullet Collision Detection: The current implementation prints a message when a player is hit. To make it functional, you should implement a health system where players can take damage or be eliminated when hit by bullets.
-
Performance Considerations: For larger numbers of bullets or players, optimize the collision detection logic to prevent performance bottlenecks.
-
Security: Since this is a networked game, consider implementing security measures to prevent cheating, such as validating client inputs on the server.
-
Testing: Thoroughly test the shooting mechanic with multiple clients to ensure synchronization and collision detection work as expected.
By following the above modifications, your game will now support shooting mechanics, allowing players to fire bullets, interact with the environment, and engage in combat more dynamically.