-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclientMain.py
More file actions
368 lines (344 loc) · 13.6 KB
/
clientMain.py
File metadata and controls
368 lines (344 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import pygame
from pygame.locals import *
from twisted.internet.protocol import ClientFactory
from twisted.internet.protocol import Protocol
from twisted.internet import reactor
from twisted.internet.defer import DeferredQueue
from twisted.internet.task import LoopingCall
import threading
import json
from preScreen import preScreen
from finalScreen import finalScreen
import Queue
import sys
from pacman import pacman
from board import board
from ghost import ghost
from items import items
import collections
# Array used to move around map
# 0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,0,0]
,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]]
#imap = tmap
class GameSpace():
def redraw(self):
self.screen.blit(self.background, (0,0))
self.allsprites.draw(self.screen)
pygame.display.flip()
def __init__(self, gf):
self.connected = False
pygame.init()
self.factory = gf
self.closed = False
self.factory.setGS(self)
self.winner = None
self.height = 640
self.width = 640
self.screen = pygame.display.set_mode((self.width, self.height), DOUBLEBUF)
self.mode = 1 # start in pause
self.index = -1 # used to identify which ghost the player is
self.numPlayers = 0 # counts other players
pygame.mouse.set_visible(0)
self.addedFactory = False
# Create Background
self.background = pygame.Surface(self.screen.get_size())
self.background.fill((0,0,0))
# Create Clock
self.clock = pygame.time.Clock()
self.going = False
# Create Objects
self.allsprites = pygame.sprite.OrderedUpdates()
self.board = board(self)
self.preScreen = preScreen(self, "Connecting to Server...")
self.items = items(self, self.mode, imap, self.board)
self.ghosts = list()
self.sendingEvents = list()
self.ghosts.append(ghost(self, self.mode, gmap, self.board, "RED"))
self.ghosts.append(ghost(self, self.mode, gmap, self.board, "CYAN"))
self.ghosts.append(ghost(self, self.mode, gmap, self.board, "ORANGE"))
self.ghosts.append(ghost(self, self.mode, gmap, self.board, "PINK"))
self.pacman = pacman(self, self.mode, gmap, self.board,self.items.getItemsList(),self.ghosts)
self.player = None
for i in self.items.getItemsList():
self.allsprites.add(i)
self.allsprites.add(self.ghosts)
self.allsprites.add(self.pacman)
self.allsprites.add(self.board)
# Allow user to press down on key
#pygame.key.set_repeat(500,30)
def main(self):
self.going = True
self.connected = False
distance = 5
while(not self.connected):
self.clock.tick(30)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_q:
self.connected = True
self.going = False
self.closed = True
elif event.type == QUIT:
self.connected = True
self.going = False
self.closed = True
self.screen.blit(self.background, (0,0))
self.screen.blit(self.preScreen.image, self.preScreen.rect)
pygame.display.flip()
# Process Received Data
if(self.going):
pdata = self.factory.connection.getData()
data = json.loads(pdata)
while(data['request'] != 'start'):
if(data['request'] == 'init'):
self.index = data['index']
self.player = self.ghosts[self.index]
elif(data['request'] == 'updatePlayers'):
self.numPlayers = data['numConns']
pdata = self.factory.connection.getData()
#print("pdata is ", pdata)
#print(" <<<<<<<<<")
data = json.loads(pdata)
#print("self.index: ", self.index)
#print("self.numPlayers: ", self.numPlayers)
while self.going:
self.clock.tick(30)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_UP:
self.sendingEvents.append("UP")
self.player.updateSetDirection("UP")
elif event.key == K_DOWN:
self.sendingEvents.append("DOWN")
self.player.updateSetDirection("DOWN")
elif event.key == K_RIGHT:
self.sendingEvents.append("RIGHT")
self.player.updateSetDirection("RIGHT")
elif event.key == K_LEFT:
self.sendingEvents.append("LEFT")
self.player.updateSetDirection("LEFT")
elif event.key == K_q:
self.going = False
self.closed = True
elif event.type == QUIT:
self.going = False
self.closed = True
self.sendEvents()
self.processForeignEvents()
self.allsprites.update() # tick
self.redraw()
self.final = finalScreen(self, "{} Won!!!".format(self.winner))
tobreak = False
if(not self.closed):
for i in range(30):
self.clock.tick(30)
self.screen.blit(self.background, (0,0))
self.screen.blit(self.final.image, self.final.rect)
pygame.display.flip()
for event in pygame.event.get():
if event.type == QUIT:
tobreak = True
if(tobreak):
break
pygame.quit()
reactor.callFromThread(reactor.stop)
def sendEvents(self):
# Send imap, position of pacman and ghosts, whether ghost is spooked or not
data = dict()
data["request"] = "update"
data['type'] = 'ghost'
data['index'] = self.index
data['events'] = self.sendingEvents
self.factory.connection.sendData(json.dumps(data))
del self.sendingEvents[:]
def processForeignEvents(self):
#print("Processing foreign Events")
numUpdates = 0
while(numUpdates < self.numPlayers):
try:
pdata = self.factory.connection.getData() # Blocking call until data is received
data = json.loads(pdata)
#print("In processing events data is ", data)
if(data['request'] == 'update'):
if(data['type'] == 'pacman'):
player = self.pacman
else:
player = self.ghost[data['index']]
events = data['events']
#print("In processing events events is ", events)
for event in events:
#print("Player is", player)
if(event == "UP"):
player.updateSetDirection("UP")
elif(event == "DOWN"):
player.updateSetDirection("DOWN")
elif(event == "RIGHT"):
player.updateSetDirection("RIGHT")
elif(event == "LEFT"):
player.updateSetDirection("LEFT")
numUpdates += 1
elif(data['request'] == 'release'):
self.player.release()
else:
print("Unhandled message", data)
except ValueError as e:
print("pdata: ", pdata)
print("The following Error has Occurred: ", e)
print("Quitting...")
sys.exit(1)
def pacmanWon(self):
#print("Pacman won!!!")
self.going = False
self.winner = "pacman"
def ghostWon(self):
#print("Ghost won!!!")
self.going = False
self.winner = "ghost"
class GameConnection(Protocol, object):
def __init__(self, Factory):
super(GameConnection, self).__init__() #
self.factory = Factory
self.gs = None
#self.lock = Threading.Lock()
self.condVar = threading.Condition()
self.queue = collections.deque()
self.qcount = 0
def connectionMade(self):
self.gs.connected = True
def dataReceived(self, data):
#print("Received data", data)
self.condVar.acquire()
self.queue.append(data)
self.qcount += 1
self.condVar.notify()
self.condVar.release()
def getData(self):
data = None
self.condVar.acquire()
while self.qcount == 0:
self.condVar.wait()
pdata = self.queue.popleft()
sdata = pdata.split('{')
del sdata[0] # should be empty
for n in range(len(sdata)):
sdata[n] = '{' + sdata[n]
if(len(sdata) > 1):
for s in sdata[1:]:
self.qcount += 1
self.queue.appendleft(s)
data = sdata[0]
self.qcount -= 1
self.condVar.release()
return data
def connectionLost(self, reason):
pass
#print("Connection lost with server. Quitting...")
#print("Reason: ", reason)
#sys.exit(1)
def sendData(self, data):
self.transport.write(data)
def setGS(self, gs):
self.gs = gs
class GameFactory(ClientFactory, object):
def __init__(self):
self.connection = GameConnection(self)
def buildProtocol(self, addr):
return self.connection
def setGS(self, gs):
self.gs = gs
self.connection.setGS(self.gs)
class runGame(threading.Thread):
def __init__(self, gf):
threading.Thread.__init__(self)
self.gs = GameSpace(gf)
def run(self):
#print("Running GS")
self.gs.main()
if __name__ == "__main__":
gf = GameFactory()
rn = runGame(gf)
rn.daemon = True
rn.start()
reactor.connectTCP("ash.campus.nd.edu",40049, gf)
reactor.run()