Skip to main content

Tic Tac Toe in python - Just for fun

The other day, I was looking for some GNU/Linux administration reference, I ended up viewing a "tic tac toe" program in Ruby at a Linux admin's blog.

He wrote that in ruby and took him 90mins. That was written using class.
But "Zen of Python in mind", I wrote my own version without class.
I prefer this way (sparse is better than dense), and I enjoy Python more when, I think of my Java days. 
I haven't read ruby code before hand so, I did not wrote a clone of ruby code.
And this took me around 40min. Because, I realized some missing features only when I played it several times.
Then only I added those.
Specifically, drawing complete board after someone wins and stopping the game when all fields are filled out.


#! /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()
view raw tictactoe.py hosted with ❤ by GitHub

I'll not say, the program is beautiful and very readable.
However, it's good enough for playing with it.

Comments

Popular posts from this blog

AJAX File Upload with Web2py

It was not that long, since I experienced a problem while trying to upload a file using an ajax  trapped form. I thought, it must be me doing something wrong. I was using web2py  to embed another page into a page via ajax. That is better known to web2py folk as LOADing a component. It's just happened that one of such component contains a file upload form. It was my first time using LOAD function provided by web2py. Basically it make use of jQuery to load the page via ajax into a target div and traps input of any form in that page, so that page doesn't reload. Oh, I forgot to say that web2py is bundled with jQuery. It's always boring and tedious to understand a problem without experiencing it. So, Let's play with an example, (PS: I"m using web2py a full stack python framework, but you can use any language at server side and this problem will be there because, it's a problem with ajax) My mod...

Start on Microchip programming... for hobby or for money

One of my friend asked me today the following question,  I'm often asked about this, someway or other. Let me answer this now for all.... Q: " I want to start programming on chip.. Can you suggest a good chip and a device to program it? Also tell me any sites which can help me ." A:" Simple one is Arduino. You will get it packaged with a programmer. If you want some more powerful and commercial one, Go for Microchip's PIC family of processors. After you are familiar with those, and need even more power, try AVR from ATMEL ." Some resources from my Bookmarks is given below: http://www.voti.nl/swp/ http://www.embedds.com/ http://www.instructables.com/id/Business-Card-PIC-Programmer/step2/Parts/ http://www.arduino.cc/playground/Main/ElectroInfoResources http://www.piclist.com/techref/microchip/index.htm My bookmarks become so messy now a days, and I'm not getting time to organize them. So, these are the quickest ones that I pic...

My First Python Program

I am very glad today. Because I finally wrote a python program all by myself. I am programming for about 3 years. Of which 2 are using C++ (Old standard and using Turbo C++ IDE ver 3.0 and yet to master Templates and STL. [:-p]) and After starting python using Dive into Python an excellent book by Mark Pilgrim during my 1st year summer vacation, and I only completed Data Structure section. Then I found an excellent Java tutorial by Sang Shin and obtained a certificate by completing First and basic course in Java. Now I am working with My Friend to develop applications in java. We established a web site already. He started programming when he is in 10, ie. more than 2 years of experience. He has Visual Basic too in his side. Now he is doing with JSP and I am concentrating on Python, Ruby (yet to start) and CSS. Today My pleasure is that I completed a python program myself. Which is asked to do in ' A byte of Python ' by Swaroop.C.H. Which is a command line program; and he...