Anv3sh
Anv3sh

Reputation: 59

I made this code to make a tic-tac-toe game without a GUI in PYTHON

I made this code on tic-tac-toe in python and after iterating it works fine but in between the computer stops giving input. My code involves a user vs computer game. Please help me I know my code doesn't contain comments but I hope you will understand and I am a beginner so please help me!!!

In this code, the computer first asks you a choice to take O or X and then does a toss in which you enter 1 or 0 and compares it to a variable that has a random value between 1 and 0. Then according to toss either the user plays first or the computer.

For computer I used the randint() function so that it chooses the row and column in which it places X or O. In every iteration the code checks whether the random row or column computer gets does not matches with the already filled ones. So this is all about this code!!

import random
row1=None
column1=None
row2 = None
column2 = None
data1=[]
data2=[]
data3=[]
data4=[]
count=0
count2=0
print("Welcome to TIC-TAC-TOE!!")
tic=input("Enter O or X as your choice --> ")
if tic=='O':
    tac='X'
else:
    tac='O'
block=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
i=0
choice=int(input("Enter 1 for Head and 0 for Tail --> "))
x=random.randint(0,1)
if choice==x:
    print("You won the toss you get the first chance : ")
    print("## Enter the row and column you want to put your choice in ##")
    row1=int(input("Row --> "))
    data1.append(row1)
    column1=int(input("Column --> "))
    data2.append(column1)
    block[row1-1][column1-1]=tic
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2!=0:
            print("## A.I ##")
            if row2!=None and column2!=None:
                row2=random.randint(1,3)
                data3.append(row2)
                index1+=1
                length1=len(data3)
                for j in data1:
                    if row2==j:
                        count+=1
                for k in range(0,index1):
                    if row2==data3[k]:
                        count2+=1
                while count>0 or count2>0:
                    row2=random.randint(1,3)
                    for j in data1:
                        if row2 == j:
                            count += 1
                    for k in range(0, index1):
                        if row2 == data3[k]:
                            count2 += 1
                data3[index1]=row2
                column2=random.randint(1,3)
                data4.append(column2)
                index2+=1
                length2=len(data4)
                count=0
                count2=0
                for j in data2:
                    if row2==j:
                        count+=1
                for k in range(0,index2):
                    if column2==data4[k]:
                        count2+=1
                while count>0 or count2>0:
                    column2=random.randint(1,3)
                    for j in data2:
                        if row2 == j:
                            count += 1
                    for k in range(0, index2):
                        if column2 == data4[k]:
                            count2 += 1
                data4[index2]=column2
                block[row2-1][column2-1] = tac
            else:
                row2=random.randint(1,3)
                data3.append(row2)
                index1=0
                for j in data1:
                    if row2==j:
                        count+=1
                while count>0:
                    count=0
                    row2=random.randint(1,3)
                    data3[0]=row2
                    for j in data1:
                        if row2 == j:
                            count += 1
                column2=random.randint(1,3)
                data4.append(column2)
                index2=0
                count = 0
                for j in data2:
                    if row2 == j:
                        count += 1
                while count>0:
                    count=0
                    column2=random.randint(1,3)
                    data4[0]=column2
                    for j in data2:
                        if row2 == j:
                            count += 1
                block[row2 - 1][column2 - 1] = tac
            #block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2==0:
            print('## Your Turn ##')
            row1=int(input("Row --> "))
            data1.append(row1)
            column1=int(input("Column --> "))
            data2.append(column2)
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        else:
            print("Draw!!")
            break
else:
    print("## A.I won the toss ##")
    print("## A.I ##")
    row2=random.randint(1,3)
    data3.append(row2)
    index1=0
    column2=random.randint(1,3)
    data4.append(column2)
    index2=0
    block[row2-1][column2-1]=tac
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2==0:
            print("## A.I ##")
            row2=random.randint(1,3)
            data3.append(row2)
            index1+=1
            length1 = len(data3)
            for j in data1:
                if row2==j:
                    count+=1
            for k in range(0,index1):
                if row2==data3[k]:
                    count2+=1
            while count>0 or count2>0:
                count=0
                count2=0
                row2=random.randint(1,3)
                for j in data1:
                    if row2 == j:
                        count += 1
                for k in range(0,index1):
                    if row2==data3[k]:
                        count2+=1
            data3[index1]=row2
            count=0
            count2=0
            column2=random.randint(1,3)
            data4.append(column2)
            index2+=1
            length2 = len(data4)
            for j in data2:
                if column2==j:
                    count+=1
            for k in range(0,index2):
                if column2==data4[k]:
                    count2+=1
            while count>0 or count2>0:
                count=0
                count2=0
                column2=random.randint(1,3)
                for j in data2:
                    if column2 == j:
                        count += 1
                for k in range(0,index2):
                    if column2==data4[k]:
                        count2+=1
            data4[index2]=column2
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2!=0:
            print("## Your Turn ##")
            row1=int(input("Row --> "))
            data1.append(row1)
            column1=int(input("Column --> "))
            data2.append(column2)
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        else:
            print("Draw!!")
            break
print("Thanks for playing!!")

Upvotes: 1

Views: 4230

Answers (2)

ACL
ACL

Reputation: 11

This is a modular version with added checks for correct functioning under ALL conditions:

import random

def print_board(board):
    """Print the Tic-Tac-Toe board"""
    print(board[0][0], "|", board[0][1], "|", board[0][2])
    print("--+---+--")
    print(board[1][0], "|", board[1][1], "|", board[1][2])
    print("--+---+--")
    print(board[2][0], "|", board[2][1], "|", board[2][2])
    
def get_player_choice(board, player):
    """Get the row and column where the player wants to place their mark"""
    while True:
        try:
            row = int(input(f"Player {player}, enter the row number (1-3): "))
            column = int(input(f"Player {player}, enter the column number (1-3): "))
            if not (1 <= row <= 3 and 1 <= column <= 3):
                raise ValueError("Invalid row or column number")
            if board[row-1][column-1] != " ":
                raise ValueError("That cell is already occupied")
            return row-1, column-1
        except ValueError as e:
            print(e)

def has_won(board, player):
    """Check if the player has won the game"""
    for i in range(3):
        # Check rows
        if board[i][0] == board[i][1] == board[i][2] == player:
            return True
        # Check columns
        if board[0][i] == board[1][i] == board[2][i] == player:
            return True
    # Check diagonals
    if board[0][0] == board[1][1] == board[2][2] == player:
        return True
    if board[0][2] == board[1][1] == board[2][0] == player:
        return True
    return False

def play_game():
    """Play a game of Tic-Tac-Toe"""
    print("Welcome to Tic-Tac-Toe!")
    board = [[" "]*3 for _ in range(3)]
    players = ["X", "O"]
    random.shuffle(players)
    print(f"The first player is {players[0]}")
    while True:
        for player in players:
            print_board(board)
            row, column = get_player_choice(board, player)
            board[row][column] = player
            if has_won(board, player):
                print_board(board)
                print(f"Player {player} has won the game!")
                return
            if all(board[i][j] != " " for i in range(3) for j in range(3)):
                print_board(board)
                print("It's a tie!")
                return

play_game()

Upvotes: 1

Anv3sh
Anv3sh

Reputation: 59

I changed the code a bit and removed the while loops instead i replaced it with another while loop in which it checks whether the place with that row and column has white space or not if not then the column keeps on changing randomly until a place comes where there is a white space.Now for the row i simply checked whether the whole row is occupied or not if it is then the row keeps on changing randomly.This whole logic was changed for just the computer's turn.and guess what i reduced the code from 300 lines to 188 lines like 50%

Also changed the logic for draw it was rekt basically it just now checks whether all the places are not white spaces if yes then it gives draw

The Improved Code

import random
row1=None
column1=None
row2 = None
column2 = None
print("Welcome to TIC-TAC-TOE!!")
tic=input("Enter O or X as your choice --> ")
if tic=='O':
    tac='X'
else:
    tac='O'
block=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
i=0
choice=int(input("Enter 1 for Head and 0 for Tail --> "))
x=random.randint(0,1)
if choice==x:
    print("You won the toss you get the first chance : ")
    print("## Enter the row and column you want to put your choice in ##")
    row1=int(input("Row --> "))
    column1=int(input("Column --> "))
    block[row1-1][column1-1]=tic
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    index1=0
    index2=0
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2!=0:
            print("## A.I ##")
            if row2!=None and column2!=None:
                row2=random.randint(1,3)
                while block[row2-1][0]!=' ' and block[row2-1][1]!=' ' and block[row2-1][2]!=' ':
                    row2=random.randint(1,3)
                column2=random.randint(1,3)
                while block[row2-1][column2-1]!=' ':
                    column2=random.randint(1,3)
            else:
                row2=random.randint(1,3)
                column2=random.randint(1,3)
                while block[row2-1][column2-1]!=' ':
                    column2=random.randint(1,3)
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2==0:
            print('## Your Turn ##')
            row1=int(input("Row --> "))
            column1=int(input("Column --> "))
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        if block[0][0]!=' ' and block[0][1]!=' ' and block[0][2]!=' ' and block[1][0]!=' ' and block[1][1]!=' ' and block[1][2]!=' 'and block[2][0]!=' ' and block[2][1]!=' 'and block[2][2]!=' ':
            print("Draw!!")
            break
else:
    print("## A.I won the toss ##")
    print("## A.I ##")
    row2=random.randint(1,3)
    column2=random.randint(1,3)
    block[row2-1][column2-1]=tac
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2==0:
            print("## A.I ##")
            row2=random.randint(1,3)
            while block[row2 - 1][0] != ' ' and block[row2 - 1][1] != ' ' and block[row2 - 1][2] != ' ':
                row2 = random.randint(1, 3)
            column2=random.randint(1,3)
            while block[row2-1][column2-1]!=' ':
                column2=random.randint(1,3)
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2!=0:
            print("## Your Turn ##")
            row1=int(input("Row --> "))
            column1=int(input("Column --> "))
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        if block[0][0]!=' ' and block[0][1]!=' ' and block[0][2]!=' ' and block[1][0]!=' ' and block[1][1]!=' ' and block[1][2]!=' 'and block[2][0]!=' ' and block[2][1]!=' 'and block[2][2]!=' ':
            print("Draw!!")
            break
print("Thanks for playing!!")

Upvotes: 3

Related Questions