Adding guns and a fully functional health system to your existing 2D multiplayer fighting game involves several steps. We'll extend both the client (game.py) and server (server.py) to handle shooting mechanics, bullet management, collision detection, health tracking, and displaying health bars.
Below are the complete updated codes for both game.py and server.py, along with explanations of the key additions and modifications.
Updated game.py
Key Additions and Modifications:
-
Player Health:
- Added health attribute to track each player's health.
- Displayed a health bar above each player.
-
Shooting Mechanics:
- Players can shoot bullets by pressing the FIRE key (
LEFT CTRL by default).
- Bullets are represented as small rectangles moving in the direction the player is facing.
- The client sends shooting actions to the server.
-
Bullet Management:
- Bullets are managed by the server to ensure authoritative game state.
- Clients receive bullet updates from the server and render them on the screen.
-
Health System:
- When a player's health reaches zero, they are considered "dead" and are removed from the game.
- Health is synchronized across all clients via the server.
Complete game.py Code:
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('2D Fight Game with Guns and Health System')
# Constants
tile_size = 72 # Tile size after scaling
GRAVITY = 1
JUMP_STRENGTH = 15
SPEED = 7 # Adjusted for better gameplay
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)
# 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)
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)
# Function to calculate angle between two points
def calculate_angle(start_pos, target_pos):
dx = target_pos[0] - start_pos[0]
dy = target_pos[1] - start_pos[1]
angle = math.atan2(dy, dx)
return angle
# 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_right = True # Direction the character is facing
# 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
character_velocity_x = 0
# 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({'action': 'join', '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, bullets, running
while running:
try:
data = receive_message(client)
players = data.get('players', {})
map_layout = data.get('map_layout', [])
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
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left mouse button to shoot
mouse_pos = pygame.mouse.get_pos()
angle = calculate_angle(character.center, mouse_pos)
send_data({'action': 'shoot', 'direction': angle})
# Get keys pressed
keys = pygame.key.get_pressed()
# Handle horizontal movement
if keys[pygame.K_LEFT]:
character_velocity_x = -SPEED
facing_right = False
elif keys[pygame.K_RIGHT]:
character_velocity_x = SPEED
facing_right = True
else:
character_velocity_x *= FRICTION # Apply friction when no key is pressed
if abs(character_velocity_x) < 0.1:
character_velocity_x = 0
# 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
# 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
# Send character position to server
try:
send_data({'action': 'move', 'position': (character.x, character.y), 'facing_right': facing_right})
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']
health = info.get('health', 100)
player_rect = pygame.Rect(pos[0], pos[1], 50, 50)
pygame.draw.rect(screen, color, player_rect)
# Draw health bar
health_bar_width = 50
health_bar_height = 5
health_ratio = max(health, 0) / 100
pygame.draw.rect(screen, RED, (player_rect.x, player_rect.y - 10, health_bar_width, health_bar_height))
pygame.draw.rect(screen, GREEN, (player_rect.x, player_rect.y - 10, health_bar_width * health_ratio, health_bar_height))
# Draw player name
font = pygame.font.Font(None, 24)
text_surface = font.render(info['name'], True, BLACK)
screen.blit(text_surface, (player_rect.x, player_rect.y - 30)) # Display name above player
# Draw all bullets
for bullet in bullets:
bullet_rect = pygame.Rect(bullet['position'][0], bullet['position'][1], 10, 4)
pygame.draw.rect(screen, BLACK, bullet_rect)
# Update the display
pygame.display.flip()
# Cap the frame rate
clock.tick(60)
# Clean up
client.close()
pygame.quit()
Updated server.py
Key Additions and Modifications:
-
Player Health Management:
- Each player has a
health attribute initialized to 100.
- When a player is hit by a bullet, their health decreases by a specified amount.
- If a player's health reaches zero, they are removed from the game.
-
Bullet Management:
- Server manages all bullets, including their positions, directions, speeds, and lifetimes.
- Bullets are updated every server tick, moving them in their respective directions.
- Collision detection between bullets and players is handled on the server.
-
Client Actions Handling:
- Clients can send different types of actions such as
join, move, shoot.
- Server processes these actions accordingly.
-
Synchronization:
- Server broadcasts updated game states, including player positions, health, and bullets, to all connected clients.
Complete server.py Code:
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, colors, and health
players = {} # Key: addr, Value: {'name': str, 'position': (x, y), 'color': (r, g, b), 'health': int, 'facing_right': bool}
# Store bullets
bullets = [] # Each bullet: {'position': [x, y], 'direction': float, 'speed': float, 'owner': addr}
# Tile size
tile_size = 72
# 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
[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 layer)
],
# Additional predefined 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], # 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 layer)
]
]
# 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, addr=None)
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}")
raise
# 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 action must be 'join'")
player_name = initial_data.get('name', 'Unknown')
spawn_position = get_random_spawn_position()
player_color = generate_color()
players[addr] = {
'name': player_name,
'position': spawn_position,
'color': player_color,
'health': 100,
'facing_right': True
}
send_data(conn, {
'players': players,
'map_layout': current_map_layout,
'bullets': bullets
})
broadcast({'players': players, 'map_layout': current_map_layout, 'bullets': bullets}, exclude=None)
while True:
data = receive_message(conn)
action = data.get('action')
if action == 'move':
position = data.get('position')
facing_right = data.get('facing_right', True)
if position:
players[addr]['position'] = position
players[addr]['facing_right'] = facing_right
elif action == 'shoot':
direction = data.get('direction')
if direction is not None:
create_bullet(addr, direction)
elif action == 'join':
# Handle re-joining if necessary
pass
# After handling actions, send updates
send_game_state()
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 excluded one."""
for player_conn in connections.copy():
if player_conn != exclude:
try:
send_data(player_conn, data)
except Exception as e:
print(f"Error broadcasting data: {e}")
disconnect_client(player_conn, addr=None)
def send_game_state():
"""Broadcast the current game state to all clients."""
data = {
'players': players,
'map_layout': current_map_layout,
'bullets': bullets
}
broadcast(data, exclude=None)
def get_random_spawn_position():
x = random.randint(0, len(current_map_layout[0]) - 1) * tile_size
y = 0
for row in range(len(current_map_layout)):
if current_map_layout[row][x // tile_size] == 1 or current_map_layout[row][x // tile_size] == 2:
y = row * tile_size - tile_size
break
return x, y
def generate_color():
return (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))
def create_bullet(owner, direction):
bullet_speed = 10 # Adjust bullet speed as needed
bullet_position = list(players[owner]['position'])
# Start bullet from the center of the player
bullet_position[0] += 25 # Half of player width
bullet_position[1] += 25 # Half of player height
bullet = {
'position': bullet_position,
'direction': direction,
'speed': bullet_speed,
'owner': owner
}
bullets.append(bullet)
def update_bullets():
"""Update bullet positions and handle collisions."""
global bullets
new_bullets = []
for bullet in bullets:
dx = math.cos(bullet['direction']) * bullet['speed']
dy = math.sin(bullet['direction']) * bullet['speed']
bullet['position'][0] += dx
bullet['position'][1] += dy
# Remove bullets that are out of bounds
if (bullet['position'][0] < 0 or bullet['position'][0] > len(current_map_layout[0]) * tile_size or
bullet['position'][1] < 0 or bullet['position'][1] > len(current_map_layout) * tile_size):
continue
# Check collision with players
for addr, info in players.items():
if addr != bullet['owner']:
player_rect = pygame.Rect(info['position'][0], info['position'][1], 50, 50)
bullet_rect = pygame.Rect(bullet['position'][0], bullet['position'][1], 10, 4)
if player_rect.colliderect(bullet_rect):
players[addr]['health'] -= 10 # Damage per hit
print(f"{info['name']} was hit! Health: {players[addr]['health']}")
if players[addr]['health'] <= 0:
print(f"{info['name']} has been eliminated!")
remove_player(addr)
break
else:
# If no collision, keep the bullet
new_bullets.append(bullet)
bullets = new_bullets
def remove_player(addr):
"""Remove a player from the game."""
if addr in players:
del players[addr]
# Notify all clients about the updated players
send_game_state()
def change_map_layout_periodically():
"""Change the map layout every 300 seconds (5 minutes)."""
global current_map_layout
map_index = 0
while True:
time.sleep(300)
current_map_layout = map_layouts[map_index]
map_index = (map_index + 1) % len(map_layouts)
print("Map layout changed.")
send_game_state()
def game_loop():
"""Main game loop for updating game state."""
while True:
update_bullets()
send_game_state()
time.sleep(0.05) # 20 updates per second
# Connection handling
def close_connection(conn, addr):
"""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 {addr}")
if addr in players:
del players[addr]
close_connection(conn, addr)
send_game_state()
# 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 = []
current_map_layout = map_layouts[0]
# Start the map layout change thread
threading.Thread(target=change_map_layout_periodically, daemon=True).start()
# Start the game state update loop
threading.Thread(target=game_loop, 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
1. Shooting Mechanics:
-
Client Side (game.py):
- When the player clicks the left mouse button, a shooting action is sent to the server with the direction based on the mouse position.
- Bullets are rendered on the client based on the data received from the server.
-
Server Side (server.py):
- The server listens for
shoot actions from clients.
- Upon receiving a shoot action, the server creates a bullet with a starting position, direction, and speed.
- The server updates bullet positions in the game loop and handles collisions with players.
- If a bullet hits a player, the player's health is decreased.
2. Health System:
-
Player Health:
- Each player has a
health attribute initialized to 100.
- Health is decreased by 10 each time a player is hit by a bullet.
- If a player's health reaches zero, they are removed from the game.
-
Displaying Health:
- On the client side, a health bar is displayed above each player.
- The health bar changes color based on the remaining health (green to red).
3. Bullet Management:
-
Server Side:
- The server manages all bullets, updating their positions based on their speed and direction.
- Bullets are removed if they go out of bounds or collide with a player.
- The server ensures that bullets are synchronized across all clients.
-
Client Side:
- Clients render bullets based on the data received from the server.
- Bullets appear as small black rectangles moving in the direction they were fired.
4. Synchronization and Security:
- The server is authoritative, meaning all game logic (player positions, bullet movements, health) is handled on the server to prevent cheating.
- Clients send actions (like moving or shooting) to the server, and the server broadcasts the updated game state to all clients.
5. Additional Enhancements:
-
Player Direction:
- Players have a
facing_right attribute to determine the direction they are facing, which affects the shooting direction.
-
Threading:
- The server uses separate threads for handling each client and updating the game state concurrently.
Running the Updated Game
-
Install Required Libraries:
- Ensure you have Pygame installed. If not, install it using:
pip install pygame
-
Server Setup:
- Run the
server.py script on your server machine or locally.
python server.py
- Ensure that the server's IP and port (
HOST and PORT variables) are correctly set and accessible to clients.
-
Client Setup:
- Ensure that the
tile_images paths in game.py point to valid image files (e.g., grass.png).
- Run the
game.py script on client machines.
python game.py
- Enter the player name and server IP when prompted.
-
Gameplay:
- Movement: Use
LEFT and RIGHT arrow keys to move, and SPACE or UP/W to jump.
- Shooting: Click the left mouse button to shoot in the direction of the mouse pointer.
- Health: Each player starts with 100 health. Getting hit by bullets decreases health by 10. When health reaches zero, the player is eliminated.
Conclusion
The above modifications introduce essential features for a more engaging multiplayer experience, including shooting and health management. These additions enhance gameplay by allowing players to engage in combat, track their health, and witness the impact of their actions in real-time.
Feel free to further customize and expand upon these features, such as adding different weapon types, implementing respawn mechanics, or introducing power-ups to enrich the game dynamics.
Happy coding and gaming!