Game of Chance in Python 3.x? - python

I have this problem in my python code which is a coinflip game, the problem is that when It asks, "Heads or Tails?" and I just say 1 or Heads(same for 2 and Tails) without quotation marks and with quotation marks, it does not give me an answer that I am looking for.
I've Tried using quotation marks in my answer which didn't seem to work either.
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails?")
coinnum = random.randint(1, 2)
if coinnum == 1:
return 1
elif coinnum == 2:
return 2
win = bet*2
if choice == "Heads" or "1":
return 1
elif choice == "Tails" or "2":
return 2
if choice == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
elif choice != coinnum:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
The expected output was either "Well done! You have won 200 Dollars!" or "Sorry, you lost 100 Dollars!"

The first thing to note here is that your usage of return seems to be wrong. Please look up tutorials about how to write a function and how to use return.
I think this is what you were trying to do:
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails? ")
coinnum = random.randint(1, 2)
win = bet*2
if choice == "Heads" or choice == "1":
choicenum = 1
elif choice == "Tails" or choice == "2":
choicenum = 2
else:
raise ValueError("Invalid choice: " + choice)
if choicenum == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
else:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
Now, lets go through the mistakes I found in your code:
return was totally out of place, I wasn't sure what you were intending here.
if choice == "Heads" or "1" is invalid, "1" always evaluates to true. Correct is: if choice == "Heads" or choice == "1":
elif choice != coinnum: is unnecessary, if it doesn't run into if choice == coinnum: a simple else: would suffice.

Related

Have couple mistakes in python with while and elif statements

from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break

I created a guessing game and I can't understand why my -= command function doesn't work

I'm a very new programmer(started less than a month ago). I really need some help with this.
Sorry if it's a bit long...
How this works is that my guesses go down every time I get something wrong(pretty obvious). Or it is supposed to, anyway.
This is a program I created as a prototype for a hangman project. Once I get this right, I'll be able to attempt the bigger project. Tell me if the full command above works differently for you or if you have any suggestion as to how to make it shorter or better or it's too early for me to attempt a project as big as this. Thank you!
import random
player_name = input("What is your name? ")
print("Good luck, " + player_name + "!")
words = ["program", "giraffe", "python", "lesson", "rainbows", "unicorns", "keys", "exercise"]
guess = " "
repeat = True
word = random.choice(words)
guesses = int(len(word))
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
the issue is with the scope of your conditionals
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
this will fix the guesses issue, but you'll need to refactor the play-again logic.
Something like this
repeat = True
gameOver = False
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
gameOver = True
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
gameOver = True
if gameOver:
playAgain = input("Do you want to play again? (input Yes/No)")
if playAgain == "Yes" or "yes":
word = random.choice(words)
repeat = True
gameOver = False
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False

Python add a time limit and check whether they have acted

I recently started learning python in school as my first language and received a homework task asking us to create a simple rock paper scissors game but with a twist (mine's an RPG) and I thought it would be good if I made it so you would have to answer withing a time limit. I checked a few other threads, but I wasn't sure how to implement that code into my program, so I decided to ask here. I'm very new to python so any simple answers would be preferred if possible.
Thank you advance!
EDIT: tomh1012 gave some advice and I took it but my timer still does not work. There isnt any error on anything, it simply does not work! Any help is greatly appreciated. Also, for whatever reason, my teacher hasn't taught us functions yet so I don't really understand them much.
while keepPlaying == "y":
while playerHealth > 0 and cpuHealth > 0:
time.sleep(0.75)
print ("You have " + str(playerHealth) + " health.")
print ("The enemy has " + str(cpuHealth) + " health.")
print ("Rock")
time.sleep(0.75)
print ("Paper")
time.sleep(0.75)
print("Scissors")
time.sleep(0.75)
startTime=time.process_time()
playerChoice = input ("Shoot!")
endTime=time.process_time()
elapsedTime = startTime - endTime
cpuChoice = (random.choice(options))
time.sleep(0.75)
print ("Your opponent chose " + cpuChoice)
if elapsedTime > 300:
print("You're too slow!")
elif playerChoice == "r" and cpuChoice == "s" or playerChoice == "p" and cpuChoice == "r" or playerChoice == "s" and cpuChoice == "p":
damageDealt = 10 * combo
combo = combo + 1
time.sleep(0.75)
print("You deal " + str(damageDealt) + " damage!")
cpuHealth = cpuHealth - damageDealt
enemyCombo = 1
elif cpuChoice == "r" and playerChoice == "s" or cpuChoice == "p" and playerChoice == "r" or cpuChoice == "s" and playerChoice == "p":
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
combo = 1
elif cpuChoice == playerChoice:
time.sleep(0.75)
print ("You both chose the same!")
else:
time.sleep(0.75)
print ("...")
time.sleep(1)
print("Thats not a choice...")
enemyDamageDealt = fans * enemyCombo
playerHealth = playerHealth - enemyDamageDealt
enemyCombo = enemyCombo + 1
time.sleep(0.75)
print("Your enemy deals " + str(enemyDamageDealt) + " damage!")
if cpuHealth <= 0:
print ("You win and gained 5 fans!")
fans = fans + 5
keepPlaying = input("Play again (y or n)")
enemyHeal
elif playerHealth <= 0:
print("You lose, sorry.")
keepPlaying = input("Play again (y or n)")
Here is a function that displays the given prompt to prompt a user for input. If the user does not give any input by the specified timeout, then the function returns None
from select import select
import sys
def timed_input(prompt, timeout):
"""Wait for user input, or timeout.
Arguments:
prompt -- String to present to user.
timeout -- Seconds to wait for input before returning None.
Return:
User input string. Empty string is user only gave Enter key input.
None for timeout.
"""
sys.stdout.write('(waiting %d seconds) ' % (int(timeout),))
sys.stdout.write(prompt)
sys.stdout.flush()
rlist, wlist, xlist = select([sys.stdin], [], [], timeout)
if rlist:
return sys.stdin.readline().strip()
print()
return None

Implementing a timer into Math game in Python

import random
from tkinter import *
import tkinter as tk
import time
scores = []
score = 0
#introduction
def start():
print(" Welcome to Maths Smash \n")
print("Complete the questions the quickest to get a better score\n")
username = True #this makes sure the user can only enter characters a-z
while username:
name = input("What is your name? ")
if not name.isalpha():
print("Please enter letters only")
username = True
else:
print("Ok,", name, "let's begin!")
main()
#menu
def main():
choice = None
while choice !="0":
print(
"""
Maths Smash
0 - Exit
1 - Easy
2 - Medium
3 - Hard
4 - Extreme
5 - Dashboard
"""
)
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Good-bye!")
quit()
#easy
elif choice == "1":
print("Easy Level")
easy_level()
#medium
elif choice == "2":
print("Medium Level")
medium_level()
#hard
elif choice == "3":
print("Hard Level")
hard_level()
#extreme
elif choice == "4":
print("Extreme Level")
extreme_level()
#teacher login
elif choice == "5":
print("Dashboard")
from GUI import dashboard
dashboard()
else:
print("Sorry but", choice, "isn't a vaild choice.")
def easy_level():
global score
#easy level
for i in range(10):
operator_sign =""
answer = 0
num1 = random.randint(1,5)
num2 = random.randint(1,5)
operator = random.randint(1,4)
#choosing the operator randomly
if operator == 1:
operator_sign = " + "
answer = num1 + num2
elif operator == 2:
operator_sign = " - "
answer = num1 - num2
elif operator == 3:
operator_sign = " * "
answer = num1 * num2
elif operator == 4:
operator_sign = " / "
num1 = random.randint(1,5) * num2
num2 = random.randint(1,5)
answer = num1 // num2
else:
print("That is not a vaild entry!\n")
#outputting the questions along with working out if it's correct
question = str(num1) + operator_sign + str(num2) + "\n"
user_input = int(input(question))
if user_input == answer:
score = score + 1
#total score
print("You scored:", str(score), "out of 10")
Been trying to add a timer in this game for a while but every time I go to the first level it doesn't work with the game at the same time, as in I will load the first level and none of the questions will pop-up until the timer has completed. Was wondering if anyone could help me or know a fix to this, I want to make it so if the user completes the test within a certain amount of time they get an additional 10 points added to the overall score. This is what I had come up with at first:
def timer():
countdown=120
while countdown >0:
time.sleep(1)
score = score + 10

Computer guessing game

import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.

Categories

Resources