Last active
December 19, 2015 21:48
-
-
Save koshov/6022534 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Echo server program | |
import socket | |
import sys | |
HOST = socket.gethostname() | |
PORT = 50007 | |
RUN = True | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.bind((HOST, PORT)) | |
s.listen(1) | |
conn, addr = s.accept() | |
print 'Connected by', addr | |
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: | |
drawGrid() | |
data = conn.recv(1024) | |
updateGrid(data, 2) | |
print "Your turn, sir:" | |
drawGrid() | |
print(">>"), | |
userIn = updateGrid(None, 1) | |
while userIn == None: | |
userIn = updateGrid(None, 1) | |
conn.sendall(userIn) | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment