Question

Making a TIC TAC TOE project

Posted June 16, 2021 182 views
PythonDevelopment

good day everyone,
I’m trying to implement a tic tac toe game project in [Python 3.9] and in my code I have created a sentence to assign which player take which letter whether x or o and I have created many statements but they didn’t work , kindly if anyone could assist to have a look on my code , I would be grateful.

import random

board = [“ ”, “ ”, “ ”, “ ”, “ ”, “ ”, “ ”, “ ”, “ ”, “ ”]
game_letters = [‘X’, 'O’]
player1 = 0
player2 = 1

1 | 2 | 3

4 | 5 | 6

7 | 8 | 9

def draw_board(board):
print(’———’)
print(board[1] , ’|’ , board[2] , ’|’ , board[3])
print(’———’)
print(board[4] , ’|’ , board[5] , ’|’ , board[6])
print(’———’)
print(board[7] , ’|’ , board[8] , ’|’ , board[9])
print(’———’)

def main():
player1 = 0
player2 = 1
drawboard(board)
print(“Welcome to TIC TAC TOE Game”)
player
1 = print(“Player 1 please enter your name: ”)
player1 = input().upper()
player
2 = print(“Player 2 please enter your name: ”)
player2 = input().upper()
turn = input(“Player ” + str(player
1) + “ would you like to choose X
or O?”) .upper()
print(str(player1) + “ take : ” + str(thisplayer) + str(player2)
+ “ take : ” + str(this
player))

while True:
    draw_board(board)
    move = int(input(" Make a move (X): "))
    valid_move = [ ]
    for position in range(9):
        if board[position]==0:
            valid_move.append(position)
        if move in valid_move:
            break                    
    print("illegal move")
    board[move] = str("X")
    """if board[move] == str("X") or board[move] == str("O"):
        print("Please make another move ")"""
    draw_board(board)
    move_2 = int(input(" Make a move (O): "))
    valid_move= [ ]
    for position in range(9):
        if board[position]==0:
            valid_move.append(position)
        if move in valid_move:
            break                    
    print("illegal move")
    board[move_2] = str("O")
    """if board[move_2] == str("X") or board[move] == str("O"):
            print("Please make another move ")"""


    # player_1 choices
    if board[1] == board[2] == board[3] == "X":  #across the top row
        print(str(player_1)  +  "wins" )
        break
    elif board[4] == board[5] == board[6] == "X":  #across the middle row
        print(str(player_1)  +  "wins" )
        break
    elif board[7] == board[8] == board[9] == "X":  #across the bottom row
        print(str(player_1)  +  "wins" )
        break
    elif board[1] == board[4] == board[7] == "X":  #first column
        print(str(player_1)  +  "wins" )
        break
    elif board[2] == board[5] == board[8] == "X":  #second column
        print(str(player_1)  +  "wins" )
        break
    elif board[3] == board[6] == board[9] == "X":  #third column
        print(str(player_1)  +  "wins" )
        break
    elif board[1] == board[5] == board[9] == "X":  #left diagonal
        print(str(player_1)  +  "wins" )
        break
    elif board[3] == board[5] == board[7] == "X":  #right diagonal
        print(str(player_1)  +  "wins" )
        break

    # player_2 choices
    if board[1] == board[2] == board[3] == "O":  #across the top row
        print(str(player_2)  +  "wins" )
        break
    elif board[4] == board[5] == board[6] == "O":  #across the middle row
        print(str(player_2)  +  "wins" )
        break
    elif board[7] == board[8] == board[9] == "O":  #across the bottom row
        print(str(player_2)  +  "wins" )
        break
    elif board[1] == board[4] == board[7] == "O":  #first column
        print(str(player_2)  +  "wins" )
        break
    elif board[2] == board[5] == board[8] == "O":  #second column
        print(str(player_2)  +  "wins" )
        break
    elif board[3] == board[6] == board[9] == "O":  #third column
        print(str(player_2)  +  "wins" )
        break
    elif board[1] == board[5] == board[9] == "O":  #left diagonal
        print(str(player_2)  +  "wins" )
        break
    elif board[3] == board[5] == board[7] == "O":  #right diagonal
        print(str(player_2)  +  "wins" )
        break
    else:
        print(" It's a Tie ")

print("Game Over")

def nextplayer(thisplayer):
return (this_player+1)%2

if name == ’main’:
main()

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
1 answer

Hi,

@mindintelligence wrote
I have created a sentence to assign which player take which letter whether x or o and I have created many statements but they didn’t work

Your function main() assigns a letter to the player but its invocation is put at the end of the script (and it is conditional for some reason). You should move the invocation to the place before the part of the code that carries on the game. I modified your code a bit putting some comments into it. Look at the snippet below.

import random

board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
game_letters = ['X', 'O']

# Y: players' names are strings rather than integers, so initial values of corresponding variables should be empty strings 
player1 = ''
player2 = ''

# Y: I have no idea what this is for, however, interpreter accepts it :-)
# Y: possibly, it is a result of lost of formatting after pasting the code into DO editor
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9

def draw_board(board):
    print('———')
    print(board[1] , '|' , board[2] , '|' , board[3])
    print('———')
    print(board[4] , '|' , board[5] , '|' , board[6])
    print('———')
    print(board[7] , '|' , board[8] , '|' , board[9])
    print('———')

# Y: I created this function to simply find opposite letter to the letter held by variable turn
# Y: for learning purposes you could modify this function to find the opposite letter within the letters available under the variable game_letters 
def opposite_turn(turn):
    if turn == 'X':
        return 'O'
    else:
        return 'X'

def main():
    draw_board(board)
    print("Welcome to TIC TAC TOE Game")
    player1 = print("Player 1 please enter your name: ")
    player1 = input().upper()
    player2 = print("Player 2 please enter your name: ")
    player2 = input().upper()    
    turn = input("Player " + str(player1) + " would you like to choose X or O?") .upper()
    # Y: it checks whether the letter entered  by user is acceptable, and if not, then asks for it again 
    while turn not in game_letters:
        turn = input("Player " + player1 + ", please choose just one letter: X or O  : ") .upper()
    # Y: I swapped the occurrences of variable thisplayer for variable turn and invocation of function opposite_turn() to print the chosen letters   
    print(player1 + " takes : " + turn + ',  ' + player2 + " takes : " + opposite_turn(turn))

# Y: I would invoke main() here to give the players a choice of letters before they start a game
main()
while True:
    draw_board(board)
    move = int(input(" Make a move (X): "))
    valid_move = [ ]
    for position in range(9):
        if board[position]==0:
            valid_move.append(position)
        if move in valid_move:
            break                    
    print("illegal move")
    board[move] = str("X")
    """if board[move] == str("X") or board[move] == str("O"):
        print("Please make another move ")"""
    draw_board(board)
    move_2 = int(input(" Make a move (O): "))
    valid_move= [ ]
    for position in range(9):
        if board[position]==0:
            valid_move.append(position)
        if move in valid_move:
            break                    
    print("illegal move")
    board[move_2] = str("O")
    """if board[move_2] == str("X") or board[move] == str("O"):
            print("Please make another move ")"""

    # player_1 choices
    if board[1] == board[2] == board[3] == "X":  #across the top row
        print(str(player_1)  +  "wins" )
        break
    elif board[4] == board[5] == board[6] == "X":  #across the middle row
        print(str(player_1)  +  "wins" )
        break
    elif board[7] == board[8] == board[9] == "X":  #across the bottom row
        print(str(player_1)  +  "wins" )
        break
    elif board[1] == board[4] == board[7] == "X":  #first column
        print(str(player_1)  +  "wins" )
        break
    elif board[2] == board[5] == board[8] == "X":  #second column
        print(str(player_1)  +  "wins" )
        break
    elif board[3] == board[6] == board[9] == "X":  #third column
        print(str(player_1)  +  "wins" )
        break
    elif board[1] == board[5] == board[9] == "X":  #left diagonal
        print(str(player_1)  +  "wins" )
        break
    elif board[3] == board[5] == board[7] == "X":  #right diagonal
        print(str(player_1)  +  "wins" )
        break

    # player_2 choices
    if board[1] == board[2] == board[3] == "O":  #across the top row
        print(str(player_2)  +  "wins" )
        break
    elif board[4] == board[5] == board[6] == "O":  #across the middle row
        print(str(player_2)  +  "wins" )
        break
    elif board[7] == board[8] == board[9] == "O":  #across the bottom row
        print(str(player_2)  +  "wins" )
        break
    elif board[1] == board[4] == board[7] == "O":  #first column
        print(str(player_2)  +  "wins" )
        break
    elif board[2] == board[5] == board[8] == "O":  #second column
        print(str(player_2)  +  "wins" )
        break
    elif board[3] == board[6] == board[9] == "O":  #third column
        print(str(player_2)  +  "wins" )
        break
    elif board[1] == board[5] == board[9] == "O":  #left diagonal
        print(str(player_2)  +  "wins" )
        break
    elif board[3] == board[5] == board[7] == "O":  #right diagonal
        print(str(player_2)  +  "wins" )
        break
    else:
        print(" It's a Tie ")

print("Game Over")

# Y: ?
def nextplayer(thisplayer):
    return (this_player+1)%2

# Y: ?
if name == 'main':
    main()

This code sometimes runs to some point and gives another error. Try to fix it by yourself as it is the best way to learn something, IMO. If you stuck, then post another question.

Keep coding :-)

P.S. I noticed that you convert into strings some values that are already the strings, e.g.

# the variable player1 gets string as a result of function input()
player1 = input().upper()
# so it is not needed to convert it into string again with str() function
print(str(player1))
# you can use 
print(player1)
# the code is clearer then and runs slightly faster (it is lesser to do for an interpreter)

input() function returns the string (even if a user entered a number), so you do not have to convert it into string again. More info here.

I hope it helps :-)

  • thanks very much for your assistance , I have yes some questions plz if you can assist its just because im new to programming that’s why i keep asking.
    now as for validmove= [ ]
    for position in range(9):
    if board[position]==0:
    valid
    move.append(position)
    if move in valid_move:
    break
    1- should i change the position to 1 and range 10 , because my board start with 1,2,3 not 0,1,2 ?
    2- during the execution it prints illegal move while its not illegal and also prints its a tie however the game isnt a tie , is this an indention mistake ?

    many many thanks again

    • Hi again,

      I am relatively new to Python as well, scripting mostly in Bash. But, let me take a look at your code :-)
      The first impression I get is there is no single comment in it !. My strong recommendation for you is to comment all the ideas/intentions being behind your code. If something (variable, function, object, method, etc.) is not explicitly named, comment it as well. I must admit that it is quite difficult to me to analyse your code because of lack of comments. I can just try to guess what you wanted to achieve writing the part of code below. I inserted my comment into it, and I hope this clue helps you somehow.

          valid_move = []
          for position in range(9):
              if board[position]==0:
                  # this condition will never be met as board[position] is either 'X', 'O' or ' ' (a space)
                  valid_move.append(position)
              if move in valid_move:
                  break
      

      As you can see your condition in the snippet above will never be met. I would like to encourage you to test it out inserting print() under the if statement (just for test). It will look like this:

          valid_move = []
          for position in range(9):
              if board[position]==0:
                  # this condition will never be met as board[position] is either 'X', 'O' or ' ' (a space)
                  print('Hi, the current position is ', position)
                  valid_move.append(position)
              if move in valid_move:
                  break
      

      Try to improve your code due to my comment :-)

      @mindintelligence wrote
      1- should i change the position to 1 and range 10 , because my board start with 1,2,3 not 0,1,2 ?

      It is up to you how you fix this issue, IMO. If it is easier for you, do it in this way but comment it. The variable board could be like below then:

      board = ["Not in use", " ", " ", " ", " ", " ", " ", " ", " ", " "]
      
      @mindintelligence wrote
      2- during the execution it prints illegal move while its not illegal and also prints its a tie however the game isnt a tie , is this an indention mistake ?

      It is not just an indentation mistake. Let’s take a look at illegal move issue. Illegal move message should be printed when value of variable move is not found among values of list valid_move. So condition if should be checked after the list valid_move is built up, and should rather look like:

          valid_move = []
          # variable position gets values from 1 to 9 due to the numbers on the board
          for position in range(1, 10):
              if board[position]==0:
                  # this condition will never be met as board[position] is either 'X', 'O' or ' ' (a space)
                  # list valid_move will never be built then; fix it :-)
                  valid_move.append(position)
          if move not in valid_move:
              print("illegal move")
      

      But if the illegal move occur, the player should be asked for their move again. So, let’s swap if statement for while loop to repeat input process:

          valid_move = []
          # variable position gets values from 1 to 9 due to the numbers on the board
          for position in range(1, 10):
              if board[position]==0:
                  # this condition will never be met as board[position] is either 'X', 'O' or ' ' (a space)
                  # list valid_move will never be built then; fix it :-)
                  valid_move.append(position)
          while move not in valid_move:
              print("illegal move")
              move = int(input(" Make a move (X): "))
      

      Try to fix It’s a tie issue by yourself. Let us know how it goes. Keep coding :-)