I'm making multiplayer game (2 hosts, local network) in pygame. I'm newbie in socket programming and can't handle problem with sending and receiving multiple data. I've got this pretty nice code from this: Python Online Game Tutorial - Sending Objects - techwithtim.net but it only shows how to send one object to both players.
I want to modify this by adding mobs and shooting mechanic, but I can't figure out how to send Mob
object to each player and update this mob in real time.
I've modified server script like this:
server.py
objects = [Player(200,500-50, 50,50, (0,255,0)),
Player(400,500-50, 50,50, (0,0,255)),
Mob(200,-1,30,40,(255,0,0))]
def threaded_client(conn, player):
conn.send(pickle.dumps(objects[player]))
reply = []
while True:
try:
data = pickle.loads(conn.recv(2048))
objects[player] = data
if not data:
print("Disconnected")
break
else:
if player == 1:
reply = objects[0], objects[2]
reply = list(reply)
else:
reply = objects[1], objects[2]
reply = list(reply)
print("Received: ", data)
print("Sending : ", reply)
conn.sendall(pickle.dumps(reply))
except:
break
print("Lost connection")
conn.close()
and client side looks almost the same as original (only redrawWindow() is changed) client.py
def redrawWindow(win,player, player2):
win.fill((255,255,255))
player.draw(win)
player2[0].draw(win)
player2[1].draw(win)
pygame.display.update()
def main():
run = True
n = Network()
p = n.getP()
clock = pygame.time.Clock()
while run:
clock.tick(60)
p2 = n.send(p)
print(p2)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
p.move()
redrawWindow(win, p, p2)
pygame.display.flip()
Mob class - mob.py:
import pygame
import random
WIDTH = 500
HEIGHT = 600
class Mob():
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.rect = (x, y, width, height)
self.vel = 1
def draw(self, win):
pygame.draw.rect(win, self.color, self.rect)
self.move()
def move(self):
self.y += self.vel
self.update()
def update(self):
self.rect = (self.x, self.y, self.width, self.height)
With my modifications of code, mob
is sent to each player, but this mob
doesn't change its position. If I draw mob
only in client side, it works OK but position of mob
is different for both players. How could I make this work?