Skip to content

Instantly share code, notes, and snippets.

@kra3
Created May 11, 2011
Embed
What would you like to do?
Retro "Tic Tac Toe" in python, wrote for fun
#! /usr/bin/env python
# All right reserved. Distributed Under BSD Lisence
__author__="Arun.K.R <the1.arun@gmail.com>"
__date__ ="$May 11, 2011 6:23:17 PM$"
import os, time
from random import choice
WIDTH = 3
BOARD = [str(i+1) for i in range(WIDTH*WIDTH)]
USERS = {True:'X', False:'O'}
def check_for_win(player, position, marked):
row=(position-1)/WIDTH
#horizontal equality test
if len(filter(marked, BOARD[row*WIDTH: row*WIDTH+WIDTH])) == WIDTH:
game_over(player)
#vertical equality test
if len(filter(marked, [BOARD[itm]
for itm in range((position-1) % WIDTH, WIDTH*WIDTH, WIDTH)])) == WIDTH:
game_over(player)
#diagonal (forward slash) test
if len(filter(marked, [BOARD[itm]
for itm in range(0, WIDTH*WIDTH, WIDTH+1)])) == WIDTH:
game_over(player)
#diagonal (backward slash) test
if len(filter(marked, [BOARD[itm]
for itm in range(WIDTH-1, WIDTH*WIDTH, WIDTH-1)[:-1]])) == WIDTH:
game_over(player)
def check_for_tie():
if len(filter((lambda x: x not in ['X', 'O']), BOARD)) == 0:
draw(ask=False)
print "\n", "Game is in tie!!!"
exit()
def ask_input(player):
try:
print "Player " + USERS[player] + "'s turn ->",
pos = int(raw_input("Enter a number from board: "))
assert pos>0 and pos<=WIDTH*WIDTH
except Exception:
print "Enter a valied number in the board!"
time.sleep(1)
draw(player)
else:
play(pos, player)
def draw(player=choice([True, False]), ask=True):
os.system('clear')
for i in range(WIDTH):
print ' | '.join(BOARD[i*WIDTH:i*WIDTH+WIDTH])
print '-'*(WIDTH * WIDTH)
if ask:
ask_input(player)
def play(position, player):
if BOARD[position-1] == str(position):
BOARD[position-1] = USERS[player]
else:
draw(player)
#check for win
check_for_win(player, position, marked=(lambda x: x==USERS[player]))
#check for draw
check_for_tie()
#switch player (simple LOGIC ANDing)
draw(not player)
def game_over(player):
draw(ask=False)
print "\n", "Player " + USERS[player] + " WON!!!"
exit()
if __name__ == "__main__":
draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment