I had previously asked about why my counter wasn't working. So, whilst working a different project, I realised I needed a counter but couldn't find or place one that fitted my needs. (I am also well aware that this could be shortened but ignore that). The counter needs to allow only 10 questions to be asked, but I just couldn't figure out how to adapt the others that I saw.
from random import randint
import random
import math
count = 0
print("This game is a quiz to see how good you are at maths. No paper allowed!")
def Start():
print("No paper allowed nor a calculator!")
ans1 = input("Do you wish to start? \n")
if ans1 == "Yes" or ans1 == "yes" or ans1 == "Y" or ans1 == "y":
Begin(count)
if ans1 == "no" or ans1 == "No" or ans1 == "n" or ans1 == "N":
exit()
def Begin(count):
opers = ['+','-','*',"/"]
operation = random.choice(opers)
num1 = random.randint(2,21)
num2 = random.randint(2,num1)
num3 = int(eval(str(num1) + operation + str(num2)))
ans2 = int(input("What is "+str(num1) + operation + str(num2)+"? \n"))
if ans2 == num3:
print("Well done! You must be good at maths!")
Begin(count)
if ans2 != num3:
print("You are terrible at maths. Go sit in that corner. (The answer was "+str(num3)+").")
Begin(count)
def Replay():
ans3 = input("Would you like to play again? \n")
if ans3 == "Yes" or ans3 == "yes" or ans3 == "Y" or ans3 == "y":
Start()
if ans3 == "no" or ans3 == "No" or ans3 == "n" or ans3 == "N":
exit()
Start()
in Begin function add :
global counter
counter+=1
if counter == 10:
print("something...")
EDIT:
this works!
from random import randint
import random
import math
count = 0
print("This game is a quiz to see how good you are at maths. No paper allowed!")
def Start():
print("No paper allowed nor a calculator!")
ans1 = input("Do you wish to start? \n")
if ans1 == "Yes" or ans1 == "yes" or ans1 == "Y" or ans1 == "y":
Begin()
if ans1 == "no" or ans1 == "No" or ans1 == "n" or ans1 == "N":
exit()
def Begin():
global count
count+=1
if count==10:
print("finished")
exit()
opers = ['+', '-', '*', "/"]
operation = random.choice(opers)
num1 = random.randint(2
, 21)
num2 = random.randint(2, num1)
num3 = int(eval(str(num1) + operation + str(num2)))
ans2 = int(input("What is " + str(num1) + operation + str(num2) + "? \n"))
if ans2 == num3:
print("Well done! You must be good at maths!")
Begin()
if ans2 != num3:
print("You are terrible at maths. Go sit in that corner. (The answer was " + str(num3) + ").")
Begin()
def Replay():
ans3 = input("Would you like to play again? \n")
if ans3 == "Yes" or ans3 == "yes" or ans3 == "Y" or ans3 == "y":
Start()
if ans3 == "no" or ans3 == "No" or ans3 == "n" or ans3 == "N":
exit()
Start()
Related
I just have a small issue with my code
I defined my response = ""
I tried to make it so that it would bring me back to my shop menu!!
But it is not working!
Could someone please be kind enough to fix this entire code for me?
Thank you so much!!!!!
My code:
CharacterHealth = 100
import time
Coins = 1000
Sword = ["Diamond", "Metal", "Wood"]
Shop = ["Shop"]
print("Hello! Welcome to my game! This is an extremely fun action game! I hope you enjoy!\n")
time.sleep(2)
name = input("Please enter your username.\nUsername: \033[1;32;40m")
print("\033[1;37;40mHello, " + name + ". Would you like to enter a shop?\nYou can purchase
swords!\n")
time.sleep(2)
response = ""
while response not in Shop:
response = input("Would you like to enter the shop?(yes/no)\nSelection: \033[1;32;40m")
if (response == "Yes") or (response == "yes"):
answer = input("\n\033[1;37;40mYou have 1000 coins. Would you like to buy:\n(a) Diamond sword
[Costs 900]\n(b) Metal Sword [500]\n(c) Wooden sword [200]\n(d) Back\nSelection: \033[1;32;40m")
if (answer == "A") or (answer == "a"):
Coins = 1000 - 900
response = input(name + "\033[1;37;40m, you currently have " + str(Coins) + " Coins!")
response = ""
if (answer == "B") or (answer == "b"):
Coins = 1000 - 500
response = input(name + "\033[1;37;40m, you currently have " + str(Coins) + " Coins!")
response = ""
if (answer == "C") or (answer == "c"):
Coins = 1000 - 200
response = input(name + "\033[1;37;40m, you currently have " + str(Coins) + " Coins!")
response = ""
if (answer == "D") or (answer == "d"):
print("You exit the shop.\n")
time.sleep(2)
response = ""
if (response == "No") or (response == "no"):
print("You exit the shop.")
print("You enter your house.")
Thank you guys so much! I hope one of you could fix my code!!
(You can paste it into replit.com or pycharm to fix it)
instead of
if (response == "Yes") or (response == "yes"):
you should go:
response= response.lower()
if(response == "yes"):
Because if user answers YES, Yes, yEs an so on your program will get confused and less errors when you forgot something
I hope that can help you and give you a appropriate start for further coding. If you need any explanation donĀ“t hesitate to ask.
You should consider that you add a routine that you cannot buy more swords if you ran out of coins.
import time
def coins_left(player_name, coins):
print(player_name + "\033[1;37;40m, you currently have " + str(coins) + " Coins!")
def exit_shop_house():
print("You exit the shop.\n")
print("You enter your house.")
CharacterHealth = 100
Coins = 1000
Sword = ["Diamond", "Metal", "Wood"]
Shop = ["Shop"]
print("Hello! Welcome to my game! This is an extremely fun action game! I hope you enjoy!\n")
time.sleep(2)
name = input("Please enter your username.\nUsername: \033[1;32;40m")
print("\033[1;37;40mHello, " + name + ". Would you like to enter a shop?\nYou can purchase swords!\n")
time.sleep(2)
response = input("Would you like to enter the shop?(yes/no)\nSelection: \033[1;32;40m")
if (response == "Yes") or (response == "yes"):
while True:
answer = input("\n\033[1;37;40mYou have %s coins. Would you like to buy:\n(a) Diamond sword [Costs 900]\n(b) Metal Sword[500]\n(c) Wooden sword[200]\n(d) Back\nSelection: \033[1; 32; 40 m" % Coins)
if (answer == "A") or (answer == "a"):
Coins -= 900
coins_left(name, Coins)
elif (answer == "B") or (answer == "b"):
Coins -= 500
coins_left(name, Coins)
elif (answer == "C") or (answer == "c"):
Coins -= 200
coins_left(name, Coins)
elif (answer == "D") or (answer == "d"):
exit_shop_house()
time.sleep(2)
break
else:
exit_shop_house()
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!!
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)
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 :(")
I am trying to create a program that lets the user choose to play rock, paper or scissors. Once they choose what they want to play and the amount of games that they want to play, they will be told if they won or lost.
I want to tally up the amount of times they won or lost, but instead it just prints after each round. Is there a way that I can make it print after the game is completed? I want to show the user the outcome overall at the end
from random import randint
def main():
games = int(input("How many games would you like to play?"))
while games > 0:
games -= 1
comp = computer()
choice = user()
print("You played", choice, "and the computer played", comp)
winner(comp, choice)
def computer():
comp = randint in range (0,3)
if comp == 0:
comp = 'rock'
elif comp == 1:
comp = 'paper'
elif comp == 2:
comp = 'scissors'
return comp
def user():
choice = int(input("choose 0 for rock, 1 for paper, or 2 for scissors: "))
if choice == 0:
choice = 'rock'
elif choice == 1:
choice = 'paper'
elif choice == 2:
choice = 'scissors'
else:
print("invalid input")
return choice
def winner(comp, choice):
tie = 0
win = 0
lose = 0
while True:
if choice == "rock" and comp == "rock":
result = 'tie'
tie += 1
break
elif choice == 'rock'and comp == 'scissors':
result = "you win"
win += 1
break
elif choice == 'rock' and comp == 'paper':
result = "you lose"
lose += 1
break
elif choice == 'paper' and comp == 'paper':
result = 'tie'
tie += 1
break
elif choice == 'paper' and comp == 'scissors':
result = 'you lose'
lose += 1
break
elif choice == 'paper' and comp == 'rock':
result = 'you win'
win =+ 1
break
elif choice == 'scissors' and comp == 'scissors':
result = 'tie'
tie += 1
break
elif choice == 'scissors' and comp == 'paper':
result = 'you win'
win += 1
break
elif choice == 'scissors' and comp == 'rock':
result = 'you lose'
lose +=1
break
else:
print("error")
break
print(result)
print("you won", win,"times, and lost", lose,"times, and tied", tie,"times.")
main()
Declare globals for the win, lose and tie counters
randint(0, 2) is how you get random integer
It's += and not =+
There are couple of mistakes. I added a comment # CORRECTION at the respective lines.
from random import randint
tie = 0
win = 0
lose = 0
def main():
games = int(input("How many games would you like to play?"))
while games > 0:
games -= 1
comp = computer()
choice = user()
print("You played", choice, "and the computer played", comp)
winner(comp, choice)
def computer():
# CORRECTION: randint in range (0,3) always return FALSE. BELOW IS THE CORRECT WAY
comp = randint(0, 2)
if comp == 0:
comp = 'rock'
elif comp == 1:
comp = 'paper'
elif comp == 2:
comp = 'scissors'
return comp
def user():
choice = int(input("choose 0 for rock, 1 for paper, or 2 for scissors: "))
if choice == 0:
choice = 'rock'
elif choice == 1:
choice = 'paper'
elif choice == 2:
choice = 'scissors'
else:
print("invalid input")
return choice
def winner(comp, choice):
# CORRECTION: MAKE ALL THE COUNTERS GLOBAL
global tie
global win
global lose
while True:
if choice == "rock" and comp == "rock":
result = 'tie'
tie += 1
break
elif choice == 'rock'and comp == 'scissors':
result = "you win"
win += 1
break
elif choice == 'rock' and comp == 'paper':
result = "you lose"
lose += 1
break
elif choice == 'paper' and comp == 'paper':
result = 'tie'
tie += 1
break
elif choice == 'paper' and comp == 'scissors':
result = 'you lose'
lose += 1
break
elif choice == 'paper' and comp == 'rock':
result = 'you win'
# CORRECTION: ITS NOT =+ ITS +=
# win =+ 1
win += 1
break
elif choice == 'scissors' and comp == 'scissors':
result = 'tie'
tie += 1
break
elif choice == 'scissors' and comp == 'paper':
result = 'you win'
win += 1
break
elif choice == 'scissors' and comp == 'rock':
result = 'you lose'
lose +=1
break
else:
print("error")
break
print(result)
main()
print("you won", win,"times, and lost", lose,"times, and tied", tie,"times.")