[Tutor] Tic-Tac-Toe
bob gailer
bgailer at gmail.com
Sun Feb 20 05:06:11 CET 2011
I got stimulated to create a minimal tic-tac-toe program. No functions,
no classes.
board = [" "]*9
player = 'X'
prompt = "Player %s cell #, Q=quit, B=display board>"
while True:
cell = raw_input(prompt % player)
if cell in 'qQ': break
elif cell in 'bB':
print ('+---+' + '\n|%s%s%s|'*3 + '\n+---+') % tuple(board)
elif not(len(cell) == 1 and cell.isdigit() and '1' <= cell <= '9'):
print "Cell must be a number between 1 and 9."
elif board[int(cell)-1] != " ": print "Cell is occupied."
else:
board[int(cell)-1] = player
if any(1 for a,b,c in ((0,3,1), (3,6,1), (6,9,1), (0,7,3), (1,8,3),
(2,9,3), (0,9,4), (2,7,2)) if board[a:b:c] == [player]*3):
print player, "wins"
break
player = 'O' if player == 'X' else 'X'
--
Bob Gailer
919-636-4239
Chapel Hill NC
More information about the Tutor
mailing list