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
]
]
To implement a bullet limit system and introduce a firing delay (cooldown) to prevent continuous firing in your multiplayer Pygame-based 2D fighting game, you'll need to make modifications to both the client (game.py) and the server (server.py). Below, I'll guide you through the necessary changes step-by-step.
Overview
-
Bullet Limit System: Restrict the number of bullets a player can have on the screen at any given time (e.g., maximum of 5 bullets).
-
Firing Delay (Cooldown): Introduce a cooldown period between consecutive shots (e.g., 500 milliseconds) to prevent players from spamming bullets.
Both features will enhance gameplay balance and prevent potential network flooding from excessive bullet firing.
Modifications in game.py (Client)
1. Add Necessary Variables
a. Define Bullet Limit and Cooldown Constants
At the beginning of your game.py, define constants for the bullet limit and cooldown duration.
# Constants
BULLET_LIMIT = 5 # Maximum number of bullets allowed on screen
FIRE_COOLDOWN = 500 # Cooldown duration in milliseconds
b. Initialize Tracking Variables
Add variables to track the number of active bullets and the last fire time.
# Initialize bullet tracking
last_fire_time = 0
2. Modify the Shooting Logic
Update the shooting mechanism to enforce the bullet limit and cooldown.
a. Update the Shooting Condition
Replace the existing shooting logic inside the main game loop with the following:
# Handle shooting with bullet limit and cooldown
current_time = pygame.time.get_ticks()
if keys[pygame.K_f]:
if len(bullets) < BULLET_LIMIT and (current_time - last_fire_time) > FIRE_COOLDOWN:
# 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
))
last_fire_time = current_time # Update the last fire time
Explanation:
- Bullet Limit:
len(bullets) < BULLET_LIMIT ensures that the player cannot fire more than the allowed number of bullets.
- Cooldown Check:
(current_time - last_fire_time) > FIRE_COOLDOWN ensures that enough time has passed since the last shot.
b. Prevent Continuous Firing
To prevent the player from holding down the fire button and continuously firing, you can modify the event handling to detect key presses instead of key holds.
Replace This:
if keys[pygame.K_f]:
# Shooting logic
With This:
for event in pygame.event.get():
# ... existing event handling ...
# Handle shooting on key press
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_f:
current_time = pygame.time.get_ticks()
if len(bullets) < BULLET_LIMIT and (current_time - last_fire_time) > FIRE_COOLDOWN:
# 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
))
last_fire_time = current_time # Update the last fire time
Note: This change ensures that bullets are fired only on discrete key presses, preventing rapid-fire when the key is held down.
3. Update Bullet Management
Ensure that bullets are properly removed when they go off-screen or hit a target to maintain the bullet limit.
Current Bullet Removal Logic:
for bullet in bullets[:]:
bullet.move()
# Remove bullets that are off-screen
if bullet.x < 0 or bullet.x > 1280:
bullets.remove(bullet)
Enhancement: Ensure that bullets hitting targets are also removed, which seems to be handled on the server side. Ensure synchronization between client and server bullet states.
4. Limit Bullets Sent to Server
When sending bullet data to the server, ensure that only active bullets within the limit are sent.
Existing Send Data Code:
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
Ensure that bullets list adheres to the BULLET_LIMIT, which is already enforced in the shooting logic.
5. Provide Visual Feedback (Optional)
To enhance user experience, you can display the remaining bullets or cooldown status on the screen.
Example:
# Display remaining bullets
draw_text(f"Bullets: {BULLET_LIMIT - len(bullets)}", SMALL_FONT, WHITE, screen, 100, 50)
# Display cooldown (optional)
time_since_last_fire = current_time - last_fire_time
if time_since_last_fire < FIRE_COOLDOWN:
cooldown_remaining = FIRE_COOLDOWN - time_since_last_fire
draw_text(f"Cooldown: {cooldown_remaining}ms", SMALL_FONT, WHITE, screen, 100, 80)
Modifications in server.py (Server)
1. Enforce Bullet Limits and Cooldown on Server Side
While the client enforces bullet limits and cooldowns, it's crucial to validate these constraints on the server to prevent cheating.
a. Update Player Data Structure
Include timestamps for the last fired bullet to enforce cooldowns server-side.
# In the players dictionary initialization
players[addr] = {
'name': player_name,
'position': spawn_position,
'color': generate_color(),
'health': 100,
'bullets': [],
'last_fire_time': 0 # Add this line
}
b. Define Bullet Limit and Cooldown Constants on Server
Ensure consistency by defining the same bullet limit and cooldown.
# Constants (same as client)
BULLET_LIMIT = 5
FIRE_COOLDOWN = 500 # in milliseconds
BULLET_SPEED = 15
c. Update the handle_client Function
Modify the handle_client function to enforce bullet limits and cooldowns.
import time
# ... existing imports and code ...
def 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': [],
'last_fire_time': 0 # Initialize last fire time
}
# 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
current_time = int(time.time() * 1000) # Current time in milliseconds
# Enforce cooldown
last_fire_time = players[addr].get('last_fire_time', 0)
incoming_bullets = data.get('bullets', [])
valid_bullets = []
for b in incoming_bullets:
if (current_time - last_fire_time) > FIRE_COOLDOWN and len(players[addr]['bullets']) < BULLET_LIMIT:
bullet = {
'owner': addr,
'x': b['x'],
'y': b['y'],
'direction': b['direction']
}
players[addr]['bullets'].append(bullet)
valid_bullets.append(bullet)
players[addr]['last_fire_time'] = current_time # Update last fire time
else:
print(f"Player {players[addr]['name']} attempted to fire too quickly or exceed bullet limit.")
# Update player position
players[addr]['position'] = data['position']
# 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'] * BULLET_SPEED
# 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)
Explanation:
-
Timestamp Tracking: The server tracks last_fire_time for each player to enforce the cooldown.
-
Bullet Limit Enforcement: Before adding a new bullet, the server checks if the player has not exceeded the BULLET_LIMIT.
-
Valid Bullets: Only bullets that pass both the cooldown and limit checks are added to the server's bullet list.
-
Logging Attempts to Cheat: If a player tries to fire bullets too quickly or exceed the limit, the server logs the attempt.
2. Modify Broadcasted Bullet Data
Ensure that the server correctly sends the current state of bullets to all clients.
Existing Bullet Broadcasting:
broadcast({'players': players, 'map_layout': current_map_layout}, exclude=None)
Ensure Bullets Are Properly Serialized:
If necessary, adjust the broadcasting to include all relevant bullet data. However, the existing structure seems sufficient as long as bullets are part of the players dictionary.
3. Optional: Implement Server-Side Bullet Management
For more robust server-side control, you might consider handling bullet movement and collisions entirely on the server. This approach minimizes client-side trust and potential cheating.
However, given the current architecture where the client manages bullet movement and sends updates to the server, the above changes primarily enforce limits and cooldowns, which should suffice for basic security.
Final Code Adjustments
Below are the consolidated changes to both game.py and server.py.
game.py (Client)
# ... [existing imports and initializations] ...
# 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 system constants
BULLET_LIMIT = 5 # Maximum number of bullets on screen
FIRE_COOLDOWN = 500 # Cooldown time in milliseconds
# 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
# Tracking variables
last_fire_time = 0
# ... [existing functions for drawing text, connecting screen, user input, networking] ...
# Start a thread to receive data from the server
running = True
threading.Thread(target=receive_data, daemon=True).start()
# Bullet class remains unchanged
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 = []
# Main game loop
while running:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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()
# After connecting screen, establish the connection and break input loop
# Normally, connection logic here
elif event.key == pygame.K_BACKSPACE:
server_ip = server_ip[:-1]
else:
server_ip += event.unicode
# Handle shooting on key press
if event.key == pygame.K_f:
if len(bullets) < BULLET_LIMIT and (current_time - last_fire_time) > FIRE_COOLDOWN:
# 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
))
last_fire_time = current_time # Update last fire time
if connecting:
# Connection logic (established earlier)
try:
client.connect((HOST, PORT))
# Send initial player data to the server
send_data({'name': player_name, 'position': (character.x, character.y)})
connecting = False # Reset connecting flag
except socket.error as e:
print(f"Unable to connect to the server: {e}")
sys.exit()
# Only handle game logic if not in user input phase
if not connecting:
# 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 key hold prevented
# (Moved to event handling)
# 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
server_bullets = []
for addr_key, info in players.items():
server_bullets.extend(info.get('bullets', []))
for b in server_bullets:
bullet_rect = pygame.Rect(b['x'], b['y'], 10, 5)
pygame.draw.rect(screen, RED, bullet_rect)
# Draw local bullets (optional if server manages all bullets)
for bullet in bullets:
bullet.draw(screen)
# Optional: Display bullet count and cooldown
draw_text(f"Bullets: {BULLET_LIMIT - len(bullets)}", SMALL_FONT, WHITE, screen, 100, 50)
time_since_last_fire = current_time - last_fire_time
if time_since_last_fire < FIRE_COOLDOWN:
cooldown_remaining = FIRE_COOLDOWN - time_since_last_fire
draw_text(f"Cooldown: {cooldown_remaining}ms", SMALL_FONT, WHITE, screen, 100, 80)
# Update the display
pygame.display.flip()
# Cap the frame rate
pygame.time.Clock().tick(60)
pygame.quit()
server.py (Server)
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
# Bullet system constants
BULLET_LIMIT = 5 # Maximum number of bullets per player
FIRE_COOLDOWN = 500 # Cooldown time in milliseconds
BULLET_SPEED = 15
# 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 = [
# ... [existing map layouts] ...
]
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', 'Unknown')
spawn_position = get_random_spawn_position()
players[addr] = {
'name': player_name,
'position': spawn_position,
'color': generate_color(),
'health': 100,
'bullets': [],
'last_fire_time': 0 # Initialize last fire time
}
# 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
current_time = int(time.time() * 1000) # Current time in milliseconds
# Update player position
players[addr]['position'] = data['position']
# Handle bullets from this player
incoming_bullets = data.get('bullets', [])
for b in incoming_bullets:
# Enforce cooldown and bullet limit
if (current_time - players[addr]['last_fire_time'] > FIRE_COOLDOWN) and (len(players[addr]['bullets']) < BULLET_LIMIT):
bullet = {
'owner': addr,
'x': b['x'],
'y': b['y'],
'direction': b['direction']
}
players[addr]['bullets'].append(bullet)
players[addr]['last_fire_time'] = current_time # Update last fire time
else:
print(f"Player {players[addr]['name']} attempted to fire too quickly or exceed bullet limit.")
# Update bullets positions and handle collisions
update_bullets()
# Remove bullets that have hit or are out of bounds
for player_addr in list(players.keys()):
bullets_to_remove = []
for bullet in players[player_addr]['bullets']:
# Move bullet
bullet['x'] += bullet['direction'] * BULLET_SPEED
# 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:
if bullet in players[player_addr]['bullets']:
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]) - 2)
y = len(current_map_layout) - 1 # Spawn at ground layer
return x * tile_size, y * tile_size - 50 # Adjust y to fit the player's height
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():
"""Currently handled in handle_client. Placeholder for additional logic."""
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()
Key Changes:
-
Player Data Structure: Added last_fire_time to track when the player last fired a bullet.
-
Bullet Limit & Cooldown Enforcement: Within the handle_client function, before adding incoming bullets, the server checks if the player hasn't exceeded the bullet limit and if the cooldown period has passed.
-
Logging Unauthorized Attempts: The server logs any attempts by players to bypass bullet limits or cooldowns.
-
Consistent Bullet Management: Both client and server manage bullets in a synchronized manner, ensuring gameplay consistency.
Testing the Implementation
After making these changes, it's essential to thoroughly test the game to ensure:
-
Players cannot fire more than the specified number of bullets (BULLET_LIMIT).
-
The firing cooldown (FIRE_COOLDOWN) effectively prevents rapid-fire or continuous shooting.
-
Bullets are correctly synchronized between clients and the server.
-
Proper visual feedback is provided to players about their remaining bullets and cooldown status.
Steps:
-
Run the Server:
python server.py
-
Run Multiple Clients:
python game.py
-
Test Shooting Mechanics:
- Attempt to fire bullets continuously by pressing and holding the fire key (
F).
- Observe that bullets are limited to the maximum allowed and that firing is restricted by the cooldown.
-
Verify Server Logs:
- Check the server console to ensure that any unauthorized firing attempts are logged.
-
Check Synchronization:
- Ensure that all clients see the correct number of bullets and that bullet positions are consistent.
Conclusion
By implementing a bullet limit system and a firing cooldown, you enhance the balance and fairness of your multiplayer game. The above modifications ensure that players cannot spam bullets, which helps maintain a smooth and enjoyable gameplay experience for all participants.
Feel free to adjust the BULLET_LIMIT and FIRE_COOLDOWN constants to best fit your game's design and desired difficulty level.
If you encounter any issues or have further questions, don't hesitate to ask!