Dice Rolling Simulator - python-3.x

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

Related

Python3: How to loop my dice roller program back to the start

Writing my first solo program with no help from teacher or group, a simple code that can act as a D&D dice roller for any type or number of dice a user requires.
I've been working on it for about four hours, and I'm stuck on the last thing I want to do which is loop it back to the beginning instead of just ending when a user doesn't reroll the already chosen dice, I'd like it so it starts again from the top so the player can input a new dice value and number of rolls generated without closing the program and rerunning it.
import random
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
You might try something like:
import random
while True:
try:
min = 1
max = int(input("Enter the highest value of dice to be rolled or 0 to exit: "))
except:
print("Your input was invalid, program rolled a d20 by default")
min = 1
max = 20
if max == 0:
break
if max < 0:
continue
again = True
number_of_dice = int(input("Enter number of dice to roll: "))
for i in range(number_of_dice - 1):
print(random.randint(min, max))
while again:
print(random.randint(min, max))
reroll = input("Roll again? (y/n): ")
if reroll.lower() == "y" or reroll.lower() == "yes":
for i in range(number_of_dice - 1):
print(random.randint(min, max))
else:
print("Thank you")
break
Also, I would suggest renaming "min" and "max" as they are reserved keywords

How To Limit The Times a User Could Input

Hi I'm a beginner Making a Game Where The Program Generates a random Number And The User Needs To Guess The Number. If They Fail 5 Times They Lose. I Need To Count How Many Times The User Can Enter And If It Reaches 5 And Print You Lost And restart.
Something Like This
cnt = 0
if cnt >= 5:
print("You Lost")
pass
You need :
import random
op_number = random.randint(1,20)
# print(op_number)
number = int(input("Guess a number between 1 to 20 : "))
count=0
while True:
if count == 5:
print("You Lose.")
break
count+=1
if op_number == number:
print("You won")
break
else:
print("Incorrect guess. {} attempts left.".format(5-count))
number = int(input("Guess a number between 1 to 20 : "))

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.

I don't know why the variable doesn't add up

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.

Resources