I am building a tic-tac-toe. I have almost finished it but I cannot break the while loop in the end. I have turned win into True. But the if statement in the while loop is not working.
board = [[1,2,3],[4,"X",6],[7,8,9]]
win = False
def DisplayBoard(board):
def printborder():
print("+-------+-------+-------+")
def printline():
print("| | | |")
def printitem(board,row):
print("| ",board[row][0]," | ",board[row][1]," | ",board[row][2]," |", sep="")
printborder()
printline()
printitem(board,0)
printline()
printborder()
printline()
printitem(board,1)
printline()
printborder()
printline()
printitem(board,2)
printline()
printborder()
def EnterMove(board):
while True:
move = int(input("Enter your move: "))
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==move:
board[i][j]="O"
return None
def MakeListOfFreeFields(board):
freefield = []
for i in range(len(board)):
for j in range(len(board[i])):
for k in range(1,10):
if board[i][j] == k:
freefield.insert(0,k)
return freefield
def VictoryFor(board, sign):
def whowin(sign):
if sign == "O":
print("Player wins.")
win = True
elif sign == "X":
print("Computer wins.")
win = True
def checkvertical(board):
for i in range(3):
if board[0][i]==board[1][i]==board[2][i]:
whowin(sign)
def checkhorizontal(board):
for i in range(3):
if board[i][0]==board[i][1]==board[i][2]:
whowin(sign)
def checkdiagonal(board):
if board[0][0]==board[1][1]==board[2][2] or board[0][2]==board[1][1]==board[2][0]:
whowin(sign)
checkvertical(board)
checkhorizontal(board)
checkdiagonal(board)
def DrawMove(board):
from random import randrange
while True:
ran = randrange(1,10)
if ran in MakeListOfFreeFields(board):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==ran:
board[i][j]="X"
return None
DisplayBoard(board)
while True:
EnterMove(board)
DisplayBoard(board)
VictoryFor(board, "O")
if win==True:
break
DrawMove(board)
DisplayBoard(board)
VictoryFor(board, "X")
if win==True:
break
print("ended")
fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
In your whowin function (inside of VictoryFor) you simply create a local win variable. If you want to refer to the global one, you need to tell Python to do so:
def whowin(sign):
global win # <---- add this
if sign == "O":
print("Player wins.")
win = True
elif sign == "X":
print("Computer wins.")
win = True
Related
So here is my code:
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()
My output is:
Click 1 for attack
Click 2 for shield
:1
Krotos: 75
Sephiroth: 75
Click 1 for attack
Click 2 for shield
:
How can I get rid of the first three lines so it only shows the newest information? Any new ideas would be useful. I have tried using google but I can't find anything.
Try this below :
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def clear():
import os
os.system("clear") # Linux
os.system("cls") # Windows
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
clear() # -------------> Call clear function after your input
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()
You can clear the console after every attack:
import os
os.system("cls") #windows
os.system("clear") #linux
Its showing"line 42, in
if input_ !='no':
NameError: name 'input_' is not defined" error when i input 'no'
The code is :
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
input_=input(y+z+"?")
if input_ == "no":
return
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
How can i rectify it? (this is just a small part of the entire program but i think this should do...)
Variable input_ is initialised inside function rock_paper_scissors() which means outside of it (function scope) is undefined. So we need to put it inside function or make input_ global.
def rock_paper_scissors():
comp_score = your_score = 0
y, z = "This is a rock paper scissors game. ", "Do you wish to play"
x= ["rock", "paper", "scissors"]
input_=input(y + z + "?")
if input_ == "no":
return
else: # no need for: if input_ != "no"
a = input("Do you wanna play again?")
rock_paper_scissors()
Hope this helps.
Here is my take on it, still needs some work, it functional...
# Tested via Python 3.7.4 - 64bit, Windows 10
# Author: Dean Van Greunen
# License: I dont care, do what you want
####################################
# Some Defines
####################################
# imports
import random
# global vars
comp_score = 0
your_score = 0
input_ = ''
ai_input = ''
# strings
string_1 = 'This is a rockpaper scissors game.'
question_1 = 'Do you wish to play? '
question_2 = 'Enter your move: '
question_3 = 'Do you wanna play again? '
string_4 = 'Valid Moves: '
string_5 = 'Thank you for playing!'
string_6 = 'Scores: Player {0} V.S. AI {1}'
yes = 'yes'
no = 'no'
# vaild moves
moves = ["rock","paper","scissors"]
####################################
# Code Setup
####################################
def displayWinner(player_move_str, ai_move_str):
# Vars
winner = ''
tie = False
# Winner Logic
if player_move_str == ai_move_str:
tie = True
elif player_move_str == 'paper' and ai_move_str == 'rock':
winner = 'Player'
elif player_move_str == 'scissor' and ai_move_str == 'rock':
winner = 'AI'
elif player_move_str == 'rock' and ai_move_str == 'paper':
winner = 'AI'
elif player_move_str == 'scissor' and ai_move_str == 'paper':
winner = 'Player'
elif player_move_str == 'rock' and ai_move_str == 'scissor':
winner = 'Player'
elif player_move_str == 'paper' and ai_move_str == 'scissor':
winner = 'AI'
# display Logic
if tie:
print('It Was A Tie!')
else:
global your_score
global comp_score
if winner == 'AI':
comp_score = comp_score + 1
elif winner == 'Player':
your_score = your_score + 1
print(winner + ' Won!')
def start():
global your_score
global comp_score
print(string_1)
print(string_6.format(your_score, comp_score))
input_ = input(question_1)
if input_ == yes:
print(string_4)
[print(x) for x in moves]# make sure input is valid.
input_ = input(question_2)
ai_input = random.choice(moves) # let AI pick move
print('AI Picked: ' + ai_input)
displayWinner(input_, ai_input)
input_ = input(question_3) # Play Again?
if input_ == yes:
start() # Restart Game (Recursive Call)
else:
print(string_5) # Thank you Message
####################################
# Game/Script Entry Point/Function
####################################
start()
Thanks yall. Fixed my program. Now it goes like:
import time
import random
input_ =""
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
global input_
input_=input(y+z+"?")
if input_ == "no":
return
max_score=("Enter max score : ")
while True:
input_=input("Enter your choice among rock, paper and scissors ('stop' to
quit):")
if input_ not in x and input_!='stop'and input_ != 'enough':
print("Invalid answer. Are you blind? Pick one from the 3.")
continue
n = random.randint(0,2)
k=x[n]
if n<2:
if input_==x[n+1]:
your_score+=1
elif input_==k:
pass
else:
comp_score+=1
else:
if input_=="paper":
comp_score+=1
elif input_=="rock":
your_score+=1
elif input_=="scissors":
pass
else:
pass
if input_!="stop" and input_ != "enough":
print(3)
time.sleep(1.5)
print(2)
time.sleep(1.5)
print(1)
time.sleep(1.5)
print("Your choice : "+input_ +"\nComputers move : "+k)
elif input_=="stop" and input_=="enough":
input_=input("Play again?")
if (your_score == max_score or comp_score==max_score) or (input_=="stop"
or input_=="enough"):
print("Your score is : ",your_score)
print("AI's score is : ",comp_score)
break
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
if a =="yes":
rock_paper_scissors()
print("k.bye! \n :(")
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
play_func()
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append()
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
I think the problem is here:
besides from no
if secret_word[x] == guess:
guess_word[x] == guess
print(guess_word)
if not '-' in guess_word:
print('You Won!')
break
else:
print('The letter is not in the word. Try Again!')
guess_taken += 1
if guess_taken == 8:
print('You Lost, the secret word was: ', secret_word)
change()
guessing()
print('Game Over!')
if secret_word[x] == guess:
guess_word[x] == guess
I think the problem is on these lines of code because they don't actually replace guess_word
This should hopefully get you on the right track. I just created a new method/function to contain all of your other functions, and fixed the append statement. Good Luck!
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def main():
play_func()
change()
guessing()
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append(guess)
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
print(x)
main()
This code does not run. It fails during the run(gate) function. The first error I get is from the .__name__ call. This isn't my main issue, so I'm not particularly worried about this error yet
The second error I get is in the last line of run(gate). The error message says gate is not callable.
I believe my actual issue is with the structure of my program. Am I misunderstanding (or misapplying) some object-oriented principles? I would appreciate it if somebody could provide an example or a correction to my code for a better way of structuring it. Thank you!
main.py
import builtins
import logic
print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
run(logic.andGate)
elif(int(logicGate) == 2):
run(logic.nandGate)
elif(int(logicGate) == 3):
run(logic.orGate)
elif(int(logicGate) == 4):
run(logic.norGate)
elif(logicGate.lower() == 'q'):
prog = 'n'
else:
print("Invalid input. Please try again")
def toBool(s):
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError
def run(gate):
print(gate.__name__ + " Gate function")
print("Enter value for 'a'")
valA = input()
print("Enter value for 'b'")
valB = input()
print("Result: " + str(gate(toBool(valA), toBool(valB))))
And logic.py
def andGate(a, b):
if(a and b):
return True
else:
return False
def nandGate(a,b):
if(a and b):
return False
else:
return True
def orGate(a, b):
if(a or b):
return True
else:
return False
def norGate(a, b):
if(a or b):
return False
else:
return True
move your defs under imports and just remove the else: raise.... etc ect part... itnot used correctly.
import builtins
import logic
def toBool(s):
if s == 'True':
return True
elif s == 'False':
return False
def run(gate):
print(gate.__name__ + " Gate function")
print("Enter value for 'a'")
valA = input()
print("Enter value for 'b'")
valB = input()
print("Result: " + str(gate(toBool(valA), toBool(valB))))
print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
run(logic.andGate)
elif(int(logicGate) == 2):
run(logic.nandGate)
elif(int(logicGate) == 3):
run(logic.orGate)
elif(int(logicGate) == 4):
run(logic.norGate)
elif(logicGate.lower() == 'q'):
prog = 'n'
else:
print("Invalid input. Please try again")
Everything is running smoothly up until the while loop breaks and the else statement runs and asks the players if they want to play again.
else:
if input("Do you want to play again? Type Yes or No: ").lower() != 'no':
game_tic()
When I call game_tic() again the board doesn't refresh. The old moves are still displaying. I thought if I call the game_tic() the game was suppose to restart fresh.
Please check out my code:
import os
x_moves = [None, None, None, None, None, None, None, None, None]
o_moves = [None, None, None, None, None, None, None, None, None]
numeros= [1,2,3,
4,5,6,
7,8,9]
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def draw_map_choices():
print("#" * 7)
tile = "|{}"
both_set = set(x_moves) | set(o_moves)
for num in numeros:
if num in both_set:
if num == 3:
if num in x_moves:
print(tile.format("X") + '|', end='\n')
else:
print(tile.format("O") + '|', end='\n')
elif num == 6:
if num in x_moves:
print(tile.format("X") + '|', end='\n')
else:
print(tile.format("O") + '|', end='\n')
elif num == 9:
if num in x_moves:
print(tile.format("X") + '|', end='\n')
else:
print(tile.format("O") + '|', end='\n')
print("#" * 7)
else:
if num in x_moves:
print(tile.format("X"), end='')
else:
print(tile.format("O"), end='')
else:
if num == 3:
print(tile.format(num)+'|',end='\n')
elif num == 6:
print(tile.format(num) + '|', end='\n')
elif num == 9:
print(tile.format(num) + '|')
print("#" * 7)
else:
print(tile.format(num),end="")
def return_open():
return sorted(set(numeros) - (set(x_moves) | set(o_moves)))
def player_X():
clear_screen()
draw_map_choices()
print("You can pick from the following number positions: {}.\n".format(", ".join(str(x) for x in return_open())))
x = int(input("Player X's turn: "))
if x not in x_moves and x not in o_moves:
x_moves[x-1] = x
else:
print("Pick a location that is open")
def player_O():
clear_screen()
draw_map_choices()
print("You can pick from the following number positions: {}.\n".format(", ".join(str(x) for x in return_open())))
o = int(input("Player O's turn: "))
if o not in o_moves and o not in x_moves:
o_moves[o-1] = o
else:
print("Pick a location that is open")
def check_if_won(xo_list):
#Horizontal MAtch
for n in range(0, 9, 3):
if (numeros[n], numeros[n+1], numeros[n+2]) == (xo_list[n], xo_list[n+1], xo_list[n+2]):
return True
# Vertical MAtch
for n in range(0, 3):
if(numeros[n],numeros[n+3], numeros[n+6]) == (xo_list[n], xo_list[n+3], xo_list[n+6]):
return True
#Diagonal Check
if (numeros[0], numeros[4], numeros[8]) == (xo_list[0], xo_list[4], xo_list[8]):
return True
if (numeros[2], numeros[4], numeros[6]) == (xo_list[2], xo_list[4], xo_list[6]):
return True
else:
return False
def game_tic():
juego = True
num_turn = 1
while juego:
player_X()
if check_if_won(x_moves):
clear_screen()
draw_map_choices()
print("Player X Won! Congratulations!\n")
juego = False
elif num_turn == 5:
clear_screen()
draw_map_choices()
print("Is a DRAW!\n")
juego = False
if juego:
player_O()
if check_if_won(o_moves):
clear_screen()
draw_map_choices()
print("Player O Won! Congratulations!\n")
juego = False
num_turn += 1
else:
if input("Do you want to play again? Type Yes or No: ").lower() != 'no':
game_tic()
clear_screen()
print("Let's Start Our Game of Tic Toc Toe!")
input("Press ENTER when you are ready!")
game_tic()
A quick solution would be to reset x_moves and o_moves in game_tic(), like this:
def game_tic():
juego = True
num_turn = 1
global x_moves, o_moves
x_moves = [None for i in range(0, 9)]
o_moves = [None for i in range(0, 9)]
...