Commit b4a67f2a authored by Michele's avatar Michele

tic tac toe now works on socket

parent 77921993
......@@ -22,7 +22,11 @@
# Copyright Stephen Ostermiller 2002-2014
import random
# make ot deterministic for the moment
# TODO: comment following line
random.seed(100)
import socket
import sys
turn = -1
xWon = 0
......@@ -341,24 +345,84 @@ def nice_print():
line = line + cell + " | "
print(line)
def in_line_board():
ret = ''
for j in range(9):
char = cells[j]
if char == '':
char = str(j)
ret = ret + char
return ret
if __name__ == "__main__":
makeCells()
newGame()
nice_print()
#nice_print()
# 0 to 8 for moves, 9 for reset
HOST = 'localhost' # Symbolic name, meaning all available interfaces
PORT = 29001 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print('Socket bind complete')
#Start listening on socket
s.listen(10)
print('Socket now listening')
#wait to accept a connection - blocking call
conn, addr = s.accept()
print("Connected with client")
conn.send(bytes('Welcome to the Tic Tac Toe. 0-8 valid inputs, 9 for reset.\n', 'UTF-8'))
while True:
move1 = int(input("Next move? "))
#Receiving from client
data = conn.recv(1024)
if not data:
break
move1 = int(data.decode("utf-8"))
if move1 == 9:
newGame()
elif (move1 > 9 or move1 < 0):
raise
pass
else:
move(move1)
nice_print()
#nice_print()
state = getState()
winner = detectWin(state)
if winner != 0:
print("Game finished. Player 1 won "+ str(xWon) + " games, while Player 2 won "+ str(oWon) + " games. New game.")
conn.sendall(bytes("END\n", 'UTF-8'))
newGame()
nice_print()
# build an output
# 0O2X4O6X8 stands for
# | 0 | O | 2 |
# | X | 4 | O |
# | 6 | X | 8 |
board = in_line_board()
conn.sendall(bytes(board, 'UTF-8'))
# out of loop
conn.close()
s.close()
print("Socket closed")
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment