Tic Tac Toe AI Bugs plz help me fix it - python-3.x

I am trying to create a Tic-Tac-Toe AI that will never lose. My code works sometimes but it does not work other times. Sometimes it will find the best move and print it out correctly but other times it will just fail. For example, once the AI takes the center if you press nine and take the top right corner then the AI will take a top left corner. Then if you take the bottom right corner the AI takes the middle left tile and then if you take the middle right tile then you will win. I wanted the AI to take the middle right to stop you from winning. I am a beginner programmer so please excuse me if the code is not written in the most optimal way. Why is that? Also can you please elaborate your explanation so I can understand what is wrong? Here is the code:
the_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
def print_board(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
def check_for_win(current_state_of_the_board, player_sign):
if current_state_of_the_board["7"] == current_state_of_the_board["8"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["4"] == current_state_of_the_board["5"] == current_state_of_the_board["6"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["2"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["4"] == current_state_of_the_board["7"] == player_sign:
return "Victory"
elif current_state_of_the_board["2"] == current_state_of_the_board["5"] == current_state_of_the_board["8"] == player_sign:
return "Victory"
elif current_state_of_the_board["3"] == current_state_of_the_board["6"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["7"] == current_state_of_the_board["5"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["9"] == current_state_of_the_board["5"] == current_state_of_the_board["1"] == player_sign:
return "Victory"
else:
return "No Victory"
def get_copy_of_the_board(current_board, move, player_sign):
copy_of_the_board = current_board
if copy_of_the_board[str(move)] == " ":
copy_of_the_board[str(move)] = player_sign
return copy_of_the_board
else:
return copy_of_the_board
def check_for_computer_win():
for number in range(1, 10):
print( check_for_win(get_copy_of_the_board(the_board, number, "X"), "X"))
if check_for_win(get_copy_of_the_board(the_board, number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_win():
for number in range(1, 10):
print(check_for_win(get_copy_of_the_board(the_board, number, "O"), "O"))
if check_for_win(get_copy_of_the_board(the_board, number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_computer_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "X")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "O")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def get_computer_move():
if check_for_computer_win() != "Check next condition":
comp_move = check_for_computer_win()
return comp_move
else:
if check_for_player_win() != "Check next condition":
comp_move = check_for_player_win()
return comp_move
else:
if check_for_computer_forks() != "Check next condition":
comp_move = check_for_computer_forks()
return comp_move
else:
if check_for_player_forks() != "Check next condition":
comp_move = check_for_player_forks()
return comp_move
else:
for move in ["5"]:
if the_board[move] == " ":
comp_move = "5"
return comp_move
for move in ["7", "9", "1", "3"]:
if the_board[str(move)] == " ":
return move
for move in ["4", "8", "6", "2"]:
if the_board[str(move)] == " ":
return move
def game():
count = 0
turn = "computer"
while count < 9:
if turn == "computer":
print("The computer move is: ")
final_computer_move = get_computer_move()
if the_board["1"] == "O":
pass
else:
if final_computer_move == "1":
pass
else:
the_board["1"] = " "
the_board[final_computer_move] = "X"
print_board(the_board)
if check_for_win(the_board, "X") == "Victory":
print("The computer has won!")
exit()
else:
turn = "player"
count += 1
else:
player_move = input("Where would you like to move?")
the_board[player_move] = "O"
print_board(the_board)
if check_for_win(the_board, "O") == "Victory":
print("You have won!")
exit()
else:
turn = "computer"
count += 1
game()
Thanks in advance!!

Related

Why the "stop" input doesnt stop the hitorstop() and run the code for the condition elif todo == "stop"

import random
class Player:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
run = True
def __init__(self):
self.name = input("Enter your name : ")
self.Bet = inputs.bet(self)
self.Aceval = inputs.Aval(self)
class Dealer:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
class inputs:
def bet(self):
"""
takes in the bet from the user and stores it in the player class
:return: output
"""
self.bet = input("Enter the amount for your bet : ")
output = self.bet
if self.bet.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.bet(self)
else:
return int(output)
def Aval(self):
"""
Takes the value for ace and stores it in the player class
:return: output
"""
self.aval = input("Enter the value for ACE (1 or 10) : ")
output = self.aval
if self.aval.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.Aval(self)
elif self.aval.isnumeric() == True:
if self.aval in ["1", "10"]:
return int(output)
else:
print("I understand you suffer braincell deficiency but I need you to fire up those 2 braincells you have and enter the proper number")
return inputs.Aval(self)
def valcalc(card):
"""
takes the card for player.deck and returns the value of that card
:return: card value
"""
if card[0] in ("K", "Q", "J"):
return 10
elif card[0] == "A":
return p.Aceval
else:
if len(card) > 2:
return int(card[0:2])
else:
return int(card[0])
def hitorstop(todo):
if todo.lower() == ("hit" or "stop"):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
if todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
p = Player()
d = Dealer()
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
print("Dealer's card is :" + str(dcard) + "+")
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
hitorstop(input("Do you want to hit or stop : "))
Why does the code below todo == "stop" run when i put in stop as input , it just keeps looping asking for the input again and again if i put "stop" for hitorstop() function
.................................................................................................................................................................................................................................................................................................................................................
You need to replace the line todo.lower() == ("hit" or "stop"): with todo.lower() in ("hit", "stop"): to make it work.
However, this entire condition is redundant in the first place and you can remove it.
You don't need it since you compare the input with "hit" and "stop" later, so it is useless to compare twice.
Here is the replace:
def hitorstop(todo):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
elif todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
else:
hitorstop(input("\n\nDo you want to hit or stop : "))

How would I trigger an automatic enter key press after an Input function?

choice = input(">>")
if choice.lower() == "+":
death = death0.IncreaseDeath()
elif choice.lower() == "-":
death = death0.DecreaseDeath()
elif choice.lower() == "r":
death = death0.ResetDeath()
elif choice.lower() == "q":
sys.exit()
I have this code, but its supposed to be a death counter, where the user should jus press + or - or r or q and it increments automatically, without the user needing to press enter. I tried keyboard.press_and_release('enter') and keyboard.add_hotkey('+', death = death0.IncreaseDeath()) but 2nd one doesn't work, and second one works AFTER input finishes and user presses Enter, and now its spamming enter on the input(which isnt what i want, i want the user to type one letter and then have it press Enter automatically. How would I do this to make it happen so user doesnt need to press "Enter" after the input
if msvcrt.kbhit():
key_stroke = msvcrt.getch()
if key_stroke == b'+':
death = death0.IncreaseDeath()
elif key_stroke == b'-':
death = death0.DecreaseDeath()
elif key_stroke == b'r':
death = death0.ResetDeath()
elif key_stroke == b'q':
sys.exit()
Also tried this BUT my code before which is:
def DeathCount(death,DEATH_NAME):
while True:
os.system('cls' if os.name == 'nt' else 'clear')
print ("####################")
print (f" {DEATH_NAME}: {death} ")
print ("####################")
print (" * + : increase * ")
print (" * - : decrease * ")
print (" * r : reset * ")
print (" * q : quit * ")
print ("####################")
doesn't show up and it gives no clue to the user what to press and whether its actually incrementing or not.
hope this code helps
import sys
from getkey import getkey
death0 = 15
death = death0
print(death)
while True:
print(">>")
choice = getkey()
if choice.lower() == "+":
death += 1
elif choice.lower() == "-":
death -= 1
elif choice.lower() == "r":
death = death0
elif choice.lower() == "q":
sys.exit()
else:
print("invalid input")
print(death)

Can`t exit from program

Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here
#import sys
def body_cycle(*args):
if option == "/":
error_func_for_zero(first_number, second_number, option)
print(division_option(first_number, second_number))
print()
print(begin)
def error_func_for_zero(*args):
try:
first_number / 0 or second_number / 0
except ZeroDivisionError:
print("YOU CANNOT DIVIDE BY ZERO!")
print(begin)
def division_option(*args):
return first_number / second_number
begin = " "
while begin:
print("Hello, I am calculator. ")
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")
print(body_cycle(first_number, second_number, option))
ask = " "
while ask:
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")
if exit_or_continue == "Y" or "y":
print("OK")
elif exit_or_continue == "N" or "n":
#break
ask == False
else:
print("Break program. ")
break
You just want to replace ask == False by ask = False.
In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:
def operation(a, b, option):
if option == "+":
return a + b
elif option == "-":
return a - b
elif option == "*":
return a * b
elif option == "/":
try:
return a / b
except ZeroDivsionError
return "YOU CANNOT DIVIDE BY ZERO!"
The rest can be put in a single loop instead of two, like so:
print("Hello, I am calculator. ")
while True:
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\n
Choose your option (+, -, *, /): ")
# Result.
print(operation(first_number, second_number, option))
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
Choice: ").lower()
if exit_or_continue == "y":
print("OK")
elif exit_or_continue == "n":
break

not getting output but they do not show error

import random
dict = {0:'rock',1:'Spock',2:'paper',3:'lizard',4:'scissors'}
def name_to_number(name):
if name == "rock":
return 0
elif name == "spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "csissors":
return 4
else:
print("error:wrong name!")
return
def number_to_name(number):
if number == 0:
return "rock"
elif number == 1:
return "spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print("error: wrong number!")
return
def rpsls(palyer_choice):
print(" ")
print("players chooses %s",'player_choice')
player_number = name_to_number(player_choice)
comp_number = random.randrange(0, 5)
print ("Computer chooses %s",' comp_number')
difference = player_number - comp_number
if difference == 0:
print("Player and computer tie!")
elif difference == 3 or difference ==3 or difference == -1 or difference == -2:
print ("computer wins!")
else:
print("Players wins!")
you have to call rpsls function
so add this code in the last of your code
rpsls()

How to stop this while loop?

I'm a beginner in coding and I'm making a simple rpg. I'm currently making a floor with only 4 rooms. I want the game to loop infinitely. I also want the game to prompt the player to enter a valid command when they enter an invalid command, but the while loop repeats infinitely. Can someone give me a fix that a beginner can understand, and maybe some pointers? The while loop is
while foo(move) == False:.
def foo(m):
"""
"""
if m.lower == 'l' or m.lower == 'r' or m.lower == 'help' or m.lower == 'pokemon':
return True
else:
return False
print() #Put storyline here
print("You may input 'help' to display the commands.")
print()
gamePlay = True
floor4 = ['floor 4 room 4', 'floor 4 room 3', 'floor 4 room 2', 'floor 4 room 1']
floor4feature = ['nothing here', 'nothing here', 'stairs going down', 'a Squirtle']
currentRoom = 0
pokemonGot = ['Bulbasaur']
while gamePlay == True:
print("You are on " + floor4[currentRoom] + ". You find " + floor4feature[currentRoom] + ".")
move = input("What would you like to do? ")
while foo(move) == False:
move = input("There's a time and place for everything, but not now! What would you like to do? ")
if move.lower() == 'l':
if currentRoom > 0:
currentRoom = currentRoom - 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'r':
if currentRoom < len(floor4) - 1:
currentRoom = currentRoom + 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'help':
print("Input 'r' to move right. Input 'l' to move left. Input 'pokemon' to see what Pokemon are on your team. Input 'help' to see the commands again.")
elif move.lower() == 'pokemon':
print("The Pokemon on your team are: " + str(pokemonGot) + ".")
print()
In foo you are comparing a function definition, m.lower, to a character. Try m.lower () to call the function.

Resources