Python Tic Tac Toe code propblems - python-3.x

I have tried creating a tic tac toe game using Python but it is not working. Can someone please take a look at it and tell me if I made a mistake?
When I run the game it only prints the board and then asks for a number for x. Once I type that, the game prints a board and closes.
def tic_tac_toe():
end = False
win_combinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
board = [1,2,3,4,5,6,7,8,9]
def draw():
print(board[0], board[1], board[2])
print(board[3], board[4], board[5])
print(board[6], board[7], board[8])
print()
def player_option_check():
while True:
try:
arg1 = input("please enter number")
arg1 = int(arg1)
if arg1 in range(0,9):
return arg1 - 1
else:
print ('not a number on he board')
except:
print('this is not a number re try')
def player_X():
choice = player_option_check()
board[choice] = 'x'
def player_y():
choice = player_option_check()
board[choice] = 'y'
def check_winner_x ():
for a in win_combinations:
if board[a[0]] == board[a[1]] == board[a[2]] == 'o':
print('player o wins')
return True
if board[a[0]] == board[a[1]] == board[a[2]] == 'x':
print('player x wins')
return True
for a in range(9):
if board[a] == "X" or board[a] == "O":
count += 1
if count == 9:
print("The game ends in a Tie\n")
return True
while not end:
draw()
end = check_winner_x
if end == True:
break
else:
player_X()
draw()
end = check_winner_x
if end == True:
break
else:
player_y()
draw()
if end==True:
again_play=print(input("would u like to play again press (y/n)"))
again_play == "y"
tic_tac_toe()
else:
print('thanks for playing')
break
tic_tac_toe()
So can you please help me find the mistake in my code. This is in Python 3.

I'm assuming it's cause you're not calling check_winner_x, just assigning it to the value end (maybe print(end) at the end of the loop to see it's value).
That means that when you get back to the while statement, end will register as "truthy" as it's no longer set to false and the loop will exit.
Try actually calling check_winner_x:
end = check_winner_x()
Not sure about anything else that might be buggy, but that's definitely a start.

Related

tic tac toe for python3

how do I add a score counter to this tic tac toe game:
i need to be able to keep score of the tic tac toe games so that the users (its a 2 player game) can play mutable games in a row and the program will keep score for them.The program bellow already allows the users to continue to play so that they can play multiple games in a row however the program does not keep track of the score of player x and o or the number of ties. how to I add to this so that it will tray player x's wins, player o's wins, and the number on ties
def drawboard(board):
print(' | |')
print(' ' + str(board[7]) + ' | ' +str( board[8]) + ' | ' + str(board[9]))
print(' | |')
print('-----------')
print(' | |')
print(' ' + str(board[4]) + ' | ' + str(board[5]) + ' | ' + str(board[6]))
print(' | |')
print('-----------')
print(' | |')
print(' ' + str(board[1]) + ' | ' + str(board[2]) + ' | ' + str(board[3]))
print(' | |')
def draw(board):
print(board[7], board[8], board[9])
print(board[4], board[5], board[6])
print(board[1], board[2], board[3])
print()
def t(board):
while True:
try:
x = int(input())
if x in board:
return x
else:
print("\nSpace already taken. Try again")
except ValueError:
print("\nThat's not a number. enter a space 1-9")
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
return True
def tic_tac_toe():
board = [None] + list(range(1, 10))
win = [(1, 2, 3),(4, 5, 6),(7, 8, 9),(1, 4, 7),(2, 5, 8),(3, 6, 9),(1, 5, 9),(3, 5, 7),]
for player in 'XO' * 9:
drawboard(board)
if GO(win,board):
break
print("Player {0}".format(player))
board[t(board)] = player
print()
def main():
while True:
tic_tac_toe()
if input("Play again (y/n)\n") != "y":
break
main()
Seeing that the code is already a bit messy and still without answer, I would suggest a quick & dirty solution.
You can define a global variable outside of all the functions, like:
scoreboard = {"X": 0, "O": 0, "T": 0}
Then you simply increment the scores in your GO function.
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
scoreboard[board[x]] += 1
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
scoreboard["T"] += 1
return True
And just print the scores from scoreboard wherever you want.
However, I would recommend to learn how to make your code more readable. It will help you to write more difficult programs more easily. It will help to avoid quick and dirty solutions like this one and make a lot of difficult things fall into place without much effort.
In any case, congrats on writing a working TTT game, keep it up :)
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
# return False if there is no winner
return False
def tic_tac_toe():
board = [None] + list(range(1, 10))
win = [(1, 2, 3),(4, 5, 6),(7, 8, 9),(1, 4, 7),(2, 5, 8),(3, 6, 9),(1, 5, 9),(3, 5, 7),]
for player in 'XO' * 9:
drawboard(board)
if GO(win,board):
# returns the winner if there is one
return player
elif GO(win, board) is False:
# returns False if winner is a tie
return False
print("Player {0}".format(player))
board[t(board)] = player
print()
First, you should create unique output values for different game outcomes rather than only True. Then, you can keep score in your while loop based on the value of the function call.
def main():
count_x = 0
count_o = 0
while True:
score = tic_tac_toe()
if score == 'X':
count_x += 1
elif score == 'O':
count_o += 1
print("The running score is " + '('+ str(count_x), str(count_y) +')')
if input("Play again (y/n)\n") != "y":
break
main()

Is there a way to add to a next free space in a two-dimensional array? (Python 3.x)

Is there a way in Python to add to an array to the next free space available? So if (0,0) has already a value, move on to the (0,1) and add the value there. I got as far as shown below, and I'm stuck now..
class Array:
def __init__(self):
self.array = [[0 for x in range(5)] for x in range(5)]
def view(self):
for x in self.array:
print(x)
def input(self):
item = input("Enter an item: ")
self.array[0][0] = item
array = Array()
array.input()
array.view()
Here is one example. I am simply running the loop 9 times. You should be able to work it into your OOP style code. I am also using pprint module from standard library as I like how it displays nested lists.
from pprint import pprint as pp
myList = [[0 for x in range(5)] for x in range(5)]
for i in range(9):
userInput = int(input("Enter an item: "))
isFound = False # This flag is used to prevent duplicate entries.
for rowIndex, row in enumerate(myList):
for colIndex, column in enumerate(row):
if column == 0 and not isFound:
myList[rowIndex][colIndex] = userInput
isFound = True
break
pp(myList)
Output after last iteration of the loop: (assuming 5 was always entered):
Enter an item: 5
[[5, 5, 5, 5, 5],
[5, 5, 5, 5, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
class Array:
def __init__(self):
self.myList = [[0 for x in range(5)] for x in range(5)]
def input(self):
print("You will be asked to put a value, if you want to stop, press RETURN key.")
for i in range(25):
print()
userInput = input("Enter an item: ")
isFound = False
if userInput == '':
menu()
for rowIndex, row in enumerate(self.myList):
for colIndex, column in enumerate(row):
if column == 0 and not isFound:
self.myList[rowIndex][colIndex] = userInput
isFound = True
break
print()
for x in self.myList:
print(x)
def remove(self):
print("Which box do you want to delete? Type in coordinates.")
x = int(input("Please enter a column: "))
x -= 1
y = int(input("Please enter a row: "))
y -= 1
self.myList[x][y] = 0
print()
for i in self.myList:
print(i)
menu()
def view(self):
for i in self.myList:
print(i)
menu()
array = Array()
def menu():
print()
print()
print()
print("****************")
print(" MENU")
print("****************")
print("Please choose:")
print("1. Add an item to the array")
print("2. Remove an item from the array")
print("3. View array")
print()
print("0. Quit")
print("****************")
option = int(input("Enter (1, 2 or 0): "))
print()
if option == 1:
array.input()
elif option == 2:
array.remove()
elif option == 3:
array.view()
elif option == 0:
quit()
else:
print("Error..")
menu()

What is wrong with my elif statement? Invalid Syntax

if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
from tkinter import *
def mhello():
mtext = ment.get()
mLabel2 = Label(test, text=mtext).pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+10')
test.title('Test')
mlabel = Label(test, text='Time to guess').pack()
mbutton = Button(test, text='Click', command = mhello).pack()
mEntry = Entry(test, textvariable=ment).pack()
test.mainloop()
from tkinter import *
def mhello():
my_word = 'HELLO'
mtext = ment.get()
if my_word == mtext:
mLabel2 = Label(test, text='Correct').pack()
else:
mLabel2 = Label(test, text='Incorrect').pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+300')
test.title('Test')
def label_1():
label_1 = Label(test, text='Hello. Welcome to my game.').pack()
def label_2():
label_2 = Label(test, text='What word am I thinking of?').pack()
button_1 = Button(test, text='Click', command = mhello).pack()
entry_1 = Entry(test, textvariable=ment).pack()
label_1()
test.after(5000, label_2)
test.mainloop()
from tkinter import *
from random import shuffle
game = Tk()
game.geometry('200x200')
game.grid()
game.title("My Game")
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def board_1():
board1 = []
k = 0
for i in range(3):
for j in range(3):
board1.append(Label(game, text = board[k]))
board1[k].grid(row = i, column = j)
k +=1
def board_2():
shuffle(board)
board2 = []
k = 0
for i in range(3):
for j in range(3):
board2.append(Label(game, text = board[k]))
board2[k].grid(row = i, column = j)
k +=1
board_1()
game.after(5000, board_2)
game.mainloop()
#2nd Option
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
The bit that has the Syntax Error is the 1st elif statement (2nd Option). Ignore all the code prior to this if necessary (it is there for context). Whenever I run the code it says that there is a syntax error and just positions the typing line (I don't know what it's called) at the end of the word elif.
This is a simple fix, with if else statements you need to have a closing ELSE and in this case there is not so when your program runs it sees that theres a lonely if without its else :)
if option == "1":
elif option == "2":
else:
'do something else in the program if any other value was recieved'
also a switch statement can be used here so it does not keep checking each condition and just goes straight to the correct case :D
The problem is that your block is separated from the first if-statement, where it actually belongs to. As it is, it follows the game.mainloop() statement, and adds an unexpected indentation. Try to rearrange your code like so:
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
[ Rest of the code ]

Tic Tac Toe in python keeps returning int error

I am trying to create a simple tic tac toe game in python. This is my code so far but when i run it it, it asks for a spot to select I enter a number and it displays the board but then it returns this error:
line 32, in
input = int(input("Select a spot: "))
TypeError: 'int' object is not callable
please help how I can resolve this as the user has to select a number. i'm using python 3.
import random
board = [0,1,2,3,4,5,6,7,8]
def show():
print (board[0]," | ", board[1]," | ", board[2])
print ("----------------")
print (board[3]," | ", board[4]," | ", board[5])
print ("----------------")
print (board[6]," | ", board[7]," | ", board[8])
def checkLine(char, spot1, spot2, spot3):
if board[spot1] == char and board[spot2] == char and board[spot3] == char:
return True
def checkAll(char):
if checkLine(char, 0, 1, 2):
True
if checkLine(char, 1, 4, 7):
True
if checkLine(char, 2, 5, 8):
True
if checkLine(char, 6, 7, 8):
True
if checkLine(char, 3, 4, 5):
True
if checkLine(char, 2, 4, 6):
True
if checkLine(char, 0, 4, 6):
True
while True:
input = int(input("Select a spot: "))
if board[input] != 'x' and board[input] != 'o':
board[input] = 'x'
if checkAll('x') == True:
print("-- X WINS --")
break;
random.seed()
opponent = random.randint(0,8)
while True:
if board[opponent] != 'o' and board[opponent] != 'x':
board[opponent] = 'o'
if checkAll('o') == True:
print("-- O WINS --")
break;
break;
else:
print ('This spot is taken')
show()
You assign an integer to input:
input = int(input("Select a spot: "))
Don't do that. Once you use the name input for a different object, the built-in function input will not be available anymore. So in the second loop input is not a function as before but an integer.
Use a different name:
user_input = int(input("Select a spot: "))
The problem is that the first time this line runs you assign an integer value to input and second time you call input("") it gets error because you call an integer! The problem would be solved by changing variable name.
To solve it you can simply change the variable name:
inp = int(input("Select a spot: "))

return seem to work for me in python 3.4

I'm trying to complete a dice game python (3.4) programming assignment for school and I'm having some trouble passing a variable from one function to another using a return statement, but when I run the program the variable "diesum" is interpreted as undefined.
import random
def RollDice():
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
diesum = die1 + die2
return diesum
def Craps(diesum):
craps = [2, 3, 12]
natural = [7, 11]
established = [4, 5, 6, 8, 9, 10]
if (diesum == craps):
print(die1, "+", die2, "=", diesum, ",You lost")
elif (diesum == natural):
print(die1, "+", die2, "=", diesum, ",You Win")
elif (diesum == established):
print("Point is ", diesum)
diesum = roll
while diesum == roll:
RollDice()
if diesum == roll:
print("Same Number, You Won!")
elif (diesum != 7):
print("You Win")
else:
print("You Lost!")
break
RollDice()
Craps(diesum)
You are not passing the result of RollDice into Craps. Try this instead:
result = RollDice()
Craps(result)
There are some other issues in the snippet that you have pasted, but this is the main reason that your are seeing an error. The return statement returns a value from a function. You need to bind the value to a name (result in my case) before you can refer to it. You could also write Craps(RollDice()) if you do not want to capture the result into an intermediate binding.
There are many reasons since it does not work.. first simplify the problem! This is a working initial example:
import random
def RollDice():
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
diesum = die1 + die2
print(diesum)
return diesum
def Craps(diesum):
craps = [2, 3, 12]
natural = [7, 11]
established = [4, 5, 6, 8, 9, 10]
for x in craps:
if diesum == x:
print("> You lost")
for x in natural:
if diesum == x:
print("> You Win")
for x in established:
if diesum == x:
print("> Point is ", diesum)
diesum = RollDice()
Craps(diesum)
Now write the second part of the game.. and be careful with indentation with Python!

Resources