Skip to content

Instantly share code, notes, and snippets.

@koshov
Last active December 19, 2015 21:48
Show Gist options
  • Save koshov/6022530 to your computer and use it in GitHub Desktop.
Save koshov/6022530 to your computer and use it in GitHub Desktop.
# Echo client program
import socket
import sys
# Set up connection
HOST = 'WR8DV9C2' # your host name here
PORT = 50007
RUN = True
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect((HOST, PORT))
grid = [0,0,0, 0,0,0, 0,0,0]
# Draw grid
def drawGrid():
for y in xrange(0, 3):
for x in xrange(0, 3):
if x != 0: print("|"),
if grid[3*y+x] == 1: print("X"),
elif grid[3*y+x] == 2: print("O"),
else: print(" "),
print"\n"
# Update grid
def updateGrid(userIn, player):
if userIn == None:
userIn = sys.stdin.readline()
print # solves a formatting issue
if userIn == "kill\n":
print "Bye!"
conn.sendall("kill\n")
conn.close()
sys.exit()
elif userIn == "reset\n":
print "Restarting game!"
for i in xrange(0,9):
grid[i] = 0
else:
try:
x = int(userIn[0])
y = int(userIn[2])
msg = userIn[4:]
loc = (y-1)*3 + (x-1)
if grid[loc] == 0 and loc<10:
grid[loc] = player
else:
print("This field is no good, you dummy!\n>>"),
return None
if len(msg)>2: print "Player says: %s" % msg
except:
print("Whoops, I could not parse that! Please try again.\n>>"),
return None
return userIn
while RUN:
print "Your turn, sir:"
drawGrid()
print(">>"),
userIn = updateGrid(None, 1)
while userIn == None:
userIn = updateGrid(None, 1)
conn.sendall(userIn)
drawGrid()
data = conn.recv(1024)
updateGrid(data, 2)
conn.close()
print 'Received', repr(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment