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
Function to check and handle general collision with tiles
def handle_tile_collisions(rect):
global character_velocity_y, character_velocity_x, is_jumping
code
# 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
Main game loop (unchanged)
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()
def receive_data():
global players, map_layout, running
while running:
try:
data = receive_message(client)
players = data.get('players', {})
map_layout = data.get('map_layout', [])
except Exception as e:
print(f"Disconnected from server: {e}")
running = False
break
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
code
# 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 > 1280:
character.right = 1280
if character.top < 0:
character.top = 0
if character.bottom > 720:
character.bottom = 720
# 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({'name': player_name, '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
# Update the display
pygame.display.flip()
# Cap the frame rate
pygame.time.Clock().tick(60)
pygame.quit()
server.py
import random
import socket
import threading
import pickle
import struct
import time
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")
code
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
send_data(conn, {'players': players, 'map_layout': current_map_layout})
while True:
data = receive_message(conn)
if not data:
break
players[addr]['position'] = data['position']
# Update all clients
broadcast({'players': players, 'map_layout': current_map_layout}, exclude=conn)
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 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})
Server setup
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
print("Server started, waiting for connections...")
Adding guns to your 2D fighting game involves implementing shooting mechanics, handling projectiles (bullets), and ensuring proper synchronization between the server and clients. Below is the complete updated code for both game.py and server.py with guns functionality integrated.
Overview of Changes
Player Facing Direction: Added logic to track and send the player's facing direction (left or right) to the server.
Shooting Mechanics:
Client Side:
Added a shooting key (F key) to fire bullets.
Defined a Bullet class to represent projectiles.
Sent shoot commands to the server when the player fires.
Rendered incoming bullets from all players.
Server Side:
Managed a list of active bullets.
Updated bullet positions and handled collisions with players and tiles.
Broadcasted bullet information to all clients.
Updated game.py
python
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 = pygame.display.set_mode((1280, 720))
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)
BULLET_SPEED = 15
BULLET_SIZE = 10
# Input boxes
player_name_input_box = pygame.Rect(400, 200, 400, 50)
server_ip_input_box = pygame.Rect(400, 300, 400, 50)
# Text variables
player_name = 'Player'
server_ip = 'localhost'
input_active = None
# Connecting flag
connecting = False
# Function to display text
def draw_text(text, font, color, surface, x, y):
textobj = font.render(text, True, color)
textrect = textobj.get_rect(center=(x, y))
surface.blit(textobj, textrect)
# Connecting screen
def show_connecting_screen():
screen.fill(BLUE)
draw_text("Connecting...", FONT, BLACK, screen, 640, 360)
pygame.display.flip()
# Function to handle user input for name and server IP in Pygame
def get_user_input_pygame():
global player_name, server_ip, input_active, connecting
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if player_name_input_box.collidepoint(event.pos):
input_active = 'name'
elif server_ip_input_box.collidepoint(event.pos):
input_active = 'server_ip'
else:
input_active = None
if event.type == pygame.KEYDOWN:
if input_active == 'name':
if event.key == pygame.K_RETURN:
input_active = 'server_ip'
elif event.key == pygame.K_BACKSPACE:
player_name = player_name[:-1]
else:
player_name += event.unicode
elif input_active == 'server_ip':
if event.key == pygame.K_RETURN:
connecting = True
show_connecting_screen()
return player_name, server_ip
elif event.key == pygame.K_BACKSPACE:
server_ip = server_ip[:-1]
else:
server_ip += event.unicode
screen.fill(BLUE)
draw_text("Enter Player Name:", FONT, BLACK, screen, 640, 160)
draw_text("Enter Server IP:", FONT, BLACK, screen, 640, 260)
pygame.draw.rect(screen, WHITE, player_name_input_box, 2)
pygame.draw.rect(screen, WHITE, server_ip_input_box, 2)
draw_text(player_name, SMALL_FONT, BLACK, screen, 640, 225)
draw_text(server_ip, SMALL_FONT, BLACK, screen, 640, 325)
pygame.display.flip()
# Bullet class
class Bullet:
def __init__(self, owner, x, y, direction):
self.owner = owner
self.x = x
self.y = y
self.direction = direction # -1 for left, 1 for right
self.rect = pygame.Rect(self.x, self.y, BULLET_SIZE, BULLET_SIZE)
def update(self):
self.x += BULLET_SPEED * self.direction
self.rect.x = self.x
def to_dict(self):
return {
'owner': self.owner,
'x': self.x,
'y': self.y,
'direction': self.direction
}
# 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
facing_direction = 1 # 1: right, -1: left
# 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 process incoming bullets from server
def process_bullets(server_bullets):
global bullets
bullets.clear()
for b in server_bullets:
bullet = Bullet(b['owner'], b['x'], b['y'], b['direction'])
bullets.append(bullet)
# 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, running, bullets
while running:
try:
data = receive_message(client)
players = data.get('players', {})
map_layout = data.get('map_layout', [])
server_bullets = data.get('bullets', [])
process_bullets(server_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
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_f: # Shooting key
# Create a bullet shoot action
shoot_data = {
'action': 'shoot',
'direction': facing_direction,
'position': (character.centerx, character.centery)
}
send_data(shoot_data)
# Get keys pressed
keys = pygame.key.get_pressed()
# Handle horizontal movement
if keys[pygame.K_LEFT]:
character_velocity_x = -SPEED
facing_direction = -1
elif keys[pygame.K_RIGHT]:
character_velocity_x = SPEED
facing_direction = 1
else:
character_velocity_x *= FRICTION # Apply friction when no key is pressed
# Handle jumping
if (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 > 1280:
character.right = 1280
if character.top < 0:
character.top = 0
if character.bottom > 720:
character.bottom = 720
# 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 and facing direction to server
try:
send_data({'action': 'update', 'name': player_name, 'position': (character.x, character.y), 'facing': facing_direction})
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']
facing = info.get('facing', 1)
player_rect = pygame.Rect(pos[0], pos[1], 50, 50)
pygame.draw.rect(screen, color, player_rect)
# Optionally, draw direction indicator
eye_radius = 5
eye_x = pos[0] + 10 if facing == 1 else pos[0] + 40
pygame.draw.circle(screen, BLACK, (eye_x, pos[1] + 10), eye_radius)
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
for bullet in bullets:
pygame.draw.circle(screen, BULLET_COLOR, (int(bullet.x), int(bullet.y)), BULLET_SIZE // 2)
# Update the display
pygame.display.flip()
# Cap the frame rate
pygame.time.Clock().tick(60)
pygame.quit()
Updated server.py
python
Explanation of the Changes
1. Player Facing Direction
Client (game.py):
Introduced a facing_direction variable to track whether the player is facing left (-1) or right (1).
Updated facing_direction based on movement keys (LEFT or RIGHT).
Server (server.py):
Stores each player's facing direction.
Updates and broadcasts the facing direction along with the player's position.
2. Shooting Mechanics
Client (game.py):
Shooting Key: The F key (pygame.K_f) is assigned to fire bullets.
Bullet Class: Defined a Bullet class to manage bullet properties and rendering.
Sending Shoot Action: When the F key is pressed, the client sends a shoot action to the server with the direction and position.
Rendering Bullets: The client receives bullet data from the server and renders all active bullets.
Server (server.py):
Bullet Management:
Maintains a bullets list to track all active bullets.
Each bullet has an id, owner, x, y, and direction.
The create_bullet function adds new bullets to the list when a client fires.
Bullet Updates:
A separate thread (update_bullets) updates the position of each bullet based on its direction.
Handles bullet collisions with tiles and players.
Removes bullets that collide or go off-screen.
Broadcasting Bullets: Sends the updated bullets list to all clients after each update.
3. Networking Protocol Adjustments
Actions:
Introduced different actions (join, update, shoot) to handle various client requests.
The server responds accordingly based on the action type.
Data Serialization:
Utilized pickle for data serialization, ensuring that complex data structures like bullets are correctly transmitted.
4. Collision Handling
Server (server.py):
Bullet collision with tiles and players is handled server-side to ensure authoritative game state.
When a bullet collides with a player, it is removed from the active bullets list, and you can implement additional logic like health reduction.
5. Threading
Server (server.py):
Added a separate thread for updating bullets (update_bullets) to handle their movement and collision independently of client interactions.
6. Game Rendering
Client (game.py):
Bullets are rendered as red circles (BULLET_COLOR).
The position of bullets is updated based on the server's authoritative state.
Installation Instructions
Install Required Libraries:
Ensure you have Python installed. Install the necessary libraries using pip:
bash
pip install pygame websocket-client
Organize Assets:
Ensure that the grass.png image is placed in an assets directory relative to both game.py and server.py.
Run the Server:
Start the server by running server.py:
bash
python server.py
Run the Client(s):
Start one or more clients by running game.py:
bash
python game.py
Enter the player name and the server IP when prompted.
Use the arrow keys (LEFT, RIGHT, UP) or W for movement.
Press the F key to shoot bullets.
Notes and Future Improvements
Health and Damage System:
Currently, bullets remove themselves upon collision but do not affect player health.
Implement a health system where players have a health bar that decreases when hit by bullets.
Bullet Types and Reloading:
Introduce different bullet types (e.g., different speeds or damage).
Implement a reloading mechanism or limited ammunition to balance gameplay.
Advanced Collision Detection:
Improve collision detection for more precise interactions between bullets and players or tiles.
Visual Enhancements:
Add animations for shooting, bullet trails, and player actions.
Implement better graphics for players and bullets.
Security Enhancements:
Currently, the server trusts client inputs. Implement validation to prevent cheating (e.g., unauthorized bullet creation).
Networking Protocol:
Consider using more efficient serialization methods or protocols (e.g., JSON, Protocol Buffers) for better performance and security.
Scaling and Performance:
Optimize server performance to handle more clients and bullets simultaneously.
Implement rate limiting to prevent spamming of shoot actions.
By following the above implementation, you now have a foundational shooting mechanic integrated into your 2D fighting game. You can further expand upon this by enhancing game mechanics, improving visuals, and optimizing performance.