I need help condensing my Yahtzee code. I'm familiar with loops, but I can't seem to figure out how to do it without wiping my roll each turn. It's set up to roll 5 random dice and then you choose which you want to keep. It will then roll what's left for three total rolls. I thought of making a placeholder list, but I can't make it work that way either.
Dice = [‘⚀ ’,‘⚁ ‘,’ ⚂ ‘,’ ⚃ ‘,’ ⚄ ‘,’ ⚅ ‘]
turns = 3
#first roll
first_roll = []
for _ in range(5):
roll = random.choice(dice)
first_roll.append(roll)
print(first_roll)
turns -= 1
print(f'You have {turns} turns left.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#second roll
second_roll = []
for i in keep:
x = int(i)
j = first_roll[x-1]
second_roll.append(j)
remainder = 5 - len(second_roll)
for _ in range(remainder):
roll = random.choice(dice)
second_roll.append(roll)
print(second_roll)
turns -= 1
print(f'This is your last turn.')
keep = input("Which dice would you like to keep? 1 - 5: ").split()
clear()
#third roll
third_roll = []
for i in keep:
x = int(i)
j = second_roll[x-1]
third_roll.append(j)
remainder = 5 - len(third_roll)
for _ in range(remainder):
roll = random.choice(dice)
third_roll.append(roll)
print(third_roll)
So I'm not sure if this is exactly what you're looking for, but I created a function that lets you continuously roll for X turns and the dice pool gets progressively smaller like your code shows. I thoroughly commented the code to hopefully give you a good explanation to what I'm doing.
import random
#Dice characters
dice = ['1','2','3','4','5','6']
#Number of turns player has
turns = 3
#This is the group of dice kept by the player
kept_dice = []
def roll():
#This is the group of dice randomly chosen
rolled_dice = []
#Generate up to 5 random dice based on how many have been kept so far
for _ in range(5 - len(kept_dice)):
#Append random dice value to rolled_dice array
rolled_dice.append(random.choice(dice))
#Print roll group
print(rolled_dice)
dice_to_keep = int(input("Which dice would you like to keep? 1 - 5: "))
kept_dice.append(rolled_dice[dice_to_keep-1])
while turns != 0:
#Let the user know how many turns they have left
print(f'You have {turns} turns left.')
#Roll dice
roll()
#Subtract 1 turn
turns -= 1
#After all turns, show the kept dice:
print("Kept dice:")
print(kept_dice)
Related
Im trying to make a loop where I start with 5 random dice rolls. the values 1,3,4, and 6 are added up for your score, while 2s and 5s are not counted and subtract the combined amount of dice rolled with 2s and 5s from the amount of dice rolled the next turn. I can't quite figure out how to get the sum of only the dice that rolled 1,3,4,6 and roll a lesser amount of dice the next turn based off ho many dice were 2 or 5
#Stuck in the Mud Dice Game
Exit = 0
Rolls = int(5)
score = 0
def RollDice():
totalsum = 0
for die in range(0, Rolls):
number = random.randint(1,6)
print("die", die + 1, ":", number)
totalsum += number
print("score: ", totalsum)
def Menu():
print("1. Roll Dice")
print("2. Exit Program")
print()
choice = int(input("Enter option here: "))
if(choice == 1):
RollDice()
if(choice == 2):
Exit()
Menu()
In the for-loop, use an if statement:
if number==2 or number==5:
Rolls -= 1
else:
totalsum += number
I suppose that you also need to start your function RollDice like this:
def RollDice():
global Rolls
...
otherwise, it might only locally (i.e., within the function) assign a new value to the variable.
Or do you mean the number of Rolls should be different when you re-start the program? This can only be done by writing the value to a file.
I'm trying to make a code for a multiplayer dice rolling game where the user can input how many players.
I want the code to repeat until a player reaches 100 points and go on a cycle between all the players.
I've tried all sorts of functions/modules for this and asked peers and some teachers, searched online for this and all over stack overflow but couldn't find an answer.
playerPoints = {}
toRoll = ""
minPlayers = 2
maxPlayers = 4
winner = 100
double1 = 25
def players(numberOfPlayers):
numberOfPlayers = 0
while numberOfPlayers not in (str(i) for i in range (minPlayers,maxPlayers)):
numberOfPlayers = int(numberOfPlayers)
for i in range(numberOfPlayers):
playerPoints["score{}".format(i+1)] = 0
return numberOfPlayers
def diceroll():
die1 = randint(1,6)
die2 = randint(1,6)
return die1, die2
roll = 0
while roll not in (str(i) for i in toRoll):
roll = input("Press enter to roll both dice")
if roll == toRoll:
print(str(die1) + " and " + str(die2))
break
I want the code to continue however I am stuck at this point where the code only asks how many players are there and then breaks.
I called the function by doing:
numberOfPlayers = input("How many players are there? (2-4)")
players(numberOfPlayers)
diceroll(die1, die2)
roll()
Possible fix for your problem
There are all kinds of return statements in your code which makes it impossible for some code to be executed. Like in the diceroll function where you return die1 and die2 in:
return die1, die2
The code after that line is never exectuted because the function returns some values.
You say that you execute the function like so:
numberOfPlayers = input("How many players are there? (2-4)")
players(numberOfPlayers)
diceroll(die1, die2)
roll()
However, the diceroll function takes zero parameters, while you give it two (die1 and die2), this won't work. Also I don't see a roll function in your code, so that will give you an error as well.
How I would have done it
So, I know StackOverflow is not the place where we write code for you. But since there were all kinds of things in your code that I found weird. I have rewritten the code as how I would have done it:
import random
playerPoints = []
minPlayers = 2
players = 0
maxscore = 100
amountOfDice = 2
gameRound = 0
def setPlayers():
while True:
players = input("How many players are playing?\n")
if players.isdigit():
players = int(players)
if minPlayers <= players:
for i in range(players):
playerPoints.append(0)
return players
def diceroll(player, amountOfDice):
throw = 0
print("\tPlayer {0}s turn:".format(player + 1))
for i in range(amountOfDice):
die = random.randint(1, 6)
print("\t\tPlayer {0} has thrown die {1} which landed on {2}".format(player + 1, i + 1, die))
throw += die
playerPoints[player] += throw
print("\tPlayer {0}s score is now: {1}".format(player + 1, playerPoints[player]))
return throw
def checkWin(maxscore):
for player in range(players):
if (playerPoints[player] >= maxscore):
print("Player {0} wins!".format(player + 1))
return True
return False
if __name__ == "__main__":
players = setPlayers()
while True:
gameRound += 1
print("Round: {0}".format(gameRound))
for i in range(players):
diceroll(i, amountOfDice)
if (checkWin(maxscore)):
break
Now, first off, I removed some restrictions in the players function (and changed the name to setPlayers). Your code didn't have a check if the input was a number, which could result in an error. I also removed the restriction of 4 players, because the code works with every amount (if 2 or higher ofcourse).
The diceroll function now takes the player that will roll as an argument as well as the amount of dice that will be rolled.
I also added the checkWin function which checks if a player has won. It takes the maximum score as an argument.
Now this probably isn't the fastest code, however I think its understandable. If you have any questions about it, feel free to ask.
Need help adding a while loop to my code to start it from the beginning again after the user agrees to it. Every time I add it at the end of the code it skips it when I run it and I'm not sure how to do it at all. Any help is welcomed. Thank you!
print('Welcome to the Dice Game')
print(" ")
print('This program will simulate rolling a dice and will track the frequency each value is rolled.')
print(" ")
print('After rolling the dice, the program will output a summary table for the session.')
print(" ")
raw_input("Press Enter to continue...")
# function to roll the dice and get a value
def roll_dice():
r=random.randint(1,6)
return r
#to track the number of times rolled the dice
rolled=0
# to track the number of remaining turns
remaining=10000
# list to store the results
result=[]
# to track the number of sessions
sessions=0
while True:
#incrementing the session variable
sessions+=1
#getting the number of turns from the user
n=int(input("How many times would you like to roll the dice? "))
#checking the number of turns greater than remaining turns or not
if n > remaining:
print('You have only remaining',remaining)
continue
#rolling the dice according to the value of n
if rolled <= 10000 and n <= remaining :
for i in range(n):
result.append(roll_dice())
#updating the remaining turns and rolled variables
remaining=remaining-n
rolled=rolled+n
#printing the results and session variable
if rolled==10000:
print('---------------')
for i in range(len(result)):
print('|{:7d} | {:d} |'.format( i+1,result[i]))
print('---------------')
print('Rolled 10000 times in %d sessions' % sessions)
sys.exit(0)
Your rolled, remaining, result and sessions variables persist on the next iteration of the while loop. You need to redefine the variables on each iteration of the loop, because you're checking against the remaining variable to check if the user's turn is over. So instead of:
def roll_dice():
# ...
rolled = 0
remaining = 10000
result = []
sessions = 0
while True:
# ...
you need:
def roll_dice():
# ...
while True:
rolled = 0
remaining = 10000
result = []
sessions = 0
# ...
I see many unnecessary variables and comparisons in your code, a cleaner code usually results less bugs and better readability.
I suggest something like this:
def do_dice_game(rounds=1000):
sessions = 0
rolls = []
while rounds > 0:
sessions += 1
user_input = rounds + 1
while user_input > rounds:
user_input = int(raw_input("..."))
rolls += [random.randint(1, 6) for i in range(user_input)]
rounds -= user_input
# print something
def do_games():
to_continue = True
while to_continue:
do_dice_game()
to_continue = raw_input("...") == "continue"
Also, according to your code, numbers of each session has no effect on the final "rolled" result. You can always just record the number of sessions and then roll 1000 random numbers at the end.
So I had to make code that roll a die fairly and counted how many 4's I got. With the help of people on here I got it to work. Well now I have to created another die and roll them and then add they products together. This is the instructions I've been given.
"Then write another function that simulates rolling two fair dice. The easy way is to call the function you just wrote, twice, and add the numbers you get.
This should return a number between 2 and 12."
I've added rolling the dice a second time but how do I add the sums of the two rolls together is my question?
And this is my code.
from random import randrange
def roll():
rolled = randrange(1,7)
if rolled == 1:
return "1"
if rolled == 2:
return "2"
if rolled == 3:
return "3"
if rolled == 4:
return "4"
if rolled == 5:
return "5"
if rolled == 6:
return "6"
def rollManyCountTwo(n):
twoCount = 0
for i in range (n):
if roll() == "2":
twoCount += 1
if roll() == "2":
twoCount +=1
print ("In", n,"rolls of a pair of dice, there were",twoCount,"twos.")
rollManyCountTwo(6000)
You shouldn't have to deal with strings at all, this could be done entirely using int values
from random import randint
def roll():
return randint(1,6)
def roll_twice():
total = 0
for turn in range(2):
total += roll()
return total
For example
>>> roll_twice()
10
>>> roll_twice()
7
>>> roll_twice()
8
And for your function that is supposed to count the number of 2s that were rolled, again you can do integer comparison
def rollManyCountTwo(n):
twos = 0
for turn in range(n):
if roll() == 2:
twos += 1
print('In {} rolls of a pair of dice there were {} twos'.format(n, twos))
return twos
>>> rollManyCountTwo(600)
In 600 rolls of a pair of dice there were 85 twos
85
from random import randint
def roll():
return randint(1,6)
def rollManyCountTwo(n):
twoCount = 0
for _n in xrange(n*2):
if roll() == 2:
twoCount += 1
print "In {n} rolls of a pair of dice, there were {cnt} twos.".format(n=n, cnt=twoCount)
Since you roll two dices for n times and count every single two rolled, just loop for n*2 and check if the dice result is two.
This is my homework question:
Write a program that simulates rolling a set of six-sided dice multiple times. The program should use a dictionary to record the results and then display the results.
Input: The program should prompt for the number of dice to roll and the number of times to roll the dice.
Output:
The program is to display how many times each possible value was rolled. The format of the output must be as shown below:
The first column is the number shown on the dice when they are rolled. The brackets are only as wide as needed and the number inside the brackets is right justified. Note the minimum and maximum values in the sample runs below.
The second column is the number of times that value was rolled. This column is right justified.
The last column is the percent of times that the number was rolled. The percentages are displayed with an accuracy of one decimal place.
This is the code I have so far:
import random
from math import floor, ceil
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
rand = float(0)
rolltotal = int(input("How many times do you want to roll? "))
q = 0
while q < rolltotal:
q = q + 1
rand = ceil(6*(random.random()))
if rand == 1:
one = one + 1
elif rand == 2:
two = two + 1
elif rand == 3:
three = three + 1
elif rand == 4:
four = four + 1
elif rand == 5:
five = five + 1
else:
six = six + 1
total = one + two + three + four + five + six
print("[1]", one, " ",round(100*one/total, 1),"%")
print("[2]", two, " ",round(100*two/total, 1),"%")
print("[3]", three, " ",round(100*three/total, 1),"%")
print("[4]", four, " ",round(100*four/total, 1),"%")
print("[5]", five, " ",round(100*five/total, 1),"%")
print("[6]", six, " ",round(100*six/total, 1),"%")
My question is: I just know how to roll one dice. how can i get more than one .
from collections import defaultdict
import random
dice = int(input("How many dice do you want to roll? "))
rolls = int(input("How many times do you want to roll them? "))
irange = xrange
sides = [1,2,3,4,5,6]
d = defaultdict(int)
for r in irange(rolls):
d[sum( random.choice(sides) for d in irange(dice) )] += 1
total = float(rolls)
for k in sorted(d.keys()):
print "[%d] %d %.1f%%" % (k, d[k], 100.0*d[k]/total)
You would rather do the following:-
loop=True
import random #This allows python to import built in "random" function.
while loop is True:
dice=input("Which sided dice would you like to roll? (You can only choose 4,6 or 12) \n") # "\n" allows python to add a new line.
if dice=="4":
print("You have chosen to roll dice 4\nYour score is... \n", random.randint(1,4)) #This allows python to generate a random number from 1 to 4.
elif dice=="6":
print("You have chosen to roll dice 6\nYour score is...\n", random.randint(1,6)) #This allows python to generate a random number from 1 to 6.
elif dice=="12":
print("You have chosen to roll dice 12\nYour score is...\n", random.randint(1,12)) #This allows python to generate a random number from 1 to 12.
else: print("Invalid option! Please try again!")
loop2=input("Do you want to roll again? (Yes or No) \n")
if loop2=="yes" or loop2=="Yes": # "or" funtion allows python to accept any of the two answers input by the user.
loop=True
else: break # This function allows program to close.