954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Tic Tac Toe

So, I created this fun little Tic Tac Toe game all on my own. It was a tough project, and I know I used some inefficient strategies in the coding. Just like the other things I've posted, this could use a lot of suggestions in the areas of clean code and possible add-ons.

import random
board_list = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def update_board(l):
    board_list = l
    board = """
   %s   |   %s   |   %s
-----------------------
   %s   |   %s   |   %s
-----------------------
   %s   |   %s   |   %s""" % (board_list[0], board_list[1], board_list[2], board_list[3], board_list[4], board_list[5], board_list[6], board_list[7], board_list[8]) 
    return board
board = update_board(board_list)

def player_turn(marker):
    temp_list = []
    num = 1
    for item in board_list:
        if item == " ":
            temp_list.append(num)
        else:
            temp_list.append(item)
        num = num + 1
    temp_board = update_board(temp_list)
    print temp_board
    while 1:
        try:
            spot = raw_input("Where would you like to place your marker? ")
            while temp_list[int(spot)-1] in ["X","O"] or spot not in ["1","2","3","4","5","6","7","8","9"]:
                spot = raw_input("Where would you like to place your marker? ")
        except IndexError:
            continue
        break
    spot = int(spot) - 1
    board_list[spot] = marker
    return update_board(board_list)

def comp_turn():
    possible_comp_moves = []
    blah = see_if_win("computer_turn")
    if blah == None: # No way for the computer to win
        for index in range(len(board_list)):
            if board_list[index] == " ":
                possible_comp_moves.append(index) # adds the index for each possible move
        move_index = random.choice(possible_comp_moves) # randomly chooses a possible move
        board_list[move_index] = comp_marker
        return update_board(board_list)
    else:
        return update_board(blah)
        
    


def see_if_win(mode="normal"):
    a = 0
    b = 1
    c = 2
    d = 3
    e = 4
    f = 5
    g = 6
    h = 7
    i = 8
    winlist = [(a,b,c), (d,e,f), (g,h,i), (a,d,g,), (b,e,h), (c,f,i), (a,e,i), (g,e,c)]
    if mode == "normal":
        for win_type in winlist:
            if board_list[win_type[0]] == board_list[win_type[1]] == board_list[win_type[2]]:
                if board_list[win_type[0]] in ["X","O"]:
                    return board_list[win_type[0]]
    elif mode == "computer_turn":
        for win_type in winlist:
            if (board_list[win_type[0]] == board_list[win_type[1]]) and board_list[win_type[2]] == " " and board_list[win_type[0]] == comp_marker:
                board_list[win_type[2]] = comp_marker
                return board_list
            elif (board_list[win_type[0]] == board_list[win_type[2]]) and board_list[win_type[1]] == " " and board_list[win_type[0]] == comp_marker:
                board_list[win_type[1]] = comp_marker
                return board_list
            elif (board_list[win_type[1]] == board_list[win_type[2]]) and board_list[win_type[0]] == " " and board_list[win_type[1]] == comp_marker:
                board_list[win_type[0]] = comp_marker
                return board_list
        for win_type in winlist:
            if (board_list[win_type[0]] == board_list[win_type[1]]) and board_list[win_type[2]] == " " and board_list[win_type[0]] == marker:
                board_list[win_type[2]] = comp_marker
                return board_list
            elif (board_list[win_type[0]] == board_list[win_type[2]]) and board_list[win_type[1]] == " " and board_list[win_type[0]] == marker:
                board_list[win_type[1]] = comp_marker
                return board_list
            elif (board_list[win_type[1]] == board_list[win_type[2]]) and board_list[win_type[0]] == " " and board_list[win_type[1]] == marker:
                board_list[win_type[0]] = comp_marker
                return board_list

        return None

# PLAYER TURN
#board = player_turn("X")

def get_marker():
    marker=raw_input("Would you like to be X's or O's?: ")
    while marker not in ["X","O","x","o"]:
       marker=raw_input("Would you like to be X's or O's?: ")
    print "You are", marker.upper()
    if marker == "O":
        comp_marker = "X"
    else:
        comp_marker = "O"
    return marker,comp_marker

# Create an empty board
board = update_board(board_list)
# Menu to choose game type:
# PVP = player vs player
# PVC = player vs computer
menu = \
'''Game modes
(1) - Player vs. Player
(2) - Player vs. Computer'''
print menu
game = raw_input("Choose a menu item number: ")
if game == "1":
    game = "PVP"
elif game == "2":
    game = "PVC"
# Part of the loops; keep playing while no one has won
win = None
if game == "PVP":
    again = 1
    while again == 1:
        marker,comp_marker = get_marker()
        turn = "player"
        while win == None:
            if " " not in board_list:
                break
            if turn == "player":
                board = player_turn(marker)
                turn = "computer"
            elif turn == "computer":
                board = player_turn(comp_marker)
                turn = "player"
            win = see_if_win()
        print board
        if win != None:
            print "%s won!" % (win)
        else:
            print "There are no more moves. DRAW!"
        while again not in ["y","n"]:
            again = raw_input("Would you like to play again? (y/n) ").lower()
        if again == "y":
            again = 1
            board_list = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
            board = update_board(board_list)

elif game == "PVC":
    again = 1
    while again == 1:
        marker,comp_marker = get_marker()
        turn = "player"
        while win == None:
            if " " not in board_list:
                break
            if turn == "player":
                board = player_turn(marker)
                turn = "computer"
            elif turn == "computer":
                board = comp_turn()
                turn = "player"
            win = see_if_win()
        print board
        if win != None:
            print "%s won!" % (win)
        else:
            print "There are no more moves. DRAW!"
        while again not in ["y","n"]:
            again = raw_input("Would you like to play again? (y/n) ").lower()
        if again == "y":
            again = 1
            board_list = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
            board = update_board(board_list)

print "I hope you enjoyed playing Tic-Tac-Toe."


Thanks! I learn a lot from your responses.

LaMouche
Posting Whiz in Training
269 posts since Oct 2006
Reputation Points: 83
Solved Threads: 39
 

Hi!

Nice! :)
I didn't have a detailed look on the code, but
*) instead of

% (board_list[0], board_list[1], board_list[2], board_list[3], board_list[4], board_list[5], board_list[6], board_list[7], board_list[8])

it may be easier to write % (tuple(board_list)) ;)
*) I won several times, but the program didn't notice it. That's frustrating :-|

Regards, mawe

mawe
Junior Poster
133 posts since Sep 2005
Reputation Points: 19
Solved Threads: 58
 

Nice game, but like mawe says, your (PVC) 'player wins' detector does not work! Something to work on.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

Good stuff. I am a tic tac toe freak myself I guess. I wrote one in Ruby and one in C. It's interesting to see how much faster the C version can solve the game tree. My ruby version only looks ahead like four moves for performance reasons. AI is neat stuff. I put the code on my blog at

C version. . .
http://samdanielson.com/2006/12/28/noughts-and-crosses-in-the-key-of-c

Ruby version. . .
http://samdanielson.com/2006/12/28/gametrees-in-ruby

:mrgreen::mrgreen::mrgreen:

sambo357
Newbie Poster
1 post since Dec 2006
Reputation Points: 10
Solved Threads: 1
 

I found and played a pretty sophisticated Tic Tac Toe game written in Python at an earlier posting here:
http://www.daniweb.com/techtalkforums/thread26658.html

sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
 

How do i run this program in my python?

RemoveTag
Newbie Poster
1 post since Oct 2009
Reputation Points: 10
Solved Threads: 0
 

First toggle the DaniWeb code field to plain text. Right click and select all, then right click and copy to your editor. From the editor save the code as let's say 'TicTacToe2.py'. If you have an IDE editor, run the code from there. If you are using Python3, then you need to convert the Python2 code to Python3 code with the 2to3.py utility that comes with Python3.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You