I'm trying to write a simple game but every time I start it, Pygame crashes.
Here's the client code:
import socket, pygame, sys
port = 5000
host_server = "localhost"
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host_server, port))
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')
WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png')
dogImg = pygame.image.load('dog.png')
catx = 0
caty = 0
dogx = 0
dogy = 0
while True:
tasto = pygame.key.get_pressed()
DISPLAYSURF.fill(WHITE)
dogx = client_socket.recv(1024)
client_socket.send(str(catx))
if tasto[K_RIGHT]:
catx += 5
elif tasto[K_DOWN]:
caty += 5
elif tasto[K_LEFT]:
catx -= 5
elif tasto[K_UP]:
caty -= 5
DISPLAYSURF.blit(catImg, (catx, caty))
DISPLAYSURF.blit(dogImg, (dogx, dogy))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
And here's the server code:
import pygame, sys, socket
from pygame.locals import *
host = "localhost"
port = 5000
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')
WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png')
dogImg = pygame.image.load('dog.png')
catx = 0
caty = 0
dogx = 0
dogy = 0
while True:
client_socket, address = server_socket.accept()
tasto = pygame.key.get_pressed()
DISPLAYSURF.fill(WHITE)
dogx = client_socket.recv(1024)
client_socket.send(catx)
if tasto[K_RIGHT]:
catx += 5
elif tasto[K_DOWN]:
caty += 5
elif tasto[K_LEFT]:
catx -= 5
elif tasto[K_UP]:
caty -= 5
DISPLAYSURF.blit(catImg, (catx, caty))
DISPLAYSURF.blit(dogImg, (dogx, dogy))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
I know the code seems a bit messed up but I'm new in python and I'd like if you can explain to me my error. The problem might be in the recv
size, but as I said, I'm new to Python so I'd like if you can explain to me how can I calculate the bytes of the message (if that's the problem).