Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

[python] tic-tac-toe

tic-tac-toe

  • Please log in to reply
4 replies to this topic

#1 Hignar

Hignar

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 239 posts

Posted 26 June 2009 - 01:39 PM

Tic-tac-toe seems to be a popular tutorial for a lot of the other languages on this site so I thought I'd put one together for python.

I've only been learning python for a few weeks so it's likely that there will be some errors but I thought that this would be a good tutorial to help taking people learning the language from the point where they are typing out short examples to thinking about how to put together a larger program.

This is something that I hadn't really done before, so there may be better ways to approach it but this is how I got to my final program.

To start off with I decided to make a simple noughts and crosses (tic-tac-toe) game. I didn't want to complicate it by trying to learn GUI programming at the same time so it's entirely command line based.

First thing I did was work out what parts the program would need. Clearly we'd still need to be able to display the game board. Using a nested list seemed to make sense to me as we can display each row on a seperate line to produce a 3x3 board. We'd also need a way to fill the board in turns and finally we need to check after each turn whether there is a winning line for the player who just took a turn or see if the game is drawn. To make the game easier to follow the board should be reprinted after each turn. Players also need to be identified as 'X' and 'O'. This will help with the checkwin function later on.

The basic outline of the program looks like this
def checkwin(player):
  #code for checking for a winning line

def printboard():
  print board[0]
  print board[1]
  print board[2]

#initialise an empty board
board = [['-','-','-'],['-','-','-'],['-','-','-']]
player1 = 'X'
player2 = 'O'
win = False

#game loop
while(win == False):
  #code for player one's turn
  printboard()
  checkwin(player1)

  #code for player two's turn
  printboard()
  checkwin(player2)


So, first thing to do is enable us to fill the board. The easiest way to do this is to ask each player to select the row and column where they want to place their mark. I decided to take this code out of the main loop and define a function that could be applied to either player.

#code for player's turn
def playerturn(player):
  print "%s's turn" % player1
  print "Select column [1-3]: ",
  col = int(raw_input()) - 1
  print "Select row [1-3]: ",
  row = int(raw_input()) - 1
  board[row][col] = player

While this works there is no way to stop players overwriting previous moves so we need to code a check to see if it is a valid move and to loop the function until a valid move is given.

#code for player's turn
def playerturn(player):
  print "%s's turn" % player
  turn = 1
  while(turn)
    print "Select column [1-3]: ",
    col = int(raw_input()) - 1
    print "Select row [1-3]: ",
    row = int(raw_input()) - 1
    #check if move is allowed
    if board[row][col] == 'X' or board[row][col] == 'O'
      print "Already taken!"
    else
      board[row][col] = player
      turn = 0

So we can now print and fill the board. All that's left is to check for a winning line so we need to define the checkwin function. There are four ways to produce a winning line. A horizontal line, a vertical line, a diagonal line from left to right and a diagonal line from right to left. We need to check for each, but once a winning line is found there is no need for the check to continue.

def checkwin(player):
  #loop through rows and columns
  for c in range(0,3):
    #check for horizontal line
    if board[c][0] == player and board[c][1] == player and board[c][2] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
    #check for vertical line
    elif board[0][c] == player and board[1][c] == player and board[2][c] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
    #check for diagonal win (left to right)
    elif board[0][0] == player and board[1][1] == player and board[2][2] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
    #check for diagonal win (right to left)
    elif board[0][2] == player and board[1][1] == player and board[2][0] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
  else:
    playerwin = False
    return playerwin


So with these elements we should be able to put together a functional (if buggy) game. The only other thing needed is a way to check for a draw. As there are only 9 moves available we can count the number of turns taken and declare a draw when there are no further moves available. Also as a draw is only possible after an odd number of turns we only need to check for a draw after the first players turn.

The final code for our game is as follows


def checkwin(player):
  #loop through rows and columns
  for c in range(0,3):
    #check for horizontal line
    if board[c][0] == player and board[c][1] == player and board[c][2] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
    #check for vertical line
    elif board[0][c] == player and board[1][c] == player and board[2][c] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
    #check for diagonal win (left to right)
    elif board[0][0] == player and board[1][1] == player and board[2][2] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
    #check for diagonal win (right to left)
    elif board[0][2] == player and board[1][1] == player and board[2][0] == player:
      print "*********\n\n%s wins\n\n*********" % player
      playerwin = True
      return playerwin
  else:
    playerwin = False
    return playerwin

#code for player's turn
def playerturn(player):
  print "%s's turn" % player
  turn = 1
  while(turn):
    print "Select column [1-3]: ",
    col = int(raw_input()) - 1
    print "Select row [1-3]: ",
    row = int(raw_input()) - 1
    if board[row][col] == 'X' or board[row][col] == 'O':
      print "Already taken!"
    else:
      board[row][col] = player
      turn = 0

def printboard():
  print board[0]
  print board[1]
  print board[2]

#initialise an empty board
board = [['-','-','-'],['-','-','-'],['-','-','-']]
player1 = 'X'
player2 = 'O'
win = False
turns = 0

#game loop
#print empty board to start program
printboard()
while(win == False):
  playerturn(player1)
  turns += 1
  printboard()
  if checkwin(player1) == True: break
  if turns == 9:
    print "This game is a draw!"
    break

  playerturn(player2)
  turns += 1
  printboard()
  checkwin(player2)
  if checkwin(player2) == True: break

While the game runs and works there is clearly room for improvement. The most obvious area is error checking. As it stands any value can be entered for the moves and anything other than the numbers 1-3 produce an error. I was surprised just how much checking is needed for the game to be fully functional.

If there is any interest I will improve the game to include error checking in a further tutorial.
  • 1

#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 26 June 2009 - 04:38 PM

Nice job! Plus, it's nice to have a few python tutorials around :) +rep
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 psam

psam

    CC Regular

  • New Member
  • PipPipPip
  • 35 posts

Posted 28 June 2009 - 09:30 AM

It's a nice tutorial :). I wrote one tic-tac-toe script too a few days ago but it has a GUI (it's programmed using Tkinter) and it's a singleplayer version (computer plays are random so it's really easy to win). I'm attaching it to this message to contribute to this post.

Attached Files


  • 0

#4 Brandon W

Brandon W

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2092 posts
  • Location:Ipswich, Australia
  • Programming Language:C, Java
  • Learning:Java, C++, JavaScript

Posted 21 July 2009 - 10:33 PM

The tutorial could of been better if you explained the code like you did in your encryption one. Still like the output of your work and all people that put time into writing these should be recognised.

+rep

EDIT: Will have to wait a while, I just did it before :o
  • 0
I've returned...

#5 skelator54

skelator54

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 09 April 2012 - 09:24 PM

Is there a way of error handling, as in if row or column is to big or to small then tell them and they will get a new go? Here is what I have so far, it also has a function that will clear the screen and reprint using
os.system('cls')
Try changing "cls" to "clear" if it doesnt work, "cls" should work on windows.

EDIT:
I got it to work!
try:
   # some code
except IndexError:
   print "Oops! That was too big or too small, sorry. Try again..."
except ValueError:
   print "Oops! That was an invalid number, sorry. Try again..."

Attached Files


  • 0





Also tagged with one or more of these keywords: tic-tac-toe