-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.py
245 lines (212 loc) · 7.05 KB
/
player.py
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
import socket
import time
import threading
import pygame
from itertools import cycle
s = socket.socket()
host = input("Enter the server IP:")
port = 9999
playerOne = 1
playerOneColor = (255, 0, 0)
playerTwo = 2
playerTwoColor = (0, 0, 255)
bottomMsg = ""
msg = "Waiting for peer"
currentPlayer = 0
xy = (-1, -1)
allow = 0 #allow handling mouse events
matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
#Create worker threads
def create_thread(target):
t = threading.Thread(target = target) #argument - target function
t.daemon = True
t.start()
#initialize
pygame.init()
width = 600
height = 550
screen = pygame.display.set_mode((width, height))
#set title
pygame.display.set_caption("Tic Tac Toe")
#set icon
icon = pygame.image.load("tictactoe.png")
pygame.display.set_icon(icon)
#fonts
bigfont = pygame.font.Font('SFProDisplay-Regular.ttf', 64)
smallfont = pygame.font.Font('SFProDisplay-Regular.ttf', 32)
backgroundColor = (255, 255, 255)
titleColor = (0, 0, 0)
subtitleColor = (128, 0, 255)
lineColor = (0, 0, 0)
def buildScreen(bottomMsg, string, playerColor = subtitleColor):
screen.fill(backgroundColor)
if "One" in string or "1" in string:
playerColor = playerOneColor
elif "Two" in string or "2" in string:
playerColor = playerTwoColor
#vertical lines
pygame.draw.line(screen, lineColor, (250-2, 150), (250-2, 450), 4)
pygame.draw.line(screen, lineColor, (350-2, 150), (350-2, 450), 4)
#horizontal lines
pygame.draw.line(screen, lineColor, (150, 250-2), (450, 250-2), 4)
pygame.draw.line(screen, lineColor, (150, 350-2), (450, 350-2), 4)
title = bigfont.render("TIC TAC TOE", True, titleColor)
screen.blit(title, (110, 0))
subtitle = smallfont.render(str.upper(string), True, playerColor)
screen.blit(subtitle, (150, 70))
centerMessage(bottomMsg, playerColor)
def centerMessage(msg, color = titleColor):
WHITE=pygame.Color(255,255,255)
pos = (120, 480)
BLINK_EVENT = pygame.USEREVENT + 0
# screen.fill(backgroundColor)
if "One" in msg or "1" in msg:
color = playerOneColor
elif "Two" in msg or "2" in msg:
color = playerTwoColor
msgRendered = smallfont.render(msg, True, color)
screen.blit(msgRendered, pos)
if("winner" in msg):
clock = pygame.time.Clock()
screen_rect = screen.get_rect()
msgRendered = smallfont.render(msg, True, color)
blink_rect = msgRendered.get_rect()
blink_rect.center = screen_rect.center
off_text_surface = pygame.Surface(blink_rect.size)
blink_surfaces = cycle([msgRendered, off_text_surface])
blink_surface = next(blink_surfaces)
pygame.time.set_timer(BLINK_EVENT, 200)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == BLINK_EVENT:
blink_surface = next(blink_surfaces)
screen.blit(blink_surface, pos)
pygame.display.update()
clock.tick(60)
def printCurrent(current, pos, color):
currentRendered = bigfont.render(str.upper(current), True, color)
screen.blit(currentRendered, pos)
def printMatrix(matrix):
for i in range(3):
#When row increases, y changes
y = int((i + 1.75) * 100)
for j in range(3):
#When col increases, x changes
x = int((j + 1.75) * 100)
current = " "
color = titleColor
if matrix[i][j] == playerOne:
current = "X"
color = playerOneColor
elif matrix[i][j] == playerTwo:
current = "O"
color = playerTwoColor
printCurrent(current, (x, y), color)
def validate_input(x, y):
if x > 3 or y > 3:
print("\nOut of bound! Enter again...\n")
return False
elif matrix[x][y] != 0:
print("\nAlready entered! Try again...\n")
return False
return True
def handleMouseEvent(pos):
x = pos[0]
y = pos[1]
global currentPlayer
global xy
if(x < 150 or x > 450 or y < 150 or y > 450):
xy = (-1, -1)
else:
# When x increases, column changes
col = int(x/100 - 1.5)
# When y increases, row changes
row = int(y/100 - 1.5)
print("({}, {})".format(row,col))
if validate_input(row, col):
matrix[row][col] = currentPlayer
xy = (row,col)
def start_player():
global currentPlayer
global bottomMsg
try:
s.connect((host, port))
print("Connected to :", host, ":", port)
recvData = s.recv(2048 * 10)
bottomMsg = recvData.decode()
if "1" in bottomMsg:
currentPlayer = 1
else:
currentPlayer =2
start_game()
s.close()
except socket.error as e:
print("Socket connection error:", e)
def start_game():
running = True
global msg
global matrix
global bottomMsg
create_thread(accept_msg)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
if allow:
handleMouseEvent(pos)
if msg == "":
break
buildScreen(bottomMsg, msg)
printMatrix(matrix)
pygame.display.update()
def accept_msg():
global matrix
global msg
global bottomMsg
global allow
global xy
while True:
try:
recvData = s.recv(2048 * 10)
recvDataDecode = recvData.decode()
buildScreen(bottomMsg, recvDataDecode)
if recvDataDecode == "Input":
failed = 1
allow = 1
xy = (-1, -1)
while failed:
try:
if xy != (-1, -1):
coordinates = str(xy[0])+"," + str(xy[1])
s.send(coordinates.encode())
failed = 0
allow = 0
except:
print("Error occured....Try again")
elif recvDataDecode == "Error":
print("Error occured! Try again..")
elif recvDataDecode == "Matrix":
print(recvDataDecode)
matrixRecv = s.recv(2048 * 100)
matrixRecvDecoded = matrixRecv.decode("utf-8")
matrix = eval(matrixRecvDecoded)
elif recvDataDecode == "Over":
msgRecv = s.recv(2048 * 100)
msgRecvDecoded = msgRecv.decode("utf-8")
bottomMsg = msgRecvDecoded
msg = "~~~Game Over~~~"
break
else:
msg = recvDataDecode
except KeyboardInterrupt:
print("\nKeyboard Interrupt")
time.sleep(1)
break
except:
print("Error occured")
break
start_player()