I am trying to make a full-on guessing game with a shop that you can buy stuff with coins. but I had a function that was supposed to give the user a certain amount of coins depending on how many attempts it took them to guess the number. However, when I have a variable called 'coins' and when a player gets the number, I add coins to 'coins' it doesn't actually add coins. When I print 'coins' it still tells me 0. It's very confusing I know but I just want to fix this. I am using a mac with python 3, and am using two files, one for the main code, and the other for the functions. Do you see where I'm going wrong?
Main Code:
from guessing_functions import guess_game, guess_home
home = False
attempt = 0
coins = 0
print ("Atemps:Coins, 10:5, 7:10, 5:20, 3:40, 1:100 ")
guess_game(coins, attempt)
while not home:
guess_home(coins)
Functions:
import random
def guess_game(coins, attempt):
print ("This is a guessing game. ")
found = False
num = random.randint(1, 100)
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == num:
print ("You got it!")
found = True
elif userGuess > num:
print ("Guess Lower!")
else:
print ("Guess Higher")
attempt += 1
if attempt == 1 and found == True:
print ("You won 100 coins!")
coins += 100
elif attempt == 2 and found == True:
print ("You won 40 coins")
coins += 40
elif attempt == 3 and found == True:
print ("You won 40 coins")
elif attempt == 4 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 5 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 6 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 7 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 8 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 9 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 10 and found == True:
print ("You won 5 coins")
coins += 5
Your function uses coins in it's local scope. In order for the function to change the value of the outter scope (global) coins variable you need to explicity state that.
Add global coins inside your function before changing coins value.
coins = 0
def f():
global coins
coins = 5
f()
print coins
# 5
Or, an alternative way is to return coins value from the function, and call your function coins = guess_game(attempt)
Here is some useful resource for this subject
To get it to work, you need only add return coins to the end of the guess_game function and collect the returned value in your main code as coins = guess_game(coins, attempt). However, if you'd like, you can simplify your code a little bit like so:
import random
def guessing_game(coins):
print("This is a guessing game. ")
attempts = 0
number = random.randint(1, 100)
user_guess = -number
while user_guess != number:
user_guess = int(input("Your Guess: "))
if user_guess > number:
print("Guess Lower!")
elif user_guess < number:
print("Guess Higher")
else:
print("You got it!")
if attempts == 1:
winnings = 100
elif attempts in [2, 3]:
winnings = 40
elif attempts in [4, 5]:
winnings = 20
elif attempts in [6, 7]:
winnings = 10
elif attempts in [8, 9, 10]:
winnings = 5
else:
winnings = 0
print("You won {} coins!".format(winnings))
return coins + winnings
attempts += 1
With your main code as:
from guessing_functions import guessing_game
coins = 0
print("Starting balance: {} coins".format(coins))
print ("Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100")
coins = guessing_game(coins)
print("Current balance: {} coins".format(coins))
Where the output from a sample run is as follows:
Starting balance: 0 coins
Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100
This is a guessing game.
Your Guess: 50
Guess Lower!
Your Guess: 25
Guess Higher
Your Guess: 37
Guess Higher
Your Guess: 44
Guess Higher
Your Guess: 47
Guess Lower!
Your Guess: 46
You got it!
You won 20 coins!
Current balance: 20 coins
You should return the number of coins from the function and assign it to coins:
def guess_game(coins, attempt):
... # code to determine coin amount
return coins
coins = guess_game(coins, attempt)
Defining Functions
Related
SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
I am new to python and built this for practice. How come if you guess incorrectly the print function runs repeatedly. Additionally, if you make a correct guess the corresponding print function doesn't run.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
elif guess < rand:
print("Too Low")
If the number is incorrect we need to ask the player to guess again. You can use break to avoid having an infinite loop, here after 5 guesses.
The conversion of the input to integer will throw an error if the entry is not a valid number. It would be good to implement error handling.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
break
elif guess < rand:
print("Too Low")
if i >= 5:
break
guess = int(input("Try again\nPick a number from 1 - 9"))
in the first while loop, when player guesses the correct number we need to break.
Also for counting the number of rounds that player played we need a new while loop based on count.
When we use count in our code we should ask player every time that he enters the wrong answer to guess again so i used input in the while
import random
print("Welcome to the Guessing Game:")
rand = random.randint(1, 9)
count = 0
while count!=5:
guess = int(input("Pick a number from 1 - 9:"))
count += 1
if guess > rand:
print("Too High")
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
break
elif guess < rand:
print("Too Low")
print('you lost')
Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
Hi i am unsure on how to add a second player for this number guessing game whereby after player 1 makes a guess, then player 2 makes a guess. like between every guess. I am only able to make it so that the player 2 guesses after player 1 guesses finish all of his choices(code below) if anyone is able to tell me if what i am looking for is possible or if there is any advice, it would be greatly appreciated. thanks in advance.
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: "))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances")
break
if guess < n:
print("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances")
break
if guess1 < n1:
print("guess is low")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no')")
if retry == "yes":
main()
else:
print("Okay. have a nice day! :D ")
main()
to achieve this I would use a while loop and a variable to detect which players turn it is. Like this:
import random
random_number = random.randint(1, 99)
player_chances = 5
current_player = 1
while player_chances > 0:
if current_player == 1:
guess = int(input("Player 1 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 2
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
else:
guess = int(input("Player 2 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 1
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
print("####")
print("Out of chances! The number was {}.".format(random_number))
print("####")
To make this possible in an efficient way I would have created a player class as such:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTrys = 0
self.guess = 0
def getNumberOfTrys(self):
return self.getNumberOfTrys
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTrys+=1
return self.guess
except Exception as error:
print(error)
return None
this class is responsible to create the player with the number of tries,his guess and his name.
the logic will be going through the list of players (you can add as much as you want) and perform the game logic as follows:
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1)
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1)
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear()
break
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Basically, create a list of players then go through each one and apply the game logic (getting input, comparing and checking number of tries)
after a player loses, we should remove him from the list and if a player wins we can clear the list and thus exiting the game.
Here is the full code:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTries = 0
self.guess = 0
def getNumberOfTries(self):
return self.getNumberOfTries
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTries+=1
return self.guess
except Exception as error:
print(error)
return None
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1) #addding player
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1) #for debug
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear() # exit game
break #exit loop
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Hope I got your question right, and excuse me If there is any errors or typos, I just created something fast that you can be inspired by. I highly suggest you get into OOP, it very simple and it can make your life much easier :)
All the best!
I'm new to programming and I have a task that I can't figure out on my own.
The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.
here is my code:
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
while True:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
while True:
if reset==True:
break
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(1, 6)
print(dicesArray[i])
total += dicesArray[i]
if dicesArray[i] == 1:
print("You rolled a one, the total is: ",str(total))
elif dicesArray[i] == 2:
print("You rolled a two, the total is: ",str(total))
elif dicesArray[i] == 3:
print("You rolled a three, the total is: ",str(total))
elif dicesArray[i] == 4:
print("You rolled a four, the total is: ",str(total))
elif dicesArray[i] == 5:
print("You rolled a five, the total is: ",str(total))
elif dicesArray[i] == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
reset=True
print("The total sum is",str(total),"with",numDices,"number of rolls.")
print()
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit=True
break
else:
print()
break
if exit==True:
break
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
total = 0
dices_counter = 0
while numDices > 0 :
eyes = random.randint(1, 6)
dices_counter+=1
total += eyes
if eyes == 1:
print("You rolled a one, the total is: ",str(total))
numDices-=1
elif eyes == 2:
print("You rolled a two, the total is: ",str(total))
numDices-=1
elif eyes == 3:
print("You rolled a three, the total is: ",str(total))
numDices-=1
elif eyes == 4:
print("You rolled a four, the total is: ",str(total))
numDices-=1
elif eyes == 5:
print("You rolled a five, the total is: ",str(total))
numDices-=1
elif eyes == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
print()
start=(input("Do you want to restart press Enter, to quit press 9. "))
if start=="9":
break
else:
print()
start = True
To solve your problem I would replace your current for loop with a while loop
Moreover, I see a lot of unacessary things in your code, I will try to list them :
Why do you use so many "while True"?
Why don't you just use exit() function to exit instead of using a
variable?
Is all the if part really necessary, can't you just print the
number?
Here's my proposal:
import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
while True:
remaining_dices=int(input("How many dices to throw? (1-5) "))
if remaining_dices<1 or remaining_dices>5:
print("Wrong input, try again")
break
dicesArray = list()
while remaining_dices>0:
dice_value = random.randint(1, 6)
dicesArray.append(dice_value)
print(dice_value)
total += dice_value
remaining_dices -= 1
if(dice_value == 6):
total-=6
remaining_dices +=2
print("You rolled a 6, rolling two new dices")
else:
print("You rolled a " + str(dice_value) + ", the total is : " +str(total))
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit()
else:
print()
for i in range(numDices):
Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed. When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.
If you want to be able to change the number of iterations, use another while loop and use i as a counter. Something like.
i = 0
while i <= numDices:
...
...
if ...:
...
elif ...:
...
i += 1
Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.
I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.
dicesArray = list(range(numDices))`
...
dicesArray[i]
...
If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError. You should probably start with an empty list and append to it. To get the most recent dice roll use dicesArray[-1] instead of dicesArray[i].
...
dicesArray = []
i = 0
while i <= numDices:
dicesArray.append(random.randint(1, 6))
total += dicesArray[-1]
if dicesArray[-1] == 1:
...
...
6.3.2. Subscriptions
Using a recursive function
import random
total = 0
diceRollList = []
# Define dice rolling function
def rollDice():
rollResult = random.randint(1, 6)
if rollResult == 6:
# If 6 Rolled run two more rolls and sum the results
print("Rolled a 6 Rolling 2 more")
return sum([rollDice() for _ in range(2)])
# If 6 not rolled return the result
print(f"Rolled a {rollResult}")
return rollResult
while True:
numberOfDice = int(input("How many Die to throw: "))
if numberOfDice not in range(1, 6):
print("Number of dice should be between 1 and 5")
break
for dice in range(numberOfDice):
print(f"Rolling Dice {dice}")
# Add result to the total
total += rollDice()
print(f"Running Total: {total}")
This one tracks how many it has rolled:
import random
a = int(0)
b = int(0)
c = int(0)
d = int(0)
e = int(0)
f = int(0)
limit = 101
count = 0
while True:
g = (random.randint(1, 6))
print(g)
count += 1
if g == 1:
a += 1
elif g == 2:
b += 1
elif g == 3:
c += 1
elif g == 4:
d += 1
elif g == 5:
e += 1
elif g == 6:
f += 1
if count > limit:
break
print(f"There are {a} 1's")
print(f"There are {b} 2's")
print(f"There are {c} 3's")
print(f"There are {d} 4's")
print(f"There are {e} 5's")
print(f"There are {f} 6's")