how to write dice rolling game project. this is my first project - python

did i write correct code
no1 = 1
no2 = 6
enter code here
dice = input("enter number: "):
no1 = int(input("enter number one: "))
no2 = int(input("enter number two: "))
print("you have enter "+str(no1))
print("you have enter "+str(no2))
if dice == "5":
print("you want to roll again")
elif dice == "6":
print("roll dice automatically")
check that you have not incorrectly formatted all of your question as code

There are many ways to write a dice rolling program. However, the simplest way would use a built-in library called random. Below I have fixed and cleaned the code:
import random # The libary used from generating random numbers
def dice_roll(): # function usedto reset the game
input("Press enter to roll the dice ")
print("The dice rolled: ", random.randint(0,6))
UserInputNew = input ("Would you like to roll again? ")
if UserInputNew == "5":
print("\n") # displays a blank line
dice_roll()
else:
print ("Thanks for playing!")
dice_roll() # loads the game
Above would do what you want. From your example above, you have loads of inputs which doesn't make sense from something like a dice roll. If you need help understanding certain bits of the code then I'll be more than happy to help.

help on this one
Alice, Bob and Carol have agreed to pool their Halloween candy and split it evenly among themselves. For the sake of their friendship, any candies left over will be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.
Write an arithmetic expression below to calculate how many candies they must smash for a given haul.

Related

Python occasional list index error when two integer dice held

When I choose to hold two dice it will not always follow the script. It occurs at approximately line 50. Sometimes it doesn't even print the list.
(As a side note- if anyone can simplify the code it would be much appreciated.)
Can anybody help offer a solution and reason for the problem.
(Script is below)
import random
points = 0
final = []
print("Welcome to Yahtzee")
print("Where there are closed questions answer lower case with 'y' or n'")
print("Please be aware that this a variation of the traditional game.\nShould you hold a number- you cannot 'unhold' it.\nIt has been added to your final roll for the round.")
print("Do not be tempted to hold onto a number you haven't rolled\n- this will not work and won't be added to your final score")
def roll_dice():
global collection
collection = []
input("Press Enter to roll the first die")
die_1 = random.randint(1,6)
collection.append(die_1)
print(die_1)
input("Press Enter to roll the second die")
die_2 = random.randint(1,6)
collection.append(die_2)
print(die_2)
input("Press Enter to roll the third die")
die_3 = random.randint(1,6)
collection.append(die_3)
print(die_3)
input("Press Enter to roll the fourth die")
die_4 = random.randint(1,6)
collection.append(die_4)
print(die_4)
input("Press Enter to roll the fifth die")
die_5 = random.randint(1,6)
collection.append(die_5)
print(die_5)
roll_dice()
print(collection)
yeno = input("Would you like to hold any dice? ")
if yeno == "n":
input("This will mean re-rolling all the dice: proceeding...")
del(collection)
roll_dice()
print(collection)
elif yeno == "y":
no = input("How many dice would you like to hold: " )
if no == "1":
num1 = input("Enter the number you would like to keep: ")
num1 = int(num1)
for x in range(len(collection)-1):
if collection[x] == num1:
final.append(num1)
del(collection[x])
print(collection)
print(final)
if no == "2":
num2 = input("Enter the first number you would like to keep: ")
num2 = int(num2)
num3 = input("Enter the second number you would like to keep: ")
num3 = int(num3)
for x in range(len(collection)-1):
if collection[x] == num2:
final.append(num2)
del(collection[x])
for x in range(len(collection)-1):
if collection[x] == num3:
final.append(num3)
del(collection[x])
print(collection)
print(final)
Seems you would do well to read up on what list and the random module has to offer.
Below a suggested simple solution to generate one round of Yatzy.
NOTE: the solution uses formatted string literals so Python 3.6 or greater is needed.
#! /usr/bin/env python3
import sys
import random
greeting = """Welcome to Yatzy
Where there are closed questions answer lower case with 'y' or n'
When asked which dice to hold answer with a list of dice separated by
space.
At most 3 rounds per turn. Between each turn decide what numbers to
keep before rolling again.
Please be aware that this a variation of the traditional game. Should
you hold a number- you cannot 'unhold' it. It has been added to your
final roll for the round.
Do not be tempted to hold onto a number you haven't rolled - this will
not work and won't be added to your final score.
"""
# Assume we have N dice. There are 3 rounds per turn and between
# rounds the player chooses r numbers to keep. The next round will
# then have N - r dice to roll. After each turn the kept dice
# collection is displayed.
#
# The turn stops when 3 rounds have been played or when there are no
# more dice to roll or when the player decides to stop.
def play_one_turn(dice=5, turns=3):
keep = []
msg = "Dice to hold: "
while turns and dice:
turns -= 1
print(f"Kept: {keep}")
play = random.choices(range(1, 7), k=dice)
print(f"Throw --> {play}")
for h in map(int, input(msg).split()):
if h in play:
keep.append(h)
dice -= 1
play.remove(h)
ask = "Another round? (yes/no) "
if not input(ask).strip().upper().startswith('Y'):
break
return keep
if __name__ == "__main__":
print(greeting)
score = play_one_turn()
print(f"Play result {score}")

Python Roll dice with 2 parameters: Number of sides of the dice and the number of dice

This is the problem I have: Write a function roll dice that takes in 2 parameters - the number of sides of the die, and the number of dice
to roll - and generates random roll values for each die rolled. Print out each roll and then return the string
“That’s all!” An example output
>>>roll_dice(6,3)
4
1
6
That's all!
This is the code I have so far using a normal roll dice code:
import random
min = 1
max = 6
roll_dice = "yes"
while roll_dice == "yes":
print random.randint(min,max)
print random.randint(min,max)
print "That's all"
import sys
sys.exit(0)
Try this:
def roll_dice(sides, rolls):
for _ in range(rolls):
print random.randint(1, sides)
print 'That\s all'
This uses a for loop to loop rolls amount of times and prints a random number between 1 and sides each loop.
import random
def roll_dice(attempts,number_of_sides):
for i in range(attempts):
print(random.randint(1, number_of_sides))
print("thats all")
In a more advanced, you can have two parameters where you ask the users input to set the values and it will run the functions and give the numbers rolled, the sum and ask if the user wants to try again.
#Import 'random' module
import random
def main():
#Get values from user to determine slides_per_dice and number_of_die.
sides_per_die = get_value(1,50, 'How many sides should the dice to have
(1-50): ', 'That is not a correct response, enter a value between 1 and
50')
number_of_dice = get_value(1,10, 'How many dice should be rolled (1-10):
', 'That is not a correct response, enter a value between 1 and 10')
#Simulate rolling specified number of dice with specified sides on each
dice.
outcome = rolling_dice (sides_per_die, number_of_dice)
#Asking user if they would like to roll again.
roll_again = input("Would you like to play again (y/n): ") .lower()
while roll_again != 'n':
if roll_again =='y':
main()
else:
print('Error: please enter "y" or "n".')
roll_again = input("Would you like to play again (y/n): ")
#Final message if user ends the game.
print('Thanks for playing.')
#Asking user for side_per_dice and number_of_nice input.
def get_value(lower_limit, upper_limit, prompt, error_message):
number = int(input(prompt))
while number < lower_limit or number > upper_limit:
print(error_message)
number = int(input(prompt))
return number
#Determining the outcome of the rolls and summing up total for all rolls.
def rolling_dice (sides_per_die, number_of_die):
roll_sum = 0
print('Rolling dice .....')
for roll in range (number_of_die):
result = random.randint(1, sides_per_die)
roll_sum += result
print(result, end = " ")
print(f'\nThe sum of all dice rolled is {roll_sum}')
main()

Loop never seems to actually loop

print("Welcome to my dice game.")
print("First enter how many sides you would like your dice to have, 4, 6 or 12")
print("Then this program will randomly roll the dice and show a number")
#Introduction explaing what the game will do. Test 1 to see if it worked.
while True:
#starts a while loop so the user can roll the dice as many times as they find necessary
import random
#Imports the random function so the code will be able to randomly select a number
dice = int(input("Enter which dice you would to use,4, 6, or 12? "))
#set a variable for the amount of dice number
if dice == 12:
x = random.randint(1,12)
print("You picked a 12 sided dice. You rolled a " + str(x) + " well done")
#Test 2 see if it does pick a random number for a 12 sided di
elif dice == 6:
x = random.randint(1,6)
print("You picked a 6 sided dice. You rolled a " + str(x) + " well done")
#Test 3 see if it does pick a random number for a 6 sided di
elif dice == 4:
x = random.randint(1,4)
print("You picked a 4 sided dice. You rolled a " + str(x) + " well done")
#Test 4 see if it does pick a random number for a 4 sided di
else:
print("Sorry, pick either 12, 6 or 4")
#Test 5 tells the user that they can only pick 4, 6 or 12 if anything else is entered this error shows
rollAgain = input ("Roll Again? ")
if rollAgain == "no":
rollAgain = False
if rollAgain == "yes":
rollAgain = True
break
print ("Thank you for playing")
#if the user enters anything apart from yes y or Yes. The code ends here.
That is the code i have so far. However the code will never actually go to the beginning of the loop, no matter what i enter the code just displays "Thanks for playing" and ends. Can anyone please tell me where i have went wrong?
First, you should be using raw_input to get the user's selection. (assuming python 2) If you're using python 3 then input is fine and keep reading.
Anyway, it'll still quit when you type yes because you break out of the loop! You should move the break statement into the "no" case so it breaks out when you say you do not want to roll again.
rollAgain = raw_input ("Roll Again? ")
if rollAgain == "no":
break
You don't need to set rollAgain to true or false at all. With the above code, anything other than "no" is assumed to be "yes" but you can add checks for that easily.
The problem is that you break your loop when the user wants to roll the dice again. The loop should break when the player doesn't want to play again so you have to do :
http://pastebin.com/hzC1UwDM

How do you convert inputted data to uppercase so that it is recognised by a while loop?

I am trying to create a program that allows the user to keep using the program as long as what they enter is YES or a form of yes. I have created the program and it works and continues to loop providing they enter YES in uppercase.
I have tried to modify my code so that at the end when it asks if they would like to repeat it takes the input and converts it to uppercase I know you can use while repeat is in [" "," "] but is there a better way to write the code so that it will convert the inputted data to uppercase on the final input?
I have tried
repeat = input()
repeat = repeat.upper()
but this does not work. Any suggestions?
#Import the random function - This only needs to be imported once.
import random
#Use a while loop to allow the user to repeat the process
repeat = "YES"
while repeat == "YES":
#User is able to input which sided dice they want to throw.
dice = input("What side dice do you want to use? 4, 6, or 12?\n")
#4 sided
if dice == "4":
#Outputs what sided dice has been chosen and the score thay they rolled.
print(dice, "sided dice chose.\nYou rolled a", random.randint(1,4))
#6 sided
elif dice == "6":
print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,6)))
#12 sided
elif dice == "12":
print(dice, "sided dice chose.\nYou rolled a", (random.randint(1,12)))
#Incorrect value entered
else:
#Informs the user that the number they have chosen is not a valid option.
print(dice, "is not a valid choice")
#Asks user if they want to use the program again.
print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
repeat = input()
repeat = repeat.upper()
Your issue appears to be indentation. Since Python identifies code blocks using indentation, it's very important that you get this right.
I noticed your lines are indented as follows:
print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
repeat = input()
repeat = repeat.upper()
Please try indenting them as follows, and it should work:
print("Do you want to use the program again? Yes or No?")
#Links back to the start of the while loop.
repeat = input()
repeat = repeat.upper()
Please look at the Lines and Indentation section here.
You may also have to remove the empty line after your while condition. But maybe not.
Hint: You won't have such problems when using whitespace-ignoring languages such as Java.

Simulate rolling dice in Python?

first time writing here.. I am writing a "dice rolling" program in python but I am stuck because can't make it to generate each time a random number
this is what i have so far
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8)
print("Roll or Quit(r or q)")
now each time that I enter r it will generate the same number over and over again. I just want to change it each time.
I would like it to change the number each time please help
I asked my professor but this is what he told me.. "I guess you have to figure out" I mean i wish i could and i have gone through my notes over and over again but i don't have anything on how to do it :-/
by the way this is how it show me the program
COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r
1
r
1
r
1
r
1
I would like to post an image but it won't let me
I just want to say THANK YOU to everyone that respond to my question! every single one of your answer was helpful! **thanks to you guys I will have my project done on time! THANK YOU
Simply use:
import random
dice = [1,2,3,4,5,6] #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)
import random
computer= 0 #Computer Score
player= 0 #Player Score
print("COP 1000 ")
print("Let's play a game of Chicken!")
print("Your score so far is", player)
r= random.randint(1,8) # this only gets called once, so r is always one value
print("Roll or Quit(r or q)")
Your code has quite a few errors in it. This will only work once, as it is not in a loop.
The improved code:
from random import randint
computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
print('COP 1000') # q and r are initialized to avoid user error, see the bottom description
print("Let's play a game of Chicken!")
player_input = '' # this has to be initialized for the loop
while player_input != 'q':
player_input = raw_input("Roll or quit ('r' or 'q')")
if player_input == 'r':
roll = randint(1, 8)
print('Your roll is ' + str(roll))
# Whatever other code you want
# I'm not sure how you are calculating computer/player score, so you can add that in here
The while loop does everything under it (that is indented) until the statement becomes false. So, if the player inputted q, it would stop the loop, and go to the next part of the program. See: Python Loops --- Tutorials Point
The picky part about Python 3 (assuming that's what you are using) is the lack of raw_input. With input, whatever the user inputs gets evaluated as Python code. Therefore, the user HAS to input 'q' or 'r'. However, a way to avoid an user error (if the player inputs simply q or r, without the quotes) is to initialize those variables with such values.
Not sure what type of dice has 8 numbers, I used 6.
One way to do it is to use shuffle.
import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])
Each time and it would randomly shuffle the list and take the first one.
This is a python dice roller
It asks for a d(int) and returns a random number between 1 and (d(int)).
It returns the dice without the d, and then prints the random number. It can do 2d6 etc. It breaks if you type q or quit.
import random
import string
import re
from random import randint
def code_gate_3(str1):
if str1.startswith("d") and three == int:
return True
else:
return False
def code_gate_1(str1):
if str1.startswith(one):
return True
else:
return False
def code_gate_2(str2):
pattern = ("[0-9]*[d][0-9]+")
vvhile_loop = re.compile(pattern)
result = vvhile_loop.match(str1)
if result:
print ("correct_formatting")
else:
print ("incorrect_formattiing")
while True:
str1 = input("What dice would you like to roll? (Enter a d)")
one, partition_two, three = str1.partition("d")
pattern = ("[0-9]*[d][0-9]+")
if str1 == "quit" or str1 == "q":
break
elif str1.startswith("d") and three.isdigit():
print (random.randint(1, int(three)))
print (code_gate_2(str1))
elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
for _ in range(int(one)):
print (random.randint(1, int(three)
print (code_gate_2(str1))
elif (str1.isdigit()) != False:
break
else:
print (code_gate_2(str1))
print ("Would you like to roll another dice?")
print ("If not, type 'q' or 'quit'.")
print ("EXITING>>>___")
This is one of the easiest answer.
import random
def rolling_dice():
min_value = 1
max_value = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
print("Rolling dices...")
print("The values are...")
print(random.randint(min_value, max_value))
print(random.randint(min_value, max_value))
roll_again = input("Roll the dices again? ")
rolling_dice()

Categories

Resources