I have 2 programs for a socket app I'm making in python and pygame, there are 2 rects, both can be moved using separate computers, but its not working, when I run the program the pygame window is black and if I click on it says not responding and soon exits. I've looked around but can't find how to fix it.
Hears my code:
import socket,pygame,struct
screen = pygame.display.set_mode([500,500])
screen.fill([255,255,255])
red = pygame.Rect(250,250,50,50)
blue = pygame.Rect(150,150,50,50)
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print ("Socket Up and running with a connection from",addr)
while True:
pygame.draw.rect(screen,[255,0,0],red)
pygame.draw.rect(screen,[0,0,255],blue)
pygame.display.flip()
buf = c.recv(8, socket.MSG_WAITALL)
struct.unpack("2i", buf)
x, y = struct.unpack("2i", buf)
red = pygame.Rect(x,y,50,50)
screen.fill([255,255,255])
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
blue.x -= 1
if blue.x <= 0:
blue.x +=1
if keys[pygame.K_RIGHT]:
blue.x += 1
if blue.x >= 450:
blue.x -=1
if keys[pygame.K_UP]:
blue.y -= 1
if blue.y <= 0:
blue.y +=1
if keys[pygame.K_DOWN]:
blue.y += 1
if blue.y >= 450:
blue.y -=1
s.send(struct.pack("2i", blue.x, blue.y))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
s.close()
if event.type == pygame.QUIT:
pygame.quit()
s.close()
And the other end:
import socket,pygame,struct
screen = pygame.display.set_mode([500,500])
screen.fill([255,255,255])
red = pygame.Rect(250,250,50,50)
blue = pygame.Rect(150,150,50,50)
s = socket.socket()
s.connect(('192.168.43.188',12345))
while True:
screen.fill([255,255,255])
pygame.draw.rect(screen,[255,0,0],red)
pygame.draw.rect(screen,[0,0,255],blue)
pygame.display.flip()
buf = s.recv(8, socket.MSG_WAITALL)
struct.unpack("2i", buf)
x, y = struct.unpack("2i", buf)
blue = pygame.Rect(x,y,50,50)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
red.x -= 1
if red.x <= 0:
red.x +=1
if keys[pygame.K_RIGHT]:
red.x += 1
if red.x >= 450:
red.x -=1
if keys[pygame.K_UP]:
red.y -= 1
if red.y <= 0:
red.y +=1
if keys[pygame.K_DOWN]:
red.y += 1
if red.y >= 450:
red.y -=1
s.send(struct.pack("2i", red.x, red.y))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
s.close()
if event.type == pygame.QUIT:
pygame.quit()
s.close()