This commit is contained in:
ZettaScript 2024-02-03 18:57:23 +01:00
parent 24a4126a8d
commit 2863035228
3 changed files with 70 additions and 2 deletions

View file

@ -7,7 +7,7 @@ port = int(sys.argv[2])
if sys.argv[1] == "s": if sys.argv[1] == "s":
sock.listen(("0.0.0.0", port)) sock.listen(("0.0.0.0", port))
while True: while True:
for d, a in sock.poll(): for d, a in sock.get():
print(d, a) print(d, a)
time.sleep(0.1) time.sleep(0.1)
elif sys.argv[1] == "c": elif sys.argv[1] == "c":

66
game.py Normal file
View file

@ -0,0 +1,66 @@
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)

View file

@ -4,6 +4,8 @@ from threading import Thread, Lock
class Sock: class Sock:
def __init__(self): def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.queue = [] self.queue = []
self.queue_lock = Lock() self.queue_lock = Lock()
self.sock_thread = None self.sock_thread = None
@ -17,7 +19,7 @@ class Sock:
self.sock_thread = SockThread(self, address, length) self.sock_thread = SockThread(self, address, length)
self.sock_thread.start() self.sock_thread.start()
def poll(self): def get(self):
if len(self.queue) == 0: if len(self.queue) == 0:
return [] return []
with self.queue_lock: with self.queue_lock: