I don't know why the variable doesn't add up - python-3.x

This is my code so far and i don't know why the variable doesn't add up when i loop the code.
import random
player1=1
player2=1
print("Welcome To My Board Game")
def dice_roll():
dice1=random.randint(1,6)
dice2=random.randint(1,6)
print("Your first roll is",dice1)
print("Your second roll is",dice2)
total_dice=(dice1+dice2)
print("Your total is",total_dice)
print("You moved",total_dice,"spaces, to space",player1+total_dice )
while True:
print("Player 1 Turn")
choice=input("Do you want to roll the dice press r ")
if choice.lower()=="r":
dice_roll()
This is the output of my code
Welcome To My Board Game
Player 1 Turn
Do you want to roll the dice press r r
Your first roll is 6
Your second roll is 5
Your total is 11
You moved 11 spaces, to space 12
Player 1 Turn
Do you want to roll the dice press r r
Your first roll is 4
Your second roll is 5
Your total is 9
You moved 9 spaces, to space 10
Player 1 Turn
Do you want to roll the dice press r
the move space part should add on from the last part

The problem is, dice1, dice2 and total_dice are "destroyed" when the function returns. Those variables are defined within the scope of the function, so they can't be used outside of the function. There are two ways of accessing the variables inside a function:
Change global variables, then read the globals somewhere else. #yi_xiao's answer shows an example of this.
Pass some data in, and return some data.
In general, you should always prefer returning the values instead of mutating (changing) global variables. Using globals variables makes testing harder, and becomes a problem if you need to access the data from more than one thread at a time.
To fix your code, you should return total_dice from dice_roll, and pass the old total in:
import random
player1=1
player2=1
print("Welcome To My Board Game")
# Pass the old total in as total_dice
def dice_roll(total_dice):
dice1=random.randint(1, 6)
dice2=random.randint(1, 6)
print("Your first roll is", dice1)
print("Your second roll is", dice2)
# Increase the running total sum
total_dice += dice1 + dice2
print("Your total is", total_dice)
print("You moved", total_dice, "spaces, to space", player1 + total_dice)
# Return the sum
return total_dice
# Note, in this simple example, sum is actually global.
# In more realistic cases, this would be inside of a function
# instead of being global
sum = 0
while True:
print("Player 1 Turn")
choice = input("Do you want to roll the dice press r ")
if choice.lower() == "r":
# Pass sum to dice_roll
# Reassing sum to the new sum given to us by dice_roll
sum = dice_roll(sum)
Also note, that currently, your loop won't exit, ever. Even if someone types something other than "r", the loop won't exit, you need to tell it to exit. You can either use break, or change from an infinite loop, to something other than while True.

Use global with your var player1, and change it every time.
def dice_roll():
dice1=random.randint(1,6)
dice2=random.randint(1,6)
print("Your first roll is",dice1)
print("Your second roll is",dice2)
total_dice=(dice1+dice2)
print("Your total is",total_dice)
global player1
player1 += total_dice
print("You moved",total_dice,"spaces, to space",player1)
Reference:
The global statement
Python Scopes and Namespaces
Edit:
Go a step further,you can define a class:
import random
class player:
def __init__(self, init_space=1):
self.space = init_space
def dice_roll(self):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
print("Your first roll is",dice1)
print("Your second roll is",dice2)
total_dice = (dice1 + dice2)
print("Your total is",total_dice)
self.space += total_dice
print("You moved",total_dice,"spaces, to space", self.space)
player1 = player()
player2 = player()
print("Welcome To My Board Game")
while True:
print("Player 1 Turn")
choice = input("Do you want to roll the dice press r ")
if choice.lower() == "r":
player1.dice_roll()
When there are more players, use class will make things easier.

Related

Problem with function in python causing a loop

When i run my code, it will run the part of player1 however once it reaches the function it will loop back and do the player1 section again, code for it is here:
import random
playerscore2 = 0
EvenNums = [2,4,6,8,10,12]
OddNums = [3,5,7,9,11]
def playerscoretwo():
print("Player 2's turn")
rolling2 = input('would you like to roll?')
roll3 = rolling2.lower()
if rolling2 == 'Yes':
playerscore3 = 0
die3 = random.randint(1,6)
print('You got: ' +str(die3))
playerscore3 = int(playerscore3) + int(die3)
roll4 = input('Would you like to roll again?')
if roll4 == 'Yes':
die4 = random.randint(1,6)
print('You got: ' +str(die4))
playerscore4 = int(playerscore3) + int(die4)
int(playerscore4)
if playerscore3 in EvenNums:
playerscore4 = int(playerscore3) + 10
print("Player 2's total score is: " +str(playerscore4))
elif playerscore3 in OddNums:
playerscore4 = int(playerscore3) - 5
print("Player 2's total score is: " +str(playerscore4))
else:
print('Wrong input, please restart the game')
else:
print('Wrong input, please restart the game')
while True:
print("Player 1's turn")
rolling = input('would you like to roll?').lower()
if rolling == 'yes':
playerscore1 = 0
die1 = random.randint(1,6)
print('You got: ' +str(die1))
playerscore1 = int(playerscore1) + int(die1)
roll2 = input('Would you like to roll again?').lower()
if roll2 == 'yes':
die2 = random.randint(1,6)
print('You got: ' +str(die2))
playerscore1 = int(playerscore1) + int(die2)
int(playerscore1)
if playerscore1 in EvenNums:
playerscore2 = int(playerscore1) + 10
print("Player 1's total score is: " +str(playerscore2))
#player 2 section, p1 evennum
playerscoretwo()
elif playerscore1 in OddNums:
playerscore2 = int(playerscore1) - 5
print("Player 1's total score is: " +str(playerscore2))
#player 2 section, player 1 oddnum
playerscoretwo()
else:
print('Wrong input, please restart the game')
#note, section will be copy pasted with certain variables changed to make code easier to write,
and easier to test
else:
print('Wrong input, please restart the game')
elif rolling == 'no':
break
else:
print('Wrong input, please restart the game')
I have attempted to not use functions at all, however indentation becomes a drastic problem and will not run at all, even if it is a plain copy paste.
If anyone has any idea on what the problem is, it'd be greatly appreciated, thanks.
To answer you question the issue is - indentation
your
while True:
print("Player 1's turn")
rolling = input('would you like to roll?').lower()
is at the same indent level with
if rolling == 'yes':
so it never actually reaches that part since it's always runs the while loop, so you probably should put your if statement and everything that follows under the while loop.
Also as a suggestion, consider refactoring this code a bit and extract common pieces into reusable parametrized functions and call them instead, this way it would be much easier to read for everyone including yourself and since it will reduce the duplication and code amount chances that you will fall into a similar trap slightly reduce

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

While Loop complication in guess the number game

So I am making a guess the number game in Python 3
After the whole process, I want my while loop to generate another number so that I can start the game again without running the program again.
Please let me know what I'm doing wrong, and if you could provide me with some insight on how to use the while loop, it'll be much appreciated.
Here's the code :
import random
while True:
number = random.randint(1, 1000)
count = 0
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
Not sure if the code you pasted was a typo (on indentation), but I may have accidentally changed your implementation.
Regardless, you should just add another while loop, and a break condition when the user gets it right.
import random
while True:
number = random.randint(1, 1000)
count = 0
while True: # Added, and added another layer of indentation
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
break # Added
In doing so, the code will keep looping to guess the correct number until they are correct. And then generate a new number to guess. However this code will never end unless you add another breaking condition (such as setting a flag the while loop will check to break out of the outer loop.
I wrote some quick code that prompts the user if they want to continue playing or not and then loops through and continues the game with a new number if they want to. I also fixed some minor bugs. Your count kept getting reset in the loop so it would always say you found it in 1 try.
import random
def promptUser():
user_continue = input("Do you want to continue playing? y/n")
if (user_continue == 'y'):
number = random.randint(1, 10)
game(0, number)
def game(count, number):
while True:
guessed = input("Enter the number you guessed: ")
count += 1
if int(guessed) < number:
print("You guessed too low")
elif int(guessed) > number:
print("You guessed too high")
elif int(guessed) == number:
print(f'You guessed right and it took you {count} guesses to the right number which is {number}')
promptUser()
break
promptUser()

Python 3: modified yahtzee/ 3 of a kind, 4 of a kind, 5 of a kind or nothing

I'm writing a modified Yahtzee game in Python 3 called '5 Dice' where the user only wins if they roll a 3, 4, or 5 of a kind. I am using a list for the dice roll but I am having trouble comparing the random list values and now it doesn't even want to work. Please help!
import time
import os
import random
number_of_dice = 5
rolls = []
def dice_roll():
os.system("clear")
print("Welcome to 5 Dice!")
raw_input("Press ENTER to roll")
for q in range(number_of_dice):
rolls.append(random.int(1,6))
rolls.sort()
time.sleep(1)
print(*rolls)
if rolls[0] == rolls[2]:
print("You rolled a three of a kind!")
try_again()
if rolls[0] == rolls[3]:
print("You rolled a four of a kind!")
try_again()
if rolls[0] == rolls[4]:
print("You rolled a five of a kind!")
try_again()
def try_again():
choice = input("Would you like to play again? Y/N: ")
if choice == "Y" or choice == "y":
dice_roll()
if choice == "N" or choice == "n":
quit()
else:
print("Please type Y or N")
I can currently see two problems with your code:
1.
Firstly, your code is indented at the beginning for some reason. This results in an indentation error, which could be why your program is not even working. If you move all the code at the start backwards, it should work.
2.
When you are comparing the dice, you say: if rolls[0] == rolls[2]. This doesn't mean three are the same, because you are only comparing two of the dice! It should be more like: if rolls[0] == rolls[1] == rolls[2]. If you change this, your game should work.
I hope this helps.

Dice Rolling Simulator

I am making a Dice rolling simulator in python to play dnd. I am very new to python so please don't make fun of me if my code is really bad.
import random
while 1 == 1:
dice = input("What kind of dice would you like to roll?: ") # This is asking what kind of dice to roll (d20, d12, d10, etc.)
number = int(input("How many times?: ")) # This is the number of times that the program will roll the dice
if dice == 'd20':
print(random.randint(1,21) * number)
elif dice == 'd12':
print(random.randint(1,13) * number)
elif dice == 'd10':
print(random.randint(1,11) * number)
elif dice == 'd8':
print(random.randint(1,9) * number)
elif dice == 'd6':
print(random.randint(1,7) * number)
elif dice == 'd4':
print(random.randint(1,5) * number)
elif dice == 'd100':
print(random.randint(1,101) * number)
elif dice == 'help':
print("d100, d20, d12, d10, d8, d6, d4, help, quit")
elif dice == 'quit':
break
else:
print("That's not an option. Type help to get a list of different commands.")
quit()
My original attention was just to let it be and not make a number variable, but then my brother reminded me that some weapons have multiple rolls and instead of just rolling more than once, I want to have an input asking how many times to roll the dice. The problem with my code right now is that it will randomize the number and then times it by two. What I want it to do is times the number of different integers and add them together.
Maybe use a for-loop and iterate over the number of times the user wants to roll the dice, while saving those to a list to display each roll of the die.
For example, the first die may look like this:
rolls = []
if dice == 'd20':
for roll in range(number):
rolls.append(random.randint(1,21))
print('rolls: ', ', '.join([str(roll) for roll in rolls]))
print('total:', sum(rolls))
Example output:
What kind of dice would you like to roll?: d20
How many times?: 2
rolls: 10, 15
total: 25
import random
print("Rolling the Dice....")
dice_number = random.randint(1, 6)
print(dice_number)
limit = 0
while limit <= 4:
ask = input("Would you like to roll again?? Yes or No ").upper()
limit = limit + 1
if ask == "YES":
print(random.randint(1, 6))
elif ask == "NO":
print("Thank You.")
break
else:
print("Thank You.")
break
else:
print("Limit Reached..TRY AGAIN!!")

Resources