jsb-netgame/game.py

67 lines
1.6 KiB
Python
Raw Normal View History

2024-02-03 17:57:23 +00:00
import network, sys, json, pygame
pygame.init()
address = ("0.0.0.0", 33033)
w, h = 640, 480
size = [w, h]
black = [0, 0, 0]
class Player:
def __init__(self, address, pos, color):
self.address = address
self.pos = pos
self.color = color
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
sock = network.Sock()
sock.listen(address)
me = Player(address, [10, 10], [255, 0, 0])
players = {}
def send_all(msg):
msg = json.dumps(msg)
for pid in players:
sock.send(msg, players[pid].address)
sock.send(json.dumps({"type":"join","pos":me.pos,"color":me.color}), ("192.168.0.255", 33033))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_right:
me.pos[0] += 1
send_all({"type":"move", "x":me.pos[0], "y":me.pos[1]})
elif event.key == pygame.K_left:
me.pos[0] -= 1
send_all({"type":"move", "x":me.pos[0], "y":me.pos[1]})
elif event.key == pygame.K_bottom:
me.pos[1] += 1
send_all({"type":"move", "x":me.pos[0], "y":me.pos[1]})
elif event.key == pygame.K_top:
me.pos[1] -= 1
send_all({"type":"move", "x":me.pos[0], "y":me.pos[1]})
for (r, c) in sock.get():
r = json.loads(r.decode())
if r["type"] == "join":
players[c] = Player(c, r["pos"], r["color"])
elif r["type"] == "move":
players[c].pos[0] += r["x"]
players[c].pos[1] += r["y"]
screen.fill(black)
pygame.draw.rect(screen, me.color, (*me.pos, 16, 16))
for pid in players:
player = players[pid]
pygame.draw.rect(screen, player.color, (*player.pos, 16, 16))
pygame.display.flip()
clock.tick(30)