Python add a time limit and check whether they have acted - python

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

Related

Simple coinflip terminal game won't update variable

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!")

User/Player Health is not saved during attack simulation using a coin and random

I am a novice to python. My longterm project is to design a choose your own adventure text-based game.
A major component of this game is attack scenarios. With that in mind, I have been constructing a python program for simulating an attack scenario. In this case, by flipping a coin to first determine whether the player or the enemy attacks first. Afterwards, a random integer between 1 and 10 is used as the attack damage. A function (HealthCheck), checks the health of the player/enemy to determine whether the player/enemy is dead.
My main problem is that the enemy's and player's health restarts after an attack. How can my program save the user's health after an attack, instead of resetting to 10 HP?
Below is my python code. Thank you for your help.
import random
import time
import sys
enemyHealth = 10
playerHealth = 10
def playerAttack(enemyHealth):
attack_damage = random.randint(1, 10)
print("The player does " + str(attack_damage) + " damage points to
the enemy.")
enemyHealth -= attack_damage
print("The enemy has " + str(enemyHealth) + " HP left!")
enemyHealthCheck(enemyHealth)
pass
def enemyAttack(playerHealth):
attack_damage = random.randint(1, 10)
print("The enemy does " + str(attack_damage) + " damage points to
the player.")
playerHealth -= attack_damage
print("The player has " + str(playerHealth) + " HP left!")
playerHealthCheck(playerHealth)
pass
def turnChoice():
h = 1
t = 2
coin = ""
while coin != "h" and coin != "t":
coin = input("Player, flip a coin to decide who attack first.\n"
"Heads or tails? H for heads. T for tails.\n")
if coin == "h":
print("You chose heads.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
else:
print("You chose tails.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
choice = random.randint(1, 2)
if choice == coin:
print("Great choice. You go first.")
playerAttack(enemyHealth)
else:
print("Enemy goes first.")
enemyAttack(playerHealth)
def replay():
playAgain = ""
while playAgain != "y" and playAgain != "n":
playAgain = input("Do you want to play again? yes or no")
if playAgain == "y":
print("You chose to play again.")
print(".")
print(".")
print(".")
time.sleep(2)
turnChoice()
else:
print("Game over. See you soon.")
sys.exit()
def playerHealthCheck(playerHealth):
if playerHealth <=0:
print("Player is dead. Game over.")
replay()
else:
print("The player has " + str(playerHealth) + " HP points!")
print("It is your turn to attack.")
playerAttack(enemyHealth)
def enemyHealthCheck(enemyHealth):
if enemyHealth <=0:
print("Enemy is dead. You win.")
replay()
else:
print("Enemy is not dead. The enemy has " + str(enemyHealth) + " HP points.")
print("It is their turn to attack.")
enemyAttack(playerHealth)
turnChoice()
To make the code edit the variables you need to use globals. When you call the variable with the parentheses in the function they are only edited in the scope of that variable, but when you use globals they get edited for the whole program. Here is an example. Below is the code that is using globals:
import random
import time
import sys
enemyHealth = 10
playerHealth = 10
def playerAttack():
global enemyHealth
attack_damage = random.randint(1, 10)
print("The player does " + str(attack_damage) + " damage points to the enemy.")
enemyHealth -= attack_damage
print("The enemy has " + str(enemyHealth) + " HP left!")
enemyHealthCheck()
pass
def enemyAttack():
global playerHealth
attack_damage = random.randint(1, 10)
print("The enemy does " + str(attack_damage) + " damage points to the player.")
playerHealth -= attack_damage
print("The player has " + str(playerHealth) + " HP left!")
playerHealthCheck()
pass
def turnChoice():
h = 1
t = 2
coin = ""
while coin != "h" and coin != "t":
coin = input("Player, flip a coin to decide who attack first.\n"
"Heads or tails? H for heads. T for tails.\n")
if coin == "h":
print("You chose heads.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
else:
print("You chose tails.\n"
"Flip the coin. \n"
". . .")
time.sleep(2)
choice = random.randint(1, 2)
if choice == coin:
print("Great choice. You go first.")
playerAttack()
else:
print("Enemy goes first.")
enemyAttack()
def replay():
playAgain = ""
while playAgain != "y" and playAgain != "n":
playAgain = input("Do you want to play again? yes or no")
if playAgain == "y":
print("You chose to play again.")
print(".")
print(".")
print(".")
time.sleep(2)
turnChoice()
else:
print("Game over. See you soon.")
sys.exit()
def playerHealthCheck():
global playerHealth
if playerHealth <= 0:
print("Player is dead. Game over.")
replay()
else:
print("The player has " + str(playerHealth) + " HP points!")
print("It is your turn to attack.")
playerAttack()
def enemyHealthCheck():
global enemyHealth
if enemyHealth <= 0:
print("Enemy is dead. You win.")
replay()
else:
print("Enemy is not dead. The enemy has " + str(enemyHealth) + " HP points.")
print("It is their turn to attack.")
enemyAttack()
turnChoice()

Game of Chance in Python 3.x?

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.

Questions about a tic-tac-toe program I am writing

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")

Simple Rock Paper Scissors game, problems with returning score?

I'm writing this Rock Paper Scissors program for my Programming class, and having some problems getting the full score to show up at the end of the program. I'm super beginner in Python, so nothing too fancy here. For some reason, as I run the program, the only score that shows up is 1 regardless of how many times the game loops. What am I doing wrong here?
from myro import *
from random import *
def announceGame():
""" Announces the game to the user """
speak("Welcome to Rock, Paper, Scissors. I look forward to playing you.")
def computerMove():
""" Determines a random choice for the computer """
randomNumber = random()
if randomNumber == 1:
compMove = "R"
elif randomNumber == 2:
compMove = "P"
else:
compMove = "S"
return compMove
def userMove():
""" Asks the user to input their choice."""
userChoice = raw_input("Please enter R, P, or S: ")
return userChoice
def playGame(userChoice, compMove):
""" Compares the user's choice to the computer's choice, and decides who wins."""
global userWin
global compWin
global tie
userWin = 0
compWin = 0
tie = 0
if (userChoice == "R" and compMove == "S"):
userWin = userWin + 1
print "You win."
elif (userChoice == "R" and compMove == "P"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "R"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "P"):
userWin = userWin + 1
print "You win"
elif (userChoice == "P" and compMove == "S"):
compWin = compWin + 1
print "I win"
elif (userChoice == "P" and compMove == "R"):
userWin = userWin + 1
print "You win"
else:
tie = tie + 1
print "It's a tie"
return compWin, userWin, tie
def printResults(compWin, userWin, tie):
""" Prints the results at the end of the game. """
print " Rock Paper Scissors Results "
print "------------------------------------"
print "Computer Wins: " + str(compWin)
print "User Wins: " + str(userWin)
print "Ties: " + str(tie)
def main():
announceGame()
for game in range(1,6):
u = userMove()
c = computerMove()
game = playGame(u,c)
printResults(compWin, userWin, tie)
main()
Inside playGame, you set userWin, compWin, and tie to zero. So every time you call that function, they get set to zero before the new values are added. You should initialize these variables outside the function that you are calling in the loop. (For instance, you could initialize them in announceGame.)

Categories

Resources