-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
277 lines (227 loc) · 8.52 KB
/
client.py
File metadata and controls
277 lines (227 loc) · 8.52 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
import socket, sys, time, pygame, connect4logic
class GameClient(object):
"""Object player will use to talk to the server"""
def enterDetails(self):
address = input("Enter server address: ")
port = input("Enter port: ")
while not port.isdigit():
port = input("Enter a valid port: ")
port = int(port)
roomName = input("Enter room name: ")
return address, port, roomName
def connector(self, address, port, roomName):
"""Creates connection between client and server"""
try:
print("Connecting...")
self._sock = socket.socket()
self._sock.connect((address, port))
self._sock.sendall(roomName.encode())
self._sock.settimeout(10)
print("Connected.")
except socket.timeout:
input("Connection failed")
sys.exit()
def accessServer(self):
address, port, roomName = self.enterDetails()
self.connector(address, port, roomName)
def recieveMessage(self):
"""Wait for message from the server"""
message = ""
while True:
try:
char = self._sock.recv(1)
charDecoded = char.decode()
if charDecoded != "&":
message += charDecoded
else:
return message
if pygame.get_init():
pygame.display.update()
except socket.timeout:
message = ""
continue
except ConnectionResetError:
input("Connection closed, press enter to end")
sys.exit()
def sendMessage(self, message):
"""Send message to server"""
if type(message) != str:
raise TypeError("Message must be a string")
try:
self._sock.sendall(message.encode())
except ConnectionResetError:
input("Connection closed, press enter to end")
sys.exit()
def waitForStart(self):
"""Wait for message from server saying 'start', this stops loop, indicated game starting, print all recieved"""
exit = False
while not exit:
message = self.recieveMessage()
if message.lower() == "start":
exit = True
else:
print(message)
def yourTurn(self):
"""Runs if it is your turn"""
pygame.display.set_caption("Your turn! Click a column to put make move")
while True:
move = self.getInputMove()
self.sendMessage(move)
response = self.recieveMessage()
if response == "confirmed":
self.doMove(int(move), self._colour)
break
elif response == "denied":
continue
def otherTurn(self):
"""Runs if its the other players turn"""
pygame.display.set_caption("Other players turn.")
move = self.recieveMessage()
self.doMove(int(move), self._otherColour)
def getInputMove(self):
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
mousePos = pygame.mouse.get_pos()
columnNum = self.getClickedColumn(mousePos)
if columnNum < 0 or columnNum > 6:
continue
else:
return str(columnNum)
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
def getClickedColumn(self, mousePos):
x = mousePos[0]
y = mousePos[1]
columnNum = x//60
return columnNum
def doMove(self, columnNum, colour):
self.renderer.animateFallingPiece(colour, columnNum, self.gameBoard)
self.gameBoard.placePiece(columnNum, colour)
def win(self):
"""Runs if you won"""
return None
def lose(self):
"""Run if you lose"""
return None
def initialise(self):
pygame.init()
self.gameBoard = connect4logic.Board()
self.renderer = Renderer()
def gameloop(self):
"""Overall loop that makes game work"""
self.initialise()
self._colour = self.recieveMessage()
if self._colour == "red":
self._otherColour = "yellow"
else:
self._otherColour = "red"
exit = False
while not exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.renderer.renderBoard(self.gameBoard)
whosTurn = self.recieveMessage()
if whosTurn == "yours":
self.yourTurn()
elif whosTurn == "other":
self.otherTurn()
winStatus = self.recieveMessage()
if winStatus != "false":
exit = True
if winStatus == "won":
self.win()
elif winStatus == "lose":
self.lose()
else:
sys.exit()
class Renderer(object):
def __init__(self):
self.TILESIZE = 60
self.HEIGHT = self.TILESIZE * 6
self.WIDTH = self.TILESIZE * 7
self.WHITE = (255, 255, 255)
self.BLACK = (0, 0, 0)
self.GREEN = (0, 255, 0)
self.YELLOW = (255, 255, 0)
self.CRIMSON = (220, 20, 60)
self.BLUE = (0, 0, 255)
self.BACKGROUNDCOL = self.GREEN
self.REDPIECECOL = self.CRIMSON
self.YELLOWPIECECOL = self.YELLOW
self.FRAMECOL = self.BLUE
self._surface = pygame.display.set_mode((self.WIDTH,self.HEIGHT))
pygame.display.set_caption("Connect 4")
def renderBackground(self):
self._surface.fill(self.BACKGROUNDCOL)
def animateFallingPiece(self, pieceColour, columnNum, board):
if pieceColour.lower() == "red":
colour = self.REDPIECECOL
elif pieceColour.lower() == "yellow":
colour = self.YELLOWPIECECOL
xPosition = (columnNum * self.TILESIZE) + self.TILESIZE//2
yPosition = 0
column = board.getBoard()[columnNum]
counter = 0
for place in column:
if place == None:
break
else:
counter += 1
finalyPosition = (abs(5-counter) * self.TILESIZE) + self.TILESIZE//2
finished = False
while not finished:
self.renderBackground()
self.renderPieces(board)
if yPosition >= finalyPosition:
yPosition = finalyPosition
finished = True
pygame.draw.circle(self._surface, colour, (xPosition, yPosition), self.TILESIZE//2)
self.renderBoardFrame()
pygame.display.update()
yPosition += 20
time.sleep(0.1)
def renderBoardFrame(self):
frameSurface = pygame.Surface((self.WIDTH, self.HEIGHT))
frameSurface.fill(self.FRAMECOL)
frameSurface.set_colorkey((0,0,0))
for x in range(7):
for y in range(6):
xPosition = (x*self.TILESIZE) + self.TILESIZE//2
yPosition = (y*self.TILESIZE) + self.TILESIZE//2
pygame.draw.circle(frameSurface, (0,0,0), (xPosition, yPosition), (self.TILESIZE//2)-5)
self._surface.blit(frameSurface, (0,0))
def renderPieces(self, board):
for x in range(7):
for y in range (6):
piece = board.getPiece(x, y)
if piece == None:
continue
elif piece.lower() == "red":
colour = self.REDPIECECOL
elif piece.lower() == "yellow":
colour = self.YELLOWPIECECOL
else:
continue
xPosition = (x * self.TILESIZE) + self.TILESIZE//2
yPosition = (abs(5-y) *self.TILESIZE) + self.TILESIZE//2
pygame.draw.circle(self._surface, colour, (xPosition, yPosition), self.TILESIZE//2)
def renderBoard(self, board):
self.renderBackground()
self.renderPieces(board)
self.renderBoardFrame()
pygame.display.update()
def testRender(self, board):
if type(board) != connect4logic.Board:
raise TypeError("board must be board object")
print(board)
def main():
gameClient = GameClient()
gameClient.accessServer()
gameClient.waitForStart()
gameClient.gameloop()
if __name__ == "__main__":
main()