import pygame
import socket
import pickle
import threading
from pygame.locals import (
K_UP,
K_DOWN,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,
K_LEFT
)
class Rectangle:
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
id = 1
def __init__(self, screen, color, x, y, width, height):
self.screen = screen
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.velocity = 1
def create_rect(self):
pygame.draw.rect(self.screen, self.color,
(self.x, self.y, self.width, self.height))
def move(self):
pressed_keys = pygame.key.get_pressed()
if pressed_keys[K_UP]:
self.y -= self.velocity
self.y = max(self.y, 0)
if pressed_keys[K_DOWN]:
self.y += self.velocity
self.y = min(self.y, self.SCREEN_HEIGHT - self.height)
if pressed_keys[K_LEFT]:
self.x -= self.velocity
self.x = max(self.x, 0)
if pressed_keys[K_RIGHT]:
self.x += self.velocity
self.x = min(self.x, self.SCREEN_WIDTH - self.width)
def serialize(self):
return {
'id' : self.id,
'color' : self.color,
'x' : self.x,
'y' : self.y,
'width' : self.width,
'height' : self.height,
}
def deserialize(self, data):
self.id = data['id']
self.color = data['color']
self.x = data['x']
self.y = data['y']
self.width = data['width']
self.height = data['height']
def recv_data(client, screen, player):
while True:
try:
data = client.recv(2048)
if data != None:
print(data)
n_r_data = pickle.loads(data)
client_id = n_r_data['id']
if client_id != player.id:
#check if player is in list or not
existing_player = next((p for p in other_players if p.id == client_id), None)
if existing_player:
existing_player.deserialize(n_r_data)
else:
#create a new player
new_player = Rectangle(screen, n_r_data['color'],
n_r_data['x'],n_r_data['y'], n_r_data['width'],
n_r_data['height'], client_id)
other_players.append(new_player)
except ConnectionAbortedError as e:
print(f"ConnectionAbortedError: {e}")
except Exception as e:
print(f"ERROR IN RECEIVING DATA FROM SERVER {e}")
client.close()
def run(screen, client, player):
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
client.close()
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
client.close()
running = False
screen.fill((0, 0, 0))
player.create_rect()
player.move()
try:
client_data = pickle.dumps(player.serialize())
client.send(client_data)
except Exception as e:
print(f"ERROR IN SENDING DATA TO SERVER {e}")
for p in other_players:
p.create_rect()
p.move()
pygame.display.flip()
clock.tick(60)
SERVER_IP = "127.0.0.1"
SERVER_PORT = 5050
pygame.init()
screen = pygame.display.set_mode([Rectangle.SCREEN_WIDTH, Rectangle.SCREEN_HEIGHT])
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER_IP, SERVER_PORT))
except Exception as e:
print(f'ERROR IN CONNECTING TO SERVER {e}')
client.close()
pygame.quit()
player = Rectangle(screen, 'red', 100, 100, 80, 80)
other_players = []
recv_thread = threading.Thread(target=recv_data,args=(client, screen, player))
recv_thread.start()
run(screen, client, player)
client.close()
pygame.quit()