Making Mastermind in Python - python

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()```

Related

How to make a function to score a Rock, Paper and Scissor game in Python?

I wrote a Rock, Paper and Scissor game in Python. And I want to have a function that scores the game. The only way I managed to do that was by using global variables inside the function. I know that's not a good practice and I'd like to know how can I make this function without the need for global variables.
import random
def validate_user_input(input):
"""Verify if user input is a valid."""
try:
usr_input = int(input)
except:
return 0
else:
if (usr_input >= 1) and (usr_input <= 3):
return usr_input
else:
return 0
def compare_results(player_choice):
"""Get computer choice and compare it with user choice"""
computer_option = random.randint(1,3)
result_to_word = {0:'- Draw', 1:'- You loose.', 2:'- You Win'}
if player_choice == computer_option:
result = 0
if (player_choice == 1 and computer_option == 2):
result = 1
if (player_choice == 1 and computer_option == 3):
result = 2
if (player_choice == 2 and computer_option == 1):
result = 2
if (player_choice == 2 and computer_option == 3):
result = 1
if (player_choice == 3 and computer_option == 1):
result = 1
if (player_choice == 3 and computer_option == 2):
result = 2
return (result, result_to_word[result], computer_option)
def codify_result(input):
"Transform number of choice into word"
num_to_word = {1: "Rock", 2: "Paper", 3:"Scissor"}
return num_to_word[input]
def make_score(result):
global computer_score
global player_score
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
player_score = 0
computer_score = 0
intro = "\nHello!\nLet's play 'Rock, Paper and Scissors'.\nChoose an option and wait to see the result (Press 'q' at any time to exit)"
print(intro)
while True:
user_input = input("\n1) Rock, 2) Paper os 3) Scissors?: ")
if (user_input == 'q'):
break
else:
user_choice = validate_user_input(user_input)
if user_choice == 0:
print("You have to choose a number between 1 and 3.")
else:
result = compare_results(user_choice)
print("You chose: " + codify_result(user_choice) + ".")
print("The computer chose: " + codify_result(result[2]) + '.')
print(result[1])
make_score(result[0])
print("You: " + str(player_score) + "\nComputer: " + str(computer_score))
So how could I implement this function in a better way?
A "pure functional" approach could be to change your make_score function to take the old scores as arguments, and then return the updated scores:
def make_score(result, computer_score, player_score):
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
return computer_score, player_score
When you call make_score you pass the old scores and assign the new scores:
computer_score, player_score = make_score(result[0], computer_score, player_score)
Taking a step back, though, I might suggest taking an approach that doesn't require you to have a function that translates an opaque result int value into a modification to one or another variable. Maybe put the scores in a dict:
scores = {
"computer": 0,
"player": 0,
}
and then instead of a magic result int, assign a winner that matches one of the dict keys:
if (player_choice == 1 and computer_option == 2):
winner = "computer"
and then you can get rid of the make_score function completely and just do:
scores[winner] += 1
I would recommend making a dictionary which you can then pass into make_score
score_dict = {'computer_score': 0, 'player_score': 0}
make_score(score_dict, result):
if result == 1:
score_dict['computer_score'] += 1
...

Python - How to return to previous function after calling another function?

Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()

I can't count the number of tries in this game in pythin

I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue

Avoid a recurring loop that repeats an instruction every time it reaches the end

My problem is, my rock, paper, scissors program seems trapped in a loop somewhere. I suspect it's either the inner loop that asks the user for the number of rounds, or the outer loop that asks the user how many players should play; both might even have indentation problems but I am not sure.
import random
from os import system, name
from time import sleep
#variable declarations and initializations
computer,players, rounds, wins, loses, draws, yourPlay, count, rec, playerRange = 0, 0, 0, 0, 0, 0, 0, 0, 0, 3
#function definitions
def RoundsWonResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[yourPlay] + " beats " + playerMoves[computer] +"!")
print ("You win!")
return
def RoundsLostResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[computer] + " beats " + playerMoves[yourPlay] +"!")
print ("You lose!")
return
def DrawMatch():
global draws
while (yourPlay == computer):
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print ("It's a draw!")
draws+=1
return
def WinsMatch():
global wins
while (yourPlay != computer):
if (yourPlay == 0 and computer != 1):
if (computer == 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 1 and computer == 0):
if (computer != 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 2 and computer != 0):
if (computer == 1):
RoundsWonResult()
wins+=1
return
def LosesMatch():
global loses
while (yourPlay != computer):
if (yourPlay == 0 and computer == 1):
if (computer != 2):
RoundsLostResult()
loses+=1
elif (yourPlay == 1 and computer == 2):
if (computer != 0):
RoundsLostResult()
loses+=1
elif (yourPlay == 2 and computer == 0):
if (computer != 1):
RoundsLostResult()
loses+=1
return
try:
players = int(input("Enter number of players[1-3]:"))
while (players < 1 or players > playerRange):
print ("Invalid range selected!")
players = int(input("Enter number of players[1-3]:"))
except ValueError:
print ("Only numeric values are allowed!")
players = int(input("Enter number of players[1-3]:"))
if (players > 0 and players <= 3):
print ("Good luck to all " + str(players) + " of you. May the better player win!")
while (rec < players):
try:
rounds = int (input("Enter number of rounds to play:"))
while (rounds <= 0):
print ("Value must be greater than zero!")
rounds = int (input("Enter number of rounds to play:"))
print(rec)
print(rounds)
except ValueError:
print ("Only numeric values are allowed!")
rounds = int (input("Enter number of rounds to play:"))
if (rounds != "" and rounds > 0):
print ("Let the games begin!")
else:
print ("Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. Good Luck!")
print("You entered " + str(rounds) + " round(s)!")
playerMoves = ["Rock","Paper","Scissors"]
while (count < rounds):
try:
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
while (yourPlay < 0 or yourPlay > 2):
print ("Invalid selection!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
except ValueError:
print ("Only numeric values are allowed!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
else:
computer = random.randint(0,2) #randomizes the numbers 0 - 2
if (yourPlay == computer):
DrawMatch()
elif (yourPlay != computer):
WinsMatch()
LosesMatch()
count+=1
print ("End of Round ", count)
if (count == rounds):
print ("Wins:",wins)
print ("Loses:",loses)
print ("Draws:",draws)
#resultLog = {"Wins":wins,"Loses":loses,"Draws":draws}
fileName = input("Enter Your name: ")
#print (resultLog)
with open (fileName,"w") as plyrRec:
print ("Your file has been created!")
plyrRec.close()
with open (fileName, "a") as plyrRec:
plyrRec.write ("{}{}\n{}{}\n{}{}\n".format("Wins:",wins,"Loses:",loses,"Draws:",draws))
plyrRec.close()
rec+=1
print ("End of Record ", rec)
So the code works fairly well except that at the end of the first round it repeatedly asks the user to enter number of rounds to play. I hope someone can advise me please.
#Date first created: September 6, 2018 v.0
#Version: v.1, modified 2021/08/31
#This is a Rock, Paper, Scissors game.
#Rock beats scissors, scissors beats paper, and paper beats rock.
import random
#variable declaration and initialization
game_moves = ["Rock","Paper","Scissors"]
def is_input_numeric(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY numeric values greater than zero
>>> is_input_numeric('4')
True
>>> is_input_numeric("like 7")
False
'''
return str_val.isnumeric() and int(str_val) > 0 and int(str_val) <= 20
def is_input_numeric_range(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY a numeric value greater than zero but less than
or equal to two
>>> is_input_numeric_range('y')
False
>>> is_input_numeric_range('3')
False
>>> is_input_numeric_range('2')
True
'''
return str_val.isnumeric() and int(str_val) >= 0 and int(str_val) <= 2
def validate_rounds():
'''(string) -> string
checks str_val and passes control to is_input_numeric function, then returns a string value
>>> validate_rounds() -> is_input_numeric("time")
False
>>> validate_rounds() -> is_input_numeric('0')
False
>>> validate_rounds()-> is_input_numeric('10')
True
'''
valid_rounds = False
while not valid_rounds:
rounds = input("Enter number of rounds to play[min = 1, max = 20]: ")
valid_rounds = is_input_numeric(rounds)
return rounds
def validate_player_input():
'''(string) -> string
checks string and passes control to is_input_numeric_range function, then returns the string value
>>> validate_player_input() -> is_input_numeric_range('-1')
False
>>> validate_player_input() -> is_input_numeric_range('i')
False
>>> validate_player_input() -> is_input_numeric_range('3')
False
>>> validate_player_input() -> is_input_numeric_range('0')
True
'''
valid_player_control = False
while not valid_player_control:
player_move = input("ONLY (0)Rock,(1)Paper,(2)Scissors, allowed: ")
valid_player_control = is_input_numeric_range(player_move)
return player_move
def get_computer_play():
'''Returns a whole number in the range 0:2
'''
computer_move = random.randint(0,2)
return computer_move
def human_player_wins(plyr, comp):
wins = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 2:
rock_beats_scissors = True
elif human_hand == 1 and computer_hand == 0:
paper_beats_rock = True
elif human_hand == 2 and computer_hand == 1:
scissors_beats_paper = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[human_hand] + " beats " + game_moves[computer_hand] + "!")
print("You Win!")
wins += 1
return wins
def human_player_lose(plyr, comp):
lose = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 1:
paper_beats_rock = True
elif human_hand == 1 and computer_hand == 2:
scissors_beats_paper = True
elif human_hand == 2 and computer_hand == 0:
rock_beats_scissors = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[computer_hand] + " beats " + game_moves[human_hand] + "!")
print("You Lose!")
lose += 1
return lose
def players_draw():
draws = 0
print("It's a draw!")
draws += 1
return draws
def start_game():
rounds_played = 0
total_wins = 0
total_losses = 0
total_draws = 0
highest_score = 0
game_rounds = input("Enter number of rounds to play[Max = 20]: ")
rounds_valid = is_input_numeric(game_rounds)
if not rounds_valid:
game_rounds = validate_rounds()
while rounds_played < int(game_rounds):
player_hand = input("(0)Rock,(1)Paper,(2)Scissors: ")
valid_control = is_input_numeric_range(player_hand)
print('plyr:', player_hand)
if not valid_control:
player_hand = validate_player_input()
computer_hand = get_computer_play()
print('comp:', computer_hand)
if int(player_hand) == computer_hand:
total_draws += players_draw()
if int(player_hand) != computer_hand:
total_wins += human_player_wins(int(player_hand),computer_hand)
total_losses += human_player_lose(int(player_hand),computer_hand)
rounds_played += 1
if total_wins > highest_score:
highest_score = total_wins * 10
print('\n--------------------------GAME RESULTS--------------------------')
print('\nHigh Score = ', highest_score )
print('\nrounds played = ', rounds_played, '||','wins = ', total_wins,'||', 'losses = ', total_losses, '||','draws = ', total_draws )
print('\n--------------------------END OF RESULTS------------------------')
start_game()
Thanks to those who tried to helped me it was appreciated. This is the new version now after four years. Yikes!

Python 3 IndentationError

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

Categories

Resources