-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnectFourClient.py
97 lines (66 loc) · 1.88 KB
/
ConnectFourClient.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
#Connect4 Client
import os,socket,time,sys
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input("Host IP: ")
port = 6667
client.connect((host,port))
def clearScreen():
for i in range(100):
print "\n"
clearScreen()
print "\nConnected!\n"
message = client.recv(1024)
print message
playerName = message[8:16] #Either 'player X' or 'player O'
def check_board(board):
"""Return a list of valid columns to play in"""
validColumns = []
counter = 0
for i in range(4,25,3):
if board[i] == ' ': #Check if the top of the column is empty
validColumns.append("{0}".format(counter))
counter += 1
return validColumns
def play():
while True:
board = client.recv(1024)
clearScreen()
print board
if board[-1] == '!': #Somebody has won
break
col = raw_input("\nYour turn {0}.\nWhich column?\n>> ".format(playerName),)
#Check if the input is a number and if it is a valid column to play in
while not col.isdigit() or col not in check_board(board):
col = raw_input("\nYour turn.\nWhich column?\n>> ",)
client.send(str(col))
board = client.recv(1024)
clearScreen()
print board
if board[-1] == '!':
break
else:
print "Waiting for other player..."
play()
while True:
playAgain = client.recv(1024)
print playAgain
answer = raw_input(">> ")
while answer != 'y' and answer != 'n':
print playAgain
answer = raw_input(">> ")
client.send(answer)
playAgain = client.recv(1024)
print "\n"
clearScreen()
if playAgain == "Let's play!": #Start a new game
print "\nWaiting for other person to play..."
if playerName == "player X":
playerName = "player O"
else:
playerName = "player X"
play()
else:
print "Someone didn't want to play again."
print "Or someone is not smart enough to type y"
break
client.close()