Mercurial > touhou
annotate pytouhou/network.py @ 478:884ca91b0854
Fix synchro bug
author | Thibaut Girka <thib@sitedethib.com> |
---|---|
date | Wed, 28 Dec 2011 19:09:14 +0100 |
parents | e71b1bcf952a |
children | 1de67f332f00 |
rev | line source |
---|---|
475 | 1 import socket |
2 import struct | |
3 from select import select | |
4 | |
5 MSG_STRUCT = struct.Struct('!IHHB') | |
6 | |
7 class Network(object): | |
8 def __init__(self, port=8080, dest=None): | |
9 self.frame = 0 | |
10 self.keystate = 0 | |
11 self.old_keystate = 0 | |
12 | |
13 self.remote_addr = dest | |
14 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) | |
15 self.sock.bind(('', port)) | |
16 | |
17 | |
18 def read_messages(self): | |
19 messages = [] | |
20 | |
477
e71b1bcf952a
Wait a bit for incoming messages...
Thibaut Girka <thib@sitedethib.com>
parents:
475
diff
changeset
|
21 rlist, wlist, xlist = select([self.sock], [], [], 1./60.) |
475 | 22 while rlist: |
23 msg, addr = rlist[0].recvfrom(MSG_STRUCT.size) | |
24 # Check whether the message comes from the right address | |
25 if self.remote_addr is None or addr == self.remote_addr: | |
26 self.remote_addr = addr | |
27 | |
28 frame, keystate, old_keystate, checksum = MSG_STRUCT.unpack(msg) | |
29 | |
30 # Check for well-formedness | |
31 if checksum == sum(ord(c) for c in msg[:-1]) & 0xFF: | |
32 messages.append((frame, keystate, old_keystate, checksum)) | |
33 else: | |
34 print('Mismatch', self.remote_addr, addr) | |
35 | |
36 rlist, wlist, xlist = select(rlist, [], [], 0) | |
37 | |
38 return messages | |
39 | |
40 | |
41 def send_message(self): | |
42 frame, keystate, old_keystate = self.frame, self.keystate, self.old_keystate | |
43 if self.remote_addr is not None: | |
44 checksum = frame + (frame >> 8) + (frame >> 16) + (frame >> 24) | |
45 checksum += keystate + (keystate >> 8) | |
46 checksum += old_keystate + (old_keystate >> 8) | |
47 checksum &= 0xFF | |
48 self.sock.sendto(MSG_STRUCT.pack(frame, keystate, old_keystate, checksum), self.remote_addr) | |
49 | |
50 | |
51 def run_iter(self, game, keystate): | |
52 if self.frame < game.frame: | |
53 self.old_keystate, self.keystate = self.keystate, keystate | |
54 self.frame = game.frame | |
55 | |
56 for frame, keystate, old_keystate, checksum in self.read_messages(): | |
57 if frame == game.frame: | |
58 game.run_iter([self.keystate, keystate]) | |
59 elif frame == game.frame + 1: | |
60 print('Skipped') | |
478 | 61 game.run_iter([self.old_keystate, old_keystate]) |
475 | 62 game.run_iter([self.keystate, keystate]) |
63 | |
64 self.send_message() | |
65 |