"Horse" Math game - python

For my computer science class final, we have been instructed to make our own game in Python.
Requirements:
1. Needs to use both a “while loop” and a “for x in y loop.”
2. Needs to use list to either keep track of information or score
3. Needs to use a function for gameplay, tracking score, both.
4. Display some art either at the beginning, after, or in between turns.
5. Can be multi player or single player.
6. Must carry a complexity commensurate with a final project.
Anyways, I decided to make a game similar to horse in basketball. The object of the game is to find the answer of the math problem before time runs out. If you don't, you get a letter in horse. Once you get all the letters of horse, your game is over.
Here is what I have so far:
import random
import time
from timeit import default_timer
print("welcome to Jared's Math Horse game!")
time.sleep(1)
print("You will have to do some basic geometry and algebra problem,and some brain teasers...")
time.sleep(1)
print("For each you get wrong, you get a letter, and it will spell 'HORSE'. Once you get all letters, you lose. ROUND TO THE NEAREST INTEGER!!!!!!!!")
time.sleep(1)
###BEgin actual stuff
how_long = int(input("How many times(problems) do you want to play? (above or equal 5)"))
score = 0
##Problems
problems = ["A cylinder has a radius of 5. It's height is 6. What is the volume?471","A boy buys two shirts. One costs $15 and he pays $27 for both shirts. How much was the 2nd shirt?12","dat boi costs $12 after a 15% discount. What was the original price?14.12","A square pyramid with a height 12 and a side length 5. What is the volume?20","What is the square root of 36?", "What is the roman numeral for 500? QUICK USE GOOGLE!!!D","On a scale of 100-100 how cool is jared?100" ]
#######End of variables
####Func time
def horse(score,problem,speed):
b = input("You have {} seconds. Press enter to begin. Round answers to nearest integer.".format(speed))
begin = default_timer()
howfast = default_timer() - begin
print(random.problem[0,7])
##Check answer
answer = input("What is your answer?:")
## Give score
##loops
for x in how_long:
while True:
if score !=5:
a = random.randint(0,7)
problem = problems[a]
##Speed
speed = int(input("How fast do you want to play?? 1=slow 2=medium 3=FAST"))
if speed == (1):
speed = random.randint(30,60)
if speed == 2:
speed = random.randint(20,40)
if speed == 3:
print("spicy!")
speed = random.randint(10,30)
score = horse(score,problem,speed)
if score == 0:
print("You have a perfect score. Good work.")
if score == 1:
print("You have an H")
if score == 2:
print("You have Ho")
if score == 3:
print("You have Hor")
if score == 4:
print("You have Hors")
if score == 5:
print("You have Horse. Game over, loser.")
break
horse()
So. I'm not sure how to make it if you type in the correct answer, you won't get a letter, and move on. I tried used a 'if and' statement and that is it. BTW, the answers to the problems are at the end. Help is VERY appreciated. Sorry if I didn't explain this well, I am a noob at this. Haha

That data structure is a disaster. You would be better off doing something like this. Keep a dict of problem : correctAnswer then get a random key, ask for some user input and time it. You still need to implement the horse logic though.
score = 0
maxTime = 3 #how many milliseconds a user has to answer the question to get it right
problems = {
"A cylinder has a radius of 5. It's height is 6. What is the volume?" : "471",
"A boy buys two shirts. One costs $15 and he pays $27 for both shirts. How much was the 2nd shirt?" : "12",
"dat boi costs $12 after a 15% discount. What was the original price?" : "14.12",
"A square pyramid with a height 12 and a side length 5. What is the volume?" : "20",
"What is the square root of 36?" : "6",
"What is the roman numeral for 500? QUICK USE GOOGLE!!!" : "D",
"On a scale of 100-100 how cool is jared?" : "100"
}
for i in range(how_long):
startTime = time.time()
thisProblem = random.choice(list(problems.keys()))
answer = input(thisProblem + ": ")
endTime = time.time()
totalTime = round(endTime - startTime, 2)
correctAnswer = problems[thisProblem]
if answer == correctAnswer and totalTime < maxTime:
print("Correct!, you took", totalTime, "ms to answer")
score += 1
elif answer != correctAnswer:
print("Incorrect!, the correct answer was", correctAnswer)
elif totalTime > maxTime:
print("Correct, but you took", totalTime, "ms to answer but are only allowed", maxTime, "ms")

Related

How would I run a simulation based on percentage with Python?

I'm writing a program for a game me and my brother made, and this is what I have so far:
def main():
number1 = requestInteger("Enter team 1 power:")
print ("team 1 is " + str(number1) + " overall")
number2 = requestInteger("Enter team 2 power:")
print ("team 2 is " + str(number2) + " overall")
odds = number1 - number2
print str(odds)
favoriteChance = odds + 50
print ("The favorite has a " + str(favoriteChance) + "% chance to win")
I want to use that percentage from this formula to run a simulation, where whatever team has that chance of winning. This is my first time self programming anything, sorry if this is really simple.
Good job with your first program. Many of us started out with much messier code.
If you don't mind I'm going to change your algorithm a little.
Currently your odds are 50% + (power1 - power2)
This is annoying because if power values go beyond 50 it make a negative chance, or above 100, which doesn't work.
So if you don't mind let's change it to : power1/(power1+power2) and power2/(power1+power2).
This has good properties:
It is always positive (teams always have a chance to win, even if its really low)
The sum is always equals to 1 (A team always wins)
The chance to win is proportional to power (If power1 = 2*power2, then the chances of winning are also twice as big.
Alright now on to the code:
I've never seen requestInteger before so I'll be using input instead.
Since we want to announce a winner, I'll be adding inputs for the team names.
I'll add a return value equal to the winning team, so you can do something with it via a winner = main() call.
To check for a winner I'll check if random.random is bigger than the chance of team1_win_chance. random.random is evenly distributed between 0 and 1, so it being bigger than team1_win_chance is the same probability as team1 has of losing.
If 1 doesn't win, since we have well defined probabilities then 2 wins by default.
Here's what the code looks like:
import random
def main():
team1 = input("Enter team 1 name:")
power1 = int(input("Enter team 1 power:"))
print(f"{team1}'s power is {power1}")
team2 = input("Enter team 2 name:")
power2 = int(input("Enter team 2 power:"))
team1_win_chance = power1/(power1+power2)
if random.random() > team1_win_chance:
winner = team2
else:
winner = team1
print(f"Team {winner} is the winner")
return(winner)
And here is what it looks like when I run it:
>>> main()
Enter team 1 name:Turtles
Enter team 1 power:40
Turtles's power is 40
Enter team 2 name:Rabbits
Enter team 2 power:5
Team Turtles is the winner
'Turtles'
Your code will probably look something like:
import random
def main():
...
favoriteChance = odds + 50
roll = random.randint(1, 100)
win = roll <= favoriteChance
if win:
... [print something indicating team 1 has won]
To step through that:
import random loads a package. When you are making more complicated programs, you can use this to load code from another file you've written, or code available online, but in this case we're loading the premade package random. Read the docs here: https://docs.python.org/3/library/random.html, or do help(random).
roll = random.randint(1, 100) generates a random number between 1 and 100. Think of it as rolling an 100-sided die. (When we call a function in the random package, we need to use random.[functionname]. That means that if you also happen to have a function with the same name in your file, it's clear which is which.)
win = roll <= favoriteChance: If we want a 70% chance of winning, one way to get that is to check if the die result is 1-70.
There's also lots of other functions in random, like for generating a random value between [0, 1), if you need more than 100 sides on your die.

How do I make this dice game run in a simulation 10,000 times using python?

I'm doing a homework assignment. I can't seem to find a solution on how to make the dice roll 10,000 times plus create a variable that updates everytime you win some money when you roll the dice correctly. I have some instructions on the homework below can anyone shed some light on me?
The game is played as follows: roll a six sided die.
If you roll a 1, 2 or a 3, the game is over.
If you roll a 4, 5, or 6, you win that many dollars ($4, $5, or $6), and then roll again.
With each additional roll, you have the chance to win more money, or you might roll a game-ending 1, 2, or 3, at which time the game is over and you keep whatever winnings you have accumulated.
Use the randint function from Python's Random module to get a die roll result
(see functions for integers).
Run 10,000 simulations of the game (Monte Carlo method).
Print the average amount won and the largest amount won.
Just as a thought experiment, would you pay $3 for a chance to play this game?
Example Output:
Average amount won = x.xx
Max amount won = xx
import random
class diceGame:
def __init__(self,dice):
self.dice = dice
def gameOutCome(self):
askUser = str(input("Roll to play the game? Y/N: "))
while True:
if askUser == 'y':
print(self.dice)
if self.dice == 1:
print("Sorry, Try Again!")
elif self.dice == 2:
print("Sorry, Try Again!")
elif self.dice == 3:
print("Sorry, Try Again!")
elif self.dice == 4:
print("You win $4")
elif self.dice == 5:
print("You win $5")
elif self.dice == 6:
print("You win $6")
askUser = str(input("Roll to play the game? Y/N: "))
x = random.randint(1,6)
dd = diceGame(x)
dd.gameOutCome()
Welcome to stackoverflow. Since this is your homework, I don't think it is appropriate to post an entire solution here.
However I do think some pointers in the right direction might be helpful:
1) You are running the simulation 10000 times. Each roll requires 2 user inputs. So in order to finish the simulation you need at least 20000 user inputs... Yeah that will be tiresome ;) .... So lets cut the user input - just write a function that executes the game until the game is finished. Once you have a function that executes one game, how can you execute it multiple times?
2) Think of each roll having two possible outcomes - continue the game or not. What des it mean to continue? What condition has to be fullfilled for the game to end?
3) Once the game has ended, what do you need to do with the money?
4) You can use the sum and max functions to calculate the average and the maximum win.
import random
def play_game():
#The function that executes the game - you have to write that on your own
pass
wins = [play_game() for i in range(0,10000)]
win_average = sum(wins)/10000.0
max_win = max(wins)

Creating a RPG game chest

So i' trying to create a chest for a rpg game i'm working on and i'm having a really difficult time implementing probability along with making sure one item always drops on open. I was able to get the probability down but whenever i get it to work i'm unable to make the potion drop along with the weapon. Any help would be greatly appreciated! And yes my items are named from fairy tail.
I've already tried giving the items weight but even so i'm unable to make sure the potion drops
import random
-------------------------------------------------------------------------
Chestitems = [
"constant: Potion",
"common: Bow",
"common: Sword",
"common: Spear",
"uncommon: irondragon_Bow",
"uncommon: irondragon_Sword",
"uncommon: irondragon_Spear",
"rare: skydragon_Bow",
"rare: skydragon_Sword",
"rare: skydragon_Spear",
"legendary: firedragon_bow",
"legendary: firedragon_Sword",
"legendary: firedragon_Spear"
]
while(True):
OpenChest = input("Type 'open' to open the Chest!")
if OpenChest == "open":
print(random.choice(Chestitems))
else:
break
The code i have above is what i have working. Consider i'm self taught with no schooling it's really hard to find anything that helped me completely.
If you always want a potion plus some other item, you can do this:
print("You found a potion plus a " + random.choice(Chestitems))
Also, it might be better to arrange your common/rare/etc. items into separate lists:
common_items = ["Bow", "Sword", "Spear"]
uncommon_items = ["Irondragon Bow", "Irondragon Sword", "Irondragon Spear"]
# etc. for rare_items and legendary_items
Then, you can roll a random number from 1 to 100 to pick which list to choose from:
die_roll = random.randint(1, 100)
if die_roll < 75:
items = common_items
elif die_roll < 90:
items = uncommon_items
elif die_roll < 98:
items = rare_items
else:
items = legendary_items
print("You found a potion plus a " + random.choice(items))

Trying to add my first score counter (Python) (Beginner)

This is my first post here. I'm a total beginner in coding and I've created a little game to get some sort of practice. I'm having trouble adding a score counter to it. I've seen some similar posts but I didn't manage to figure it out.
Also can you guys/girls give me some tips on my code, any feedback is welcome (tell me what I can improve etc.)
Here is the code:
import random
import time
def game():
user_wins = 0
user_loses = 0
while True:
try:
number = int(input('Choose a number between 1 and 10: '))
if 0 <= number <= 10:
print('Rolling the dices {} time(s)!'.format(number))
break
else:
print("That's not quite what we were looking for.")
continue
except ValueError:
print("That's not quite what we were looking for.")
user_number = random.randint(1, 50)
computer_number = random.randint(1, 50)
time.sleep(1)
print("You've rolled {}".format(user_number))
time.sleep(1)
print('Bob rolled {}'.format(computer_number))
if computer_number > user_number:
time.sleep(0.5)
print('Bob Won')
user_loses += 1
elif computer_number < user_number:
time.sleep(0.5)
print("You've Won!")
user_wins += 1
elif computer_number == user_number:
time.sleep(0.5)
print('Seems like we have a little situation')
print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))
time.sleep(0.5)
play_again = input(str("Would you like to play again (y/n)? "))
if play_again == 'y':
print("Ready?\n")
game()
else:
print("\nThank you for playing.")
game()
I want to add something like Your score: 1-0 or something similar. I've made some progress on that but when looping the values reset..
Welcome to programming! So I'm going to tell you how to implement it, so you can do it yourself as well :D. So here is what we will do:
We will have a variable outside the scope(click here) of the while loop to keep track of the score, say score = 0.
And each time someone succeeds, gets the right answer, we will increase that, by saying, score = score + 1. But that takes too much time to type that right D: So python has a shortcut! You say score += 1 somewhere in your code where you want to increase the score (in the while True loop, in this case). And then we will later print out the score (or anything) by referencing it:
print( "Your final score was %s" % str(score) ) - I know, what is that stupid str() for!? It is because our score is an integer. Since we can add and do operations on it(yeah I know soo cool).
Aaaand thats it :). If you need any further help, don't hesitate to ask it. Good luck :D.
Move this line before the while loop starts.
number = int(input('Choose a number between 1 and 10: '))
Also, it prompts to input between 1-10 but the if statement allows 0-10.
To add a counter start by assigning an initial to score to both players to 0.
user_number_score = 0
inside the If statements that determine who won the round for example if the user won add...
user_number_score = user_number_score + 1
I've found a way to do it. I had to start over, re-done the code from scratch and it's better looking too. Thank you all for the feedback.
Added it as image.

Game of Pig - can't figure out how to loop through all the players

I have figured out most of the problem but can't seem to figure out how to loop through each of the players to let them play the game. This is the code I have so far. I think that my while loop in the main() function is wrong but I don't know what to do to fix it. Let me know if you can point me in the right direction. I also need to figure out how to end the turn if you roll a 1.
import random
def instructions():
print ("==================================================")
print ("\nWelcome to the Game of Pig. To win, be the")
print ("player with the most points at the end of the")
print ("game. The game ends at the end of a round where")
print ("at least one player has 100 or more points.\n")
print ("On each turn, you may roll the die as many times")
print ("as you like to obtain more points. However, if")
print ("you roll a 1, your turn is over, and you do not")
print ("obtain any points that turn.\n")
def num_players():
while True:
players = raw_input("How many players will be playing? ")
if players.isdigit():
return int(players)
else:
print "\nPlease enter a valid number of players.\n"
def name_players(players):
count = 1
list_of_players = []
for i in range(players):
name = raw_input("Enter the name for Player {}: ".format(count))
list_of_players.append(name)
count += 1
print ""
return list_of_players
def start_game(list_of_players):
points = 0
for player in list_of_players:
print "{0} has {1} points.".format(player, points)
print ("==================================================\n")
s = input("How many sides of the dice do you want? ")
for player in list_of_players:
print ("\n{0}'s turn:").format(player)
answer = raw_input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s)
if roll > 1:
points += roll
print "{0} has {1} points.".format(player, points)
answer = raw_input("Press y to roll the dice?")
def main():
instructions()
players = num_players()
list_of_players = name_players(players)
start_game(list_of_players)
if __name__ == "__main__":
main()
The problem you encountered is due to the local variable, points, in function start_game. All your players are sharing the same variable to keep tracking their score. Therefore, once, your first player reaches/passes 100 points, the game logic will move to the second player. However, the points variable is still keeping the score from the previous player (which is more than or equal to 100). Because of that, the following players will never get chance to get into while loop.
You should declare points vriable for each players OR reset points variable every time when points variable holds value is greater than or equal to 100.
def start_game(list_of_players):
points = 0 #<----------------- points is local variable to the function
for player in list_of_players:
print("{0} has {1} points.".format(player, points))
print ("==================================================\n")
s = int(input("How many sides of the dice do you want? ")) ###
# validate value of s?
for player in list_of_players:
### the variables declared in for loop is unique to each player
print ("\n{0}'s turn:".format(player))
answer = input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s + 1, 1) ### randrange
if roll > 1:
points += roll
print("{0} has {1} points.".format(player, points))
answer = input("Press y to roll the dice?")
PS. I'm running your code with Python 3.6.1.
Furthermore, one more thing you need to take care of is that for random.randrange(start, stop, step). The output will not include the value of stop. e.g. random.randrange(0, 10, 1) will generate integers from 0 to 9 inclusive. Therefore, if a player chose 6 sides of dice, that means the random number range should be from 1 to 6. In this way, you need to increment whatever number player entered.
e.g. 6 sides of dice
either random.randrange(0, 6+1, 1) or random.randrange(6+1) should work.

Categories