import time
import threading
import random
#declare variables and constant
guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"]
nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"]
wronganswers = ["Wrong answer...", "Nope", "Try again next time.", "Wrong answer. Nice effort"]
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
guess_no = 0
score = 0
def countdown():
global my_timer
my_timer = 5
for i in range(7):
randomelement = random.choice(guessingelement)
guessingelement.remove(randomelement)
time.sleep(1)
for x in range(5):
my_timer = my_timer - 1
time.sleep(1)
print("Out of time.Haiya!")
countdown_thread = threading.Thread(target = countdown)
countdown_thread.start()
while my_timer > 0:
#tips of the element
if randomelement == "Hydrogen" and not out_of_guesses:
print("Tip 1: It is the most flammable of all the known substances.")
print("Tip 2: It reacts with oxides and chlorides of many metals, like copper, lead, mercury, to produce free metals.")
print("Tip 3: It reacts with oxygen to form water.")
#test the number of tries so that it doesn't exceed 3 times if answer is wrong
while guess != randomelement and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True
#add score, praise when answer is correct and encourage when answer is wrong for 3 times
if out_of_guesses:
print(random.choice(wronganswers))
print(f"{randomelement} was the element.")
else:
print(random.choice(nicephrases), ", YOU GET IT!")
score = score + 1
if randomelement == "Magnesium" and not out_of_guesses:
print("Tip 1: It has the atomic number of 12.")
print("Tip 2: It's oxide can be extracted into free metal through electrolysis.")
print("Tip 3: It is a type of metal.")
procedure same as the first question. And so on with my questions.
However, it shows that my_timer variable is not defined. The process that I would want it to undergo is that it will countdown for 5 seconds for every questions, and when the timer reaches 0, it will print out of time and proceed to the next question.
In the code you've shown, you haven't assigned a value to my_timer.
my_timer = 5
By assigning the global within countdown() you've merely allowed countdown to change the value of my_timer. You still need to assign a value.
Related
import math
import random
a = math.floor((random.random())*100)
if a%10 != 00:
c = math.floor(a/10)
a = a - c*10
#to make sure the number isnt over 10
attempts = int(input("enter num of attempts"))
att = attempts
for i in range(0,attempts+1,1):
tr = int(input("try"))
att = att -1
if tr == a:
print("good")
break;
else:
print("no,try again", "you got",att,"more attempts")
if att == 0:
print("game over,the num was", (a))
the game has random num between 0-10 and you need to insert num of attempst, and then guess what number is it, and you got the amount of attempst you have insert to try guessing the num.
You can replace the for loop by a while loop.
This way you have more control, you can use a found boolean and loop while it is False.
Note also that you have to increment i by yourself.
I printed the messages (win/lost) outside of the loop.
It makes the loop code more readable.
I also used randint() to choose the random number to guess.
It does all the work without further computation and is also part of the random module.
from random import randint
a = randint(1, 10)
attempts = int(input("enter num of attempts"))
att = attempts
found = False
i = 0
while i < attempts and not found:
i += 1
att -= 1
tr = int(input("try"))
if tr == a:
found = True
elif att > 0:
print("no,try again", "you got", att, "more attempts")
if found:
print("good")
else:
print("game over,the num was", (a))
I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=
I'm receiving "local variable 'var_1_mon' referenced before assignment" and "local variable 'var_0_mon' referenced before assignment" when entering 0 or 1 for racer = str(input(">")). But to my knowledge I've already assigned their values, and if I assigned them after def game() it will reset my variables to those values after every turn.
I've tried putting the initial variable values after "def game()" and removing the Game loss and Victory conditions, but then choosing var_0 ended the program and var_1 didn't loop back to game().
import random
import time
def start():
var_0_mon = 100
var_1_mon = 100
def game():
var_0 = 0
var_1 = 0
racer = str(input(">"))
if racer in ("0"):
player_mon = var_0_mon
enemy_mon = var_1_mon
elif racer in ("1"):
player_mon = var_1_mon
enemy_mon = var_0_mon
while var_0 <= 100 or var_1 <= 100:
var_0 = var_0 + random.randint(1,2)
var_1 = var_1 + random.randint(0,3)
print ("Var 0:", var_0, "Var 1:", var_1)
if var_0 >= 100 or var_1 >= 100:
break
if var_0 >= 100 and var_1 >= 100:
print ("Tie!")
elif var_0 >= 100:
var_0_mon = var_0_mon + 25
var_1_mon = var_1_mon - 25
print ("Var 0 Match Victory!")
elif var_1 >= 100:
var_0_mon = var_0_mon - 25
var_1_mon = var_1_mon + 25
print ("Var 1 Match Victory!")
game()
if player_mon <= 0:
print ("Game Loss")
elif enemy_mon <= 0:
print ("Game Victory!")
start()
I expected def start() to define the beginning of the game, so the player could choose a racer = str(input(">")) to choose between making their player_mon var_0_mon or var_1_mon. Then the game would proceed with var_0 or var_1 receiving random integers (1 - 2 and 0 - 3 respectively), upon which one would reach 100 before the other, or they would tie. Upon a tie, their the player_mon and enemy_mon would remain untouched, however upon the player winning, whichever of the two variable racers they've chosen (var_0 or var_1.) They would receive 25 to their player_mon and the enemy would lose 25 of their enemy_mon, and vice versa. game() would then return them to choose a racer, (var_0 or var_1). This would continue until one variable racer (var_0 or var_1) lost all of their money, if player_mon <= 0: or elif enemy_mon <= 0: printing "Game Loss" or "Game Victory" respectively, and then looping back to the very beginning of the program using start()
As soon as you assign to var_1_mon inside game, you create a new local variable that shadows the one defined inside start. You need to declare it non-local so that assignments affect start's variable rather than create a new one.
def start():
var_0_mon = 100
var_1_mon = 100
def game():
nonlocal var_0_mon, var_1_mon
...
I am doing Coursera mini project.
I got this problem as bad input ('def') for the line def range100(). I am trying to play guess number game in the range. I check the indentation and it's all right. Please help. Thanks
import simplegui
import random
import math
# helper function to start and restart the game
def new_game():
# initialize global variables used in your code here
global secret_number
low = 0
global n
if range100():
high = math.ceil(100)
n = int(math.log((high - low + 1),2))
elif range1000():
high = math.ceil(1000)
n = int(math.log((high - low + 1),2)
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global secret_number
secret_number = random.randrange(0, 100)
return True
def range1000():
# button that changes the range to [0,1000) and starts a new game
global secret_number
secret_number = random.randrange(0, 1000)
return True
def input_guess(guess):
# main game logic goes here
global secret_number
guess_num = int(guess)
print 'Guess was %s' %guess_num
global n
if secret_number > guess_num:
print 'Lower'
n -= 1
if n >= 0:
print 'Number of remaining guesses is %s' %n
else:
print 'You are running out of chances'
new_game()
elif secret_number < guess_num:
print 'Higher'
n -= 1
if n >= 0:
print 'Number of remaining guesses is %s' %n
else:
print 'You are running out of chances'
new_game()
else:
print 'Correct'
# create frame
frame = simplegui.create_frame('Guess the number',200, 200)
frame.add_input('Input Guess:', input_guess, 100)
frame.add_button('Range is [0, 100)', range100, 100)
frame.add_button('Range is [0, 1000)', range1000, 100)
# register event handlers for control elements and start frame
frame.start()
# call new_game
new_game()
I am trying to count guess and output the outcome. But I can't pass this run as I don't know why def is a syntax wrong....
Looking at your code, you are missing a parenthesis in the line before def range100(). The line should be n = int(math.log((high - low + 1),2)).
I've been trying out to solve the monty hall problem in Python in order to advance in coding, which is why I tried to randomize everything. The thing is: I've been running into some trouble. As most of you probably know the monty problem is supposed to show that changing the door has a higher winrate (66%) than staying on the chosen door (33%). For some odd reason though my simulation shows a 33% winrate for both cases and I am not really sure why.
Here's the code:
from random import *
def doorPriceRandomizer():
door1 = randint(0,2) #If a door is defined 0, it has a price in it
door2 = randint(0,2) #If a door is defined either 1 or 2, it has a goat in it.
door3 = randint(0,2)
while door2 == door1:
door2 = randint(0,2)
while door3 == door2 or door3 == door1:
door3 = randint(0,2)
return door1,door2,door3 #This random placement generator seems to be working fine.
while True:
loopStart = 0
amountWin = 0
amountLose = 0
try:
loopEnd = int(input("How often would you like to run this simulation: "))
if loopEnd < 0:
raise ValueError
doorChangeUser = int(input("[0] = Do not change door; [1] = Change door: "))
if doorChangeUser not in range(0,2):
raise ValueError
except ValueError:
print("Invalid input. Try again.\n")
else:
while loopStart != loopEnd:
gameDoors = doorPriceRandomizer()
inputUser = randint(0,2)
if doorChangeUser == 0:
if gameDoors[inputUser] == 0:
amountWin += 1
loopStart += 1
else:
amountLose += 1
loopStart += 1
elif doorChangeUser == 1:
ChangeRandom = 0
while gameDoors[ChangeRandom] == gameDoors[inputUser]:
ChangeRandom = randint(0,2)
if gameDoors[ChangeRandom] == 0:
amountWin += 1
loopStart += 1
else:
amountLose += 1
loopStart += 1
print("Win amount: ",amountWin,"\tLose amount: ",amountLose)
What am I doing wrong? I really appreciate all help! Thanks in advance!
ChangeRandom = 0
while gameDoors[ChangeRandom] == gameDoors[inputUser]:
ChangeRandom = randint(0,2)
This doesn't do what you think it does. Instead of checking if the ChangeRandom door is the same as the inputUser door, this checks if the ChangeRandom door and the inputUser door have the same value -- that is to say they're either both winners or both losers.
That said, that's not even what you want to do. What you want to do is to find a door that's not the user's input that IS a loser door, then switch to the OTHER one that isn't the user's input. This could be implemented with minimal change to your code as:
other_wrong_door = next(c for c, v in enumerate(gameDoors) if v != 0 and c != inputUser)
new_door = next(c for c, _ in enumerate(gameDoors) if c != inputUser and c != other_wrong_door)
But honestly this merits a re-examining of your code's structure. Give me a few minutes to work something up, and I'll edit this answer to give you an idea of how I'd implement this.
import random
DOORS = [1, 0, 0]
def runonce(switch=False):
user_choice = random.choice(DOORS)
if user_choice == 1:
# immediate winner
if switch:
# if you won before and switch doors, you must lose now
return False
else:
new_doors = [0, 0] # remove the user-selected winner
new_doors = [0] # remove another loser
return bool(random.choice(new_doors))
# of course, this is always `0`, but
# sometimes it helps to show it. In production you
# wouldn't bother writing the extra lines and just return False
else:
if switch:
new_doors = [1, 0] # remove the user-selected loser
new_doors = [1] # remove another loser
return bool(random.choice(new_doors))
# as above: this is always True, but....
else:
return False # if you lost before and don't switch, well, you lost.
num_trials = int(input("How many trials?"))
no_switch_raw = [run_once(switch=False) for _ in range(num_trials)]
switch_raw = [run_once(switch=True) for _ in range(num_trials)]
no_switch_wins = sum(1 for r in no_switch_raw if r)
switch_wins = sum(1 for r in switch_raw if r)
no_switch_prob = no_switch_wins / num_trials * 100.0
switch_prob = switch_wins / num_trials * 100.0
print( " WINS LOSSES %\n"
f"SWITCH: {switch_wins:>4} {num_trials-switch_wins:>6} {switch_prob:.02f}\n"
f"NOSWITCH:{no_switch_wins:>4} {num_trials-no_switch_wins:>6} {no_switch_prob:.02f}")
You have gotten the mechanics of the problem wrong so you are getting the wrong result. I have rewritten the choice mechanics, but I am leaving the user input stuff to you so that you can continue to learn python. This is one of many ways to solve the problem, but hopefully it demonstrates some things to you.
def get_choices():
valid_choices = [0, 1, 2] # these are the values for a valid sample
shuffle(valid_choices) # now randomly shuffle that list
return valid_choices # return the shuffled list
def get_door(user_choice):
return user_choice.index(0)
def monty_sim(n, kind):
"""
:param n: number of runs in this simulation
:param kind: whether to change the door or not, 0 - don't change, 1 = change door
:return: (win_rate, 1 - win_rate)
"""
wins = 0
for i in range(0, n):
game_doors = get_choices()
user_choice = get_door(get_choices()) # use the same method and find user door choice
# so there are two branches.
# In both, a door with a goat (game_door = 1) is chosen, which reduce the result to
# a choice between two doors, rather than 3.
if kind == 0:
if user_choice == game_doors.index(0):
wins += 1
elif kind == 1:
# so now, the user chooses to change the door
if user_choice != game_doors.index(0):
wins += 1
# Because the original choice wasn't the right one, then the new
# must be correct because the host already chose the other wrong one.
win_rate = (wins / n) * 100
return win_rate, 100 - win_rate
if __name__ == '__main__':
n = 1000
kind = 1
wins, loses = monty_sim(n, kind)
print(f'In a simulation of {n} experiments, of type {kind} user won {wins:02f} of the time, lost {loses:02f} of the time')