In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:
import random
import copy
import sys
the_board = [" "]*10
def printboard(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 choose_player():
while True:
player = input("What do you want to be; X or O?")
if player == "X":
print("You chose X")
comp = "O"
break
elif player == "O":
print("You chose O")
comp = "X"
break
else:
print("Invalid Selection")
continue
return [player, comp]
def virtual_toss():
print("Tossing to see who goes first.....")
x = random.randint(0,1)
if x== 0:
print("AI goes first")
move = "comp"
if x == 1:
print("Human goes first")
move = "hum"
return move
def win(board,le):
if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
return True
else:
return False
def make_move(board,number,symbol):
board[number] = symbol
def board_full(board):
count = 0
for item in board:
if item in ["X","O"]:
count+= 1
if count ==9 :
return True
else:
return False
def valid_move(board,num):
if board[num] == " ":
return True
else:
return False
def player_move(board):
number = int(input("Enter the number"))
return number
def copy_board(board):
copied_board = copy.copy(board)
return copied_board
def check_corner(board):
if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
return True
else:
return False
def check_center(board):
if (board[5] == " "):
return True
else:
return False
while True:
count = 0
loop_break = 0
print("welcome to TIC TAC TOE")
pla,comp = choose_player()
turn = virtual_toss()
while True:
printboard(the_board)
if turn == "hum":
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break == 6:
continue
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
else:
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break = 6:
continue
copy_board(the_board)
for i in range(0,9):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,comp)
turn = "hum"
loop_break = 1
break
else:
continue
if loop_break = 1:
continue
if (check_corner(the_board) == True) or (check_center(the_board)==True):
for i in [7,9,1,3,5]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)==True):
make_move(the_board,i,comp)
print("The AI beat you")
loop_break = 2
count = 1
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 3
break
if loop_break == 2:
break
elif loop_break == 3:
continue
else:
for i in [8,4,6,2]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)):
make_move(the_board,i,comp)
print("The AI beat you")
count = 1
loop_break = 4
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 5
break
if loop_break == 4:
break
elif loop_break == 5:
continue
if count == 1:
again = input("Would you like to play again? y/n")
if again == "y":
continue
else:
system.exit()
I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:
Traceback (most recent call last):
File "python", line 106
if (win(the_board,pla) == True):
^
IndentationError: unindent does not match any outer indentation level
More specifically, this part of the code:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
Any help? I cannot get the code to work by any means!!
Try unindenting the previous seven lines of code by one level (the code in that while loop). This should make the indents work correctly. Also, it seems that there is an extra space before the if statement that is causing you errors. Remove this space as well. This would make that part of the code like this:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
You need to indent the block under while (True): consistently. E.g.:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
Related
This is my code below, it is saying that there is an error but i cannot understand the error (the '^' is pointing at the ':' of the elif statement):
File "", line 47
elif:
^
SyntaxError: invalid syntax
'' print ("there are 27 sticks")
sticks = 27
player1 = True
Ai = False
print ("there are 27 sticks, pick the last one !")
print("1")
print("2")
print("3")
while player1 == True:
inp = int(input("Enter the number of sticks you want to take: "))
if inp == 1:
inp = "1: 1 stick taken"
sticks = sticks -1
print (sticks)
player1 = False
Ai = True
elif inp == 2:
inp = "2 sticks taken"
sticks = sticks - 2
print (sticks)
player1 = False
Ai = True
elif inp == 3:
inp = "3 sticks taken"
sticks = sticks - 3
print (sticks)
player1 = False
Ai = True
else:
print("Invalid input!")
while Ai == True:
if sticks == 7:
InpAi = 3
sticks = sticks - InpAi
print (sticks)
player1 = True
Ai = False
elif:
print ("")
else:
''
Your if tree in the second while loop has the structure if... elif... else but the elif doesn't have a condtion. It's throwing an error because there is no condtion.
You've declared an elif without a variable to check against, you need to put something like
elif something == 'something else':
do this
while Ai == True:
if sticks == 7:
InpAi = 3
sticks = sticks - InpAi
print (sticks)
player1 = True
Ai = False
elif: # <= add condition here if any otherwise remove that line :)
print ("")
else:
''
I am trying to code a simple coinflip game with a gambling function. My issue is, whenever it runs, it doesn't update the balance variable. Any suggestions?
import random
balance = 10
win = "Congrats! You have won "
lose = "That's too bad, you lost this time! You now have "
start_game = False
while True:
choice = input("Please use one of these commands 'flip', 'balance', or 'end game'. ")
if choice == "flip":
start_game = True
break
elif choice == "balance":
print(balance)
elif choice == "end game":
break
else:
print("Please use one of the listed commands!")
if start_game == True:
while True:
result = random.randint(1,2)
if result == 1:
result = True
elif result == 2:
result = False
gamble_amount = input("How much would you like to flip? You have " + str(balance) + " coins. ")
if str(gamble_amount) == "balance":
print(balance)
elif int(gamble_amount) <= int(balance) and result == True:
int(gamble_amount) * 2
int(balance) + int(gamble_amount)
print(win + str(gamble_amount) + "!" + " You now have " + str(balance) + "!")
elif int(gamble_amount) <= int(balance) and result == False:
int(balance) - int(gamble_amount)
print(lose + str(balance) + " coins!")
I am building a Tic Tac Toe AI. Here are the rules for the AI:
If there is a winning move, play it.
If the opponent has a winning move, block it.
Otherwise, play randomly.
Here's the code:
# main.py
# Prorities:
# - If there is a winning move, play it
# - If the opponent has a winning move, block it.
# - If nothing to block, make a random move.
import random
import time
import copy
boxes = []
for i in range(3):
row = []
for j in range(3):
row.append(" ")
boxes.append(row)
def printBoard():
to_print = ""
to_print += " " + boxes[0][0] + " | " + boxes[0][1] + " | " + boxes[0][2] + " \n"
to_print += "---+---+---\n"
to_print += " " + boxes[1][0] + " | " + boxes[1][1] + " | " + boxes[1][2] + " \n"
to_print += "---+---+---\n"
to_print += " " + boxes[2][0] + " | " + boxes[2][1] + " | " + boxes[2][2] + " \n"
return to_print
turn = random.randint(1, 2)
if turn == 1:
coin = "you (X)"
else:
coin = "the AI (O)"
print("The coin flip shows", coin, "will go first!")
input("Press Enter to begin! ")
def checkWin(boxes):
win = False
who = " "
for i in range(3):
if boxes[i][0] == boxes[i][1] and boxes[i][1] == boxes[i][2]:
who = boxes[i][0]
if who != " ":
win = True
for i in range(3):
if boxes[0][i] == boxes[1][i] and boxes[2][i] == boxes[1][i]:
who = boxes[0][i]
if who != " ":
win = True
if boxes[0][0] == boxes[1][1] and boxes[1][1] == boxes[2][2]:
who = boxes[0][0]
if who != " ":
win = True
if boxes[0][2] == boxes[1][1] and boxes[1][1] == boxes[2][0]:
who = boxes[0][2]
if who != " ":
win = True
return win, who
def checkTie(boxes):
for row in boxes:
for box in boxes:
if box != "X" and box != "O":
return False
return True
def checkMove(boxes, player):
for i in range(3):
for j in range(3):
if boxes[i][j] != "X" and boxes[i][j] != "O":
boxCopy = copy.deepcopy(boxes)
boxCopy[i][j] = player
win, who = checkWin(boxCopy)
if win:
return True, i, j
return False, 0, 0
while True:
print("Check 1")
win, who = checkWin(boxes)
if win and who == "X":
print("Player X has won.")
print(" ")
print(printBoard())
break
elif win and who == "O":
print("Player O has won.")
print(" ")
print(printBoard())
break
elif checkTie(boxes) == True:
print("It has been concluded as a tie.")
break
print("Check 2")
if turn == 1:
print("")
print(printBoard())
row = (int(input("Pick a row to play: ")) -1)
col = (int(input("Pick a column to play: ")) -1)
if ((row < 4 and row > -1) and (col < 4 and col > -1)) and (boxes[row][col] == " "):
boxes[row][col] = "X"
turn = 2
else:
print("Sorry, that is not allowed.")
print(" ")
# Prorities:
# - If there is a winning move, play it
# - If the opponent has a winning move, block it.
# - If nothing to block, make a random move.
else:
print("")
print(printBoard())
print("[*] AI is choosing...")
time.sleep(1)
row = random.randint(0, 2)
col = random.randint(0, 2)
winMove, winRow, winCol = checkMove(boxes, "O")
lossMove, lossRow, lossCol = checkMove(boxes, "X")
if winMove and (boxes[winRow][winCol] != "X" and boxes[winRow][winCol] != "O"):
boxes[winRow][winCol] = "O"
turn = 1
print("Statement 1: Win play")
elif lossMove and (boxes[lossRow][lossCol] != "X" and boxes[lossRow][lossCol] != "O"):
boxes[lossRow][lossCol] = "O"
turn = 1
print("Statement 2: Block play")
elif boxes[row][col] != "X" and boxes[row][col] != "O":
boxes[row][col] = "O"
turn = 1
print("Statement 3: Random play")
else:
print("Statement 4: None")
print("Check 3")
The problem occurs when there is a tie. Either the function checkTie(), or the if statement isn't working. You might see a couple print('Check #') every once in a while. When you run the code and it's a tie, it shows all the checks going by. Which means it is passing through the check. When there is a tie, it just keeps doing the loop and repeating its turn but not making a move.
What is the mistake and how can I do this correctly?
I think your function should be
def checkTie(boxes):
for row in boxes:
for box in row:
if box != "X" and box != "O":
return False
return True
You mistyped ( I think) boxes for row in the second for statement.
def checkTie(boxes):
if any(" " in box for box in boxes):
return False
return True
Change your checkTie function to this
The rest is all good.
I am simply wondering how I can make my game of Mastermind work, more specifically how I would go about making "finish" global, how I would call these functions so that the program works correctly, and overall tips that would help enhance my code. I would also like to know how to make it so the program doesn't 'reroll' the computer-generated number every single loop. This was just a difficult problem for me and I can't seem to understand how to close it out with the correct function calls and niche aspects such as that. Thank you.
run = True
def get_guess():
while run:
guess = input("Provide four unique numbers: ")
count = 0
if len(guess) == 4:
guessdupe = guess[0] == guess[1] or guess[0] == guess[2] or guess[0] == guess[3] or guess[1] == guess[2] or guess[1] == guess[3] or guess[2] == guess[3]
else:
guessdupe = False
try:
try:
for i in range(4):
if int(guess[i]) <= 7 and int(guess[i]) >= 1 and len(guess) == 4:
count += 1
if len(guess) != 4:
print "Your guess must consist of 4 numbers!"
if guessdupe:
count -= 1
print "You can only use each number once!"
except ValueError:
print "You can only use numbers 1-7 as guesses"
except IndexError:
print "You can only use numbers 1-7 as guesses"
if count == 4:
break
return guess
def check_values(computer_list, user_list):
final_list = [''] * 4
for i in range(4):
if user_list[i] in computer_list:
if user_list[i] == computer_list[i]:
final_list[i] = "RED"
else:
final_list[i] = "WHITE"
else:
final_list[i] = "BLACK"
random.shuffle(final_list)
print final_list
return final_list
def check_win(response_list):
if response_list[0] == "RED" and response_list[1] == "RED" and response_list[2] == "RED" and response_list[3] == "RED":
print "Congratulations! You've won the game!"
global finish
finish = True
def create_comp_list():
while run:
compList = [random.randint(1, 7), random.randint(1, 7), random.randint(1, 7), random.randint(1, 7)]
listBool = compList[0] == compList[1] or compList[0] == compList[2] or compList[0] == compList[3] or compList[1] == compList[2] or compList[1] == compList[3] or compList[2] == compList[3]
if listBool:
continue
else:
return compList
def play_game():
for i in range(5):
print create_comp_list()
print get_guess()
check_win(check_values(create_comp_list(), get_guess()))
if finish:
break
play_game()```
I am making a tic-tac-toe program in python.
I have two questions:
How to create a trick to terminate the move() when we have created a diagonal or a line(xxx or OOO) in the game.
In my program some error is occurring::in line 28::(UnboundLocalError: local variable 'stop' referenced before assignment)
My code is::
import random
board = {"top-l":" ","top-m":" ","top-r":" ","mid-l":" ","mid-m":" ","mid-r":" ","low-l":" ","low-m":" ","low-r":" "}
def print_board(board):
print( board["top-l"] + "|" + board["top-m"] + "|" + board["top-r"])
print("--------")
print( board["mid-l"] + "|" + board["mid-m"] + "|" + board["mid-r"])
print("--------")
print( board["low-l"] + "|" + board["low-m"] + "|" + board["low-r"])
if random.randint(0,1) == 1:
turn = "X"#user
else:
turn = "O"# computer
def instructions():
print("TYPE top FOR TOP ROW, mid FOR MIDDLE ROW AND low FOR LOWEST ROW")
print(" ")
print("TYPE -l FOR LEFT CORNER, -m FOR MIDDLE CORNER AND -r FOR RIGHT CORNER")
print(" ")
print("SO COMMAND FOR TOP RIGHT CORNER SHOULD BE top-r ")
print("AN EMPTY BOARD LOOKS LIKE::")
print_board(board)
def move():
for i in range(10):
print_board(board)
print("CHANCE NO. " + str(i))
if turn == "O":
if i == 1:
print("COMPUTER WILL TAKE THE FIRST TURN(FOR " + turn + ")")
else:
print("IT'S COMPUTER TURN NOW")
y = random.randint(0,9)
move = str(board_list[y])
elif turn == "x":
if i == 1:
print("USER WILL TAKE THE FIRST TURN(FOR " + turn + "). PLEASE ENTER YOUR MOVE")
else:
print("IT'S USERS TURN NOW. PLEASE ENTER YOUR MOVE")
move = input()
print("STEP TAKEN IS ::" + move)
board["move"] = turn
if turn == "x":
tu = 0
turn = "O"
elif turn == "O":
tu = 1
turn = "X"
if board["top-l"] == board["top-m"] == board["top-r"] or board["mid-l"] == board["mid-m"] == board["mid-r"] or board["low-l"] == board["low-m"] == board["low-r"] or board["mid-l"] == board["top-l"] == board["low-l"] or board["mid-m"] == board["top-m"] == board["low-m"] or board["mid-r"] == board["top-r"] == board["low-r"] or board["top-l"] == board["mid-m"] == board["low-r"] or board["top-r"] == board["mid-m"] == board["low-l"]:
stop = 1
else:
stop = 0
if __name__ == "__main__":
board_list = list(board.keys())
tu = int(0)# 0 for computer
# 1 for user
stop = int(0)# 0 = continue
print("PRESENTING YOU TIC-TAC-TOE GAME v1.0 BY DK SHARAMA")
print("PLEASE ENTER YOUR NAME::")
user = str(input())
print("WELCOME " + user)
instructions()
print("TO PLAY PRESS 1 ELSE 0")
play = int(input())
if play == 1:
move()
if stop == 1:
print("GAME OVER")
if tu == 0:
print("COMPUTER WON")
elif tu == 1:
print("USER WON")
elif stop == 0:
print("IT'S A TIE :: NO ONE WON")