comparison pytouhou/network.py @ 479:1de67f332f00

Fix several synchro issues
author Thibaut Girka <thib@sitedethib.com>
date Wed, 28 Dec 2011 19:42:48 +0100
parents 884ca91b0854
children d666856acb52
comparison
equal deleted inserted replaced
478:884ca91b0854 479:1de67f332f00
3 from select import select 3 from select import select
4 4
5 MSG_STRUCT = struct.Struct('!IHHB') 5 MSG_STRUCT = struct.Struct('!IHHB')
6 6
7 class Network(object): 7 class Network(object):
8 def __init__(self, port=8080, dest=None): 8 def __init__(self, port=8080, dest=None, selected_player=0):
9 self.frame = 0 9 self.frame = 0
10 self.keystate = 0 10 self.keystate = 0
11 self.old_keystate = 0 11 self.old_keystate = 0
12
13 self.selected_player = selected_player
12 14
13 self.remote_addr = dest 15 self.remote_addr = dest
14 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) 16 self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
15 self.sock.bind(('', port)) 17 self.sock.bind(('', port))
16 18
46 checksum += old_keystate + (old_keystate >> 8) 48 checksum += old_keystate + (old_keystate >> 8)
47 checksum &= 0xFF 49 checksum &= 0xFF
48 self.sock.sendto(MSG_STRUCT.pack(frame, keystate, old_keystate, checksum), self.remote_addr) 50 self.sock.sendto(MSG_STRUCT.pack(frame, keystate, old_keystate, checksum), self.remote_addr)
49 51
50 52
53 def run_game_iter(self, game, keystate, other_keystate):
54 keystates = [other_keystate, other_keystate]
55 keystates[self.selected_player] = keystate
56 game.run_iter(keystates)
57
58
51 def run_iter(self, game, keystate): 59 def run_iter(self, game, keystate):
52 if self.frame < game.frame: 60 if self.frame < game.frame:
53 self.old_keystate, self.keystate = self.keystate, keystate 61 self.old_keystate, self.keystate = self.keystate, keystate
54 self.frame = game.frame 62 self.frame = game.frame
55 63
56 for frame, keystate, old_keystate, checksum in self.read_messages(): 64 for frame, keystate, old_keystate, checksum in self.read_messages():
57 if frame == game.frame: 65 if frame == game.frame:
58 game.run_iter([self.keystate, keystate]) 66 self.run_game_iter(game, self.keystate, keystate)
59 elif frame == game.frame + 1: 67 elif frame == game.frame + 1:
60 print('Skipped') 68 self.run_game_iter(game, self.old_keystate, keystate)
61 game.run_iter([self.old_keystate, old_keystate])
62 game.run_iter([self.keystate, keystate])
63 69
64 self.send_message() 70 self.send_message()
65 71