Counting/random int in while loop - python

I want this while loop to change numbers with every iteration (both the count and random int.) but when I run the program, the loop just goes on with the same numbers on the count and random int.:
# if 4 sides
die1 = random.randint(1,4)
die2 = random.randint(1,4)
count = 1
while sides == 4 and die1 != die2:
print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
count == count + 1
print ("You got snake eyes! Finally! On try number", count,".")

Each time you call random.randint(1,4), you are creating a single random number. It does not magically change to a new random number whenever you print it.
Generate new random numbers with random.randint(1, 4) inside your while loop.
The second problem is that count == count + 1 checks for equality (and returns False in your case). To do an assignment, use the assignment operator = or count += 1 to increment count by one.
If you want a generator that endlessly spits out random numbers, write one:
>>> import random
>>> def rng(i, j):
... while True:
... yield random.randint(i, j)
...
>>> random_gen = rng(1, 4)
>>> next(random_gen)
2
>>> next(random_gen)
3
>>> next(random_gen)
2
>>> next(random_gen)
2
>>> next(random_gen)
1

You need to do the random calls also inside the while loop otherwise they will not change. And the other thing is that you compare == and not set = the counter:
import random
sides = 4
count = 1
die1 = random.randint(1,4)
die2 = random.randint(1,4)
while sides == 4 and die1 != die2:
print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
count += 1
die1 = random.randint(1,4)
die2 = random.randint(1,4)
print ("You got snake eyes! Finally! On try number", count,".")
Trying a test run gives me:
1 . die number 1 is 4 and die number 2 is 3 .
2 . die number 1 is 2 and die number 2 is 1 .
3 . die number 1 is 1 and die number 2 is 2 .
4 . die number 1 is 3 and die number 2 is 4 .
5 . die number 1 is 1 and die number 2 is 4 .
You got snake eyes! Finally! On try number 6 .
One alternative that is almost identical but uses break instead of conditions on the while loop would be:
import random
sides = 4
count = 1
def tossdie():
"""Function to create a random integer for a die"""
return random.randint(1,4)
while True:
die1 = tossdie()
die2 = tossdie()
print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
if die1 == die2:
break
count += 1
print ("You got snake eyes! Finally! On try number", count,".")

Not sure why you needed the sides variable, so I left it out.
You want to roll the die in every loop, which means you have to re-assign die1 and die2 to a random number in each loop.
import random
# Initial parameters
die1 = random.randint(1,4)
die2 = random.randint(1,4)
count = 1
# Loop and roll die each time
while die1 != die2:
print(count, ". die number 1 is", die1, "and die number 2 is", die2,".")
die1 = random.randint(1,4)
die2 = random.randint(1,4)
count += 1
# Print on which die roll you got two equal die numbers rolled
print ("You got snake eyes! Finally! On try number", count,".")

You can use a for loop with iter to spit out pairs of random numbers , enumerate will do the counting, for snake-eyes you should also be checking that both are 1's not a random matching pair:
from random import randint
def repeating_rand(i, j):
for count, (r1, r2 ) in enumerate(iter(lambda: (randint(i, j), randint(i, j)), None), 1):
if r1 == 1 and r2 == 1:
return "You got snake eyes! Finally! On try number {}.".format(count)
print("Try no. {}, die number 1 is {} and die number 2 is {}".format(count, r1, r2))
Output:
In [12]: repeating_rand(1, 4)
Try no. 1, die number 1 is 1 and die number 2 is 2
Try no. 2, die number 1 is 4 and die number 2 is 1
Try no. 3, die number 1 is 1 and die number 2 is 2
Try no. 4, die number 1 is 1 and die number 2 is 3
Try no. 5, die number 1 is 1 and die number 2 is 3
Try no. 6, die number 1 is 3 and die number 2 is 4
Try no. 7, die number 1 is 4 and die number 2 is 2
Try no. 8, die number 1 is 1 and die number 2 is 2
Try no. 9, die number 1 is 3 and die number 2 is 2
Try no. 10, die number 1 is 4 and die number 2 is 3
Try no. 11, die number 1 is 1 and die number 2 is 3
Try no. 12, die number 1 is 3 and die number 2 is 4
Out[12]: 'You got snake eyes! Finally! On try number 13.'

Related

How can I get repeating functions of a script and variable changes

I need to make a game based on the 'drinking' game Ship, Captain, Crew. The game consists of rolling 5 dies, and if the numbers are equal to 6,5,4 (in that order), you win. 6 is the Ship, 5 is the Captain and 4 is the crew. I wrote basic script but I'm still having issues. I have an issue where when I execute the script, the rolls never stop as I'm having issues telling the "roll = random.randint(1,6)" to only run 5 times then stop. Also, 'Dice' Is trying to define the number of rolls. So for example: after the dice has been rolled 5 times, Dice would = 5. I need help making it so that the script recognises that the dice must be rolled 5 times, and when it is, if the numbers rolled were not 6,5 and 4, end the game. Can anyone help?
Code:
import random
Dice = 0
SHIP_CAPTAIN_CREW = 6, 5, 4
SHIP = 6
CAPTAIN = 5
CREW = 4
WINNING_SCORE = 6, 5, 4
while Dice != WINNING_SCORE:
roll = random.randint(1,6)
print ("You Rolled A", roll)
if roll == SHIP:
print("You found the ship!")
if roll == CAPTAIN:
print("You found the Captain")
if roll == CREW:
print("You found the Crew!")
if roll == SHIP:
score = +1
roll
else:
Dice = roll
if roll == CAPTAIN :
score = +1
roll
else:
Dice += roll
if Dice == 5:
break
print ("Dice:", roll)
Since you want to run it a set number of times, a for loop with a range would be better.
Additionally, the code you have now doesn't check to make sure the numbers are rolled in the correct order.
import random
needed_value = 6; #the next roll you need
for x in range(5) :
roll = random.randint(1,6)
print ("You Rolled A", roll)
if roll == 6:
print("You found the ship!")
if(needed_value == 6):
needed_value = 5 #update the next needed number
if roll == 5:
print("You found the Captain")
if(needed_value == 5):
needed_value = 4 #update the next needed number
if roll == 4:
print("You found the Crew!")
if(needed_value == 4):
print ("Win!") #all three were found in order
break #the game has been won so no need to continue with loop
If I understood your game and your expectation well, this might be the answer.
import random
def drinking():
names = ['crew', 'captain', 'ship']
winning_order = '654'
score = ''
for _ in range(5):
dice = random.randint(1, 6)
print(f"You Rolled A {dice}")
if 4 <= dice <= 6:
print(f'You found the {names[dice - 4]}')
score += str(dice)
elif score == winning_order:
return f'Dice:, {dice}' # You won the game would be ideal
return 'You lose the game'
print(drinking())
You Rolled A 6
You found the ship
You Rolled A 6
You found the ship
You Rolled A 5
You found the captain
You Rolled A 1
You Rolled A 3
You lose the game
I made some heavy modifications to your code. I was hoping to keep it easy to understand, while still doing everything you're expecting, and also making it easy to modify.
import random
# I put the logic inside a function so you can call it
# DiceRound() will return 0 on wins, and -1 on losses
def DiceRound():
SHIP = 6
CAPTAIN = 5
CREW = 4
Counter = 0 # keeps track of how many rolls we've made
WINNING_SCORE = 0 # modified to keep track of win-condition
dierolls = "" # used for output
while WINNING_SCORE != 3 and Counter < 5:
v = 0 # verbate
roll = random.randint(1,6)
Counter = Counter +1
dierolls = dierolls + "[%d] "%roll
# Any time we roll 6, we're 1-roll towards victory
if roll == SHIP:
WINNING_SCORE = 1
# If we roll a 5 when we've already rolled a 6
if roll == CAPTAIN and WINNING_SCORE == 1:
WINNING_SCORE = 2
# Elsewise if we just rolled a 5
elif roll == CAPTAIN and WINNING_SCORE != 1:
WINNING_SCORE = 0
# If we roll a 4 when we've already rolled a 6 and a 5
if roll == CREW and WINNING_SCORE == 2:
WINNING_SCORE = 3
print(dierolls)
print("... Round won!", end="")
return(0) # return; exits loop and returns 0 for Win-condition
# Elsewise if we just rolled a 4
elif roll == CREW and WINNING_SCORE != 2:
WINNING_SCORE = 0
# If we rolled below a 4, anytime
if roll < 4:
WINNING_SCORE = 0
# If we rolled all five times without winning
print(dierolls)
print("... Round lost.", end="")
return(-1) # return; exits loop and returns -1 for Lose-condition
Output from this script will look somewhat like this if you call DiceRound() until the return == 0:
[1] [6] [1] [5] [5] ... Round lost.
[3] [6] [4] [5] [3] ... Round lost.
[4] [2] [5] [4] [4] ... Round lost.
[2] [2] [6] [5] [4] ... Round won!

Ending a while loop

I'm currently writing code for a dice game in Python 3.6 I understand my coding is a little off in this, however, I'm really just wondering how to start my while loop. The instructions of the game are as follows...
A human player plays against the computer.
Player 1 rolls until they either win, decide to hold, or roll a 1.Same for player 2.
They take turns rolling two dice, and the totals of the dice are added together Unless a 1 is rolled.
If a one 1 is rolled, you get no score added and it's the next person's turn. If two 1's are rolled, you lose all of your points and its the next person's turn.
The first player to 100 score, wins the game.
My game works fine until Player 1 and Player 2 both hit "y" to hold back to back. Then the game quits switching between player's until "n" to not hold is hit again. Any idea why?
I was told I need variables to decide who's turn it is but I'm not sure how to incorporate them into my code.
Any help would be appreciated.
import random
def main():
print("Welcome to the Two Dice Pig Game. You are Player 1!")
Player1 = 0
Player2 = 0
while(Player1<100 and Player2<100):
p1dice=random.randrange(1,7)
p1dice2=random.randrange(1,7)
Player1+=p1dice+p1dice2
print("Player 1 dice 1 =",p1dice)
print("Player 1 dice 2 =",p1dice2)
print("Player 1 dice total =",Player1)
print("Does player 1 want to hold?")
choose1 = input("Enter y for yes or n for no.")
if(choose1=="n"):
p1dice=random.randrange(1,7)
p1dice2=random.randrange(1,7)
Player1+=p1dice+p1dice2
print("Player 1 dice 1 =",p1dice)
print("Player 1 dice 2 =",p1dice2)
print("Player 1 dice total =",Player1)
if(Player1>=100):
print("Player 1 wins!")
else:
print("Does player 1 want to hold?")
choose1 = input("Enter y for yes or n for no.")
while(choose1=="y"):
print("It's player 2's turn.")
p2dice=random.randrange(1,7)
p2dice2=random.randrange(1,7)
Player2+=p2dice+p2dice2
print("Player 2 dice 2 =",p2dice)
print("Player 2 dice 2 =",p2dice2)
print("Player 2 dice total =",Player2)
print("Does player 2 want to hold?")
choose2 = input("Enter y for yes or n for no.")
while(choose2=="n"):
p2dice=random.randrange(1,7)
p2dice2=random.randrange(1,7)
Player2+=p2dice+p2dice2
print("Player 2 dice 2 =",p2dice)
print("Player 2 dice 2 =",p2dice2)
print("Player 2 dice total =",Player2)
print("Does player 2 want to hold?")
choose2 = input("Enter y for yes or n for no.")
while(choose2=="y"):
print("It's player 1's turn.")
p1dice=random.randrange(1,7)
p1dice2=random.randrange(1,7)
Player1+=p1dice+p1dice2
print("Player 1 dice 2 =",p1dice)
print("Player 1 dice 2 =",p1dice2)
print("Player 1 dice total =",Player1)
print("Does player 1 want to hold?")
choose2 = input("Enter y for yes or n for no.")
main()
Use a dict to keep a score per player name, switch a turn that holds the player currently throwing dice.
Implemented some logic as when to change turn from one to the other:
import random
def score(players):
for k in players:
print("{} has {} points".format(k,players[k]))
def hold(player):
if input("Does {} want to hold? [y or anything]".format(player)).lower().strip() == "y":
return "y"
return "n"
def main():
dice = range(1,7)
players = {"p1":0, "p2":0}
turn = ""
change_player = "y"
print("Welcome to the Two Dice Pig Game. You are Player 1!")
while all(x < 100 for x in players.values()):
# initially changePlayer is
if change_player == "y":
# print both scores on player changed
score(players)
turn = "p1" if turn != "p1" else "p2"
dice1, dice2 = random.choices(dice,k=2)
print("{} threw {} and {} for a total of {}".format(turn,d1,d2,d1+d2))
if dice1 + dice2 == 2:
players[turn] = 0
print("Two 1 - you're done for now. Your points go back to 0.")
change_player = "y"
elif dice1 == 1 or dice2 == 1:
print("One 1 - you're done for now.")
change_player = "y"
else:
# only case where we need to add values and print new score
players[turn] += dice1 + dice2
print("Your score: {}".format(players[turn]))
if turn == "p1":
change_player = hold(turn)
else:
change_player = "n" # computer is greedy, never stops
winner, points = max(players.items(),key=lambda x: x[1])
print("The winner is {} with {} points.".format(winner,points))
main()
Output:
Welcome to the Two Dice Pig Game. You are Player 1!
p1 has 0 points
p2 has 0 points
p1 threw 5 and 1 for a total of 6
One 1 - you're done for now.
p1 has 0 points
p2 has 0 points
p2 threw 3 and 6 for a total of 9
Your score: 9
p2 threw 6 and 2 for a total of 8
Your score: 17
p2 threw 4 and 1 for a total of 5
One 1 - you're done for now.
p1 has 0 points
p2 has 17 points
p1 threw 4 and 5 for a total of 9
Your score: 9
Does p1 want to hold? [y or anything]
p1 threw 2 and 6 for a total of 8
Your score: 17
Does p1 want to hold? [y or anything]
p1 threw 4 and 6 for a total of 10
Your score: 27
[snipp]
One 1 - you're done for now.
p1 has 91 points
p2 has 51 points
p1 threw 6 and 4 for a total of 10
Your score: 101
Does p1 want to hold? [y or anything]
The winner is p1 with 101 points.
You would want to simplify your code by doing something like this:
# Keep track of whose turn it is
player = 1
# Keep a dictionary of scores for each player (1 or 2)
scores = {1: 0, 2: 0}
choice = 'n'
# While neither player has > 100
while max(d.values()) < 100:
# Roll until current player decides to keep roll
while choice == 'n':
print('Player', player, 'turn')
roll = random.randrange(1,7) + random.randrange(1,7)
print('You rolled', roll)
choice = input('Keep roll? y/n')
# Increment that player's score
scores[player] += roll
choice = 'n'
# Change to other player
player = (player % 2) + 1
Because once you've set a choice for choose1, it never gets set again. The quick way to fix this would be to add an input after the two while loops for choose2, although you may want to look into making your code neater through making functions for the common logic
while(choose2=="y"):
....
choose1 = input("Enter y for yes or n for no.")

dice roll simulation in python

I am writing a program that is to repeatedly roll two dice until the user input target value is reached. I can not figure out how to make the dice roll happen repeatedly. Please, help...
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input = int (input("Enter the target sum to roll for:"))
#def main():
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input:
print ("All done!!")
if sumofRoll != input:
#how do I make this repeatedly run until input number is reached?!
Here is a complete working code which takes care of invalid sum entered as input as well. The sum of two dice rolls cannot be either less than 2 or more than 13. So a check for this condition makes your code slightly more robust. You need to initialize sumofRoll = 0 before entering the while loop as this would be needed to first enter the while loop. The value of 0 is a safe value because we excluded the value of 0 entered by user to be a valid sum.
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input_sum = int(input("Enter the target sum to roll for:"))
def main():
sumofRoll = 0
if input_sum < 2 or input_sum > 13:
print ("Enter a valid sum of dices")
return
while sumofRoll != input_sum:
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input_sum:
print ("All done!!")
main()
This program rolls two 6-sided dice until their sum is a given target value.
Enter the target sum to roll for:10
Roll: 3 and 5, sum is 8
Roll: 6 and 6, sum is 12
Roll: 5 and 1, sum is 6
Roll: 2 and 5, sum is 7
Roll: 6 and 6, sum is 12
Roll: 3 and 5, sum is 8
Roll: 1 and 2, sum is 3
Roll: 6 and 4, sum is 10
All done!!
I took your game and added some elements for you to peek through. One is you could use random.choice and select from a die list instead of generating new random ints repeatedly. Second you can use a try/except block to only accept an int and one that is within the range of (2, 13). Next we can add a roll_count to track the amount of rolls to hit our target. Our while loop will continue until target == roll_sum and then we can print our results.
from random import choice
die = [1, 2, 3, 4, 5, 6]
print('This program rolls two 6-sided dice until their sum is a given target.')
target = 0
while target not in range(2, 13):
try:
target = int(input('Enter the target sum to roll (2- 12): '))
except ValueError:
print('Please enter a target between 2 and 12')
roll_sum = 0
roll_count = 0
while target != roll_sum:
die_1 = choice(die)
die_2 = choice(die)
roll_sum = die_1 + die_2
roll_count += 1
print('You rolled a total of {}'.format(roll_sum))
print('You hit your target {} in {} rolls'.format(target, roll_count))
...
You rolled a total of 4
You rolled a total of 12
You hit your target 12 in 29 rolls
This is a simple while loop:
sumofRoll = -1; #a starting value!
while sumofRoll != input:
#Put the code that updates the sumofRoll variable here
count = 0
while(sumOfRoll != input):
dice1 = randrange(1,7)
dice2 = rangrange(1,7)
count = count + 1
sumOfRoll = dice1 + dice2
print("sum = %s, took %s tries" % (sumOfRoll, count))
Use a do while statement
do:
dice1=randrange(1,7)
...
while(sumofroll != input)
print("all done")

Dice counter error

Im making a program in python 2.7 that are going to roll dices, and then count how many times each number gets rolled. But cant seem to figure out this problem.
it returns: Traceback (most recent call last):
File "DiceRoller.py", line 16, in
counter[s] += 1
KeyError: 3
from random import randint
while True:
z = raw_input("How many sides should the dice(s) have?\n> ")
i = 0
x = raw_input("How many dices do you want?\n> ")
dice = {}
while i <= int(x):
dice[i] = randint(1,int(z))
i += 1
counter = {}
for p, s in dice.iteritems():
counter[s] += 1
print counter
raw_input("Return to restart.")
You are setting each counter to the value +1:
counter[s] =+ 1
# ^^^
You are not using += there; Python sees that as:
counter[s] = (+1)
Swap the + and the =:
counter[s] += 1
This will raise an exception as the key s is not going to be present the first time; use counter.get() to get a default value in that case:
counter[s] = counter.get(s, 0) + 1
or use a collections.defaultdict() object rather than a regular dictionary:
from collections import defaultdict
counter = defaultdict(int)
for s in dice.itervalues():
counter[s] =+ 1
or use a collections.Counter() object to do the counting:
from collections import Counter
counter = Counter(dice.itervalues())
Use xrange and just increment each count as you go, using two dicts is unnecessary if you just want to count how many times each side is rolled:
from collections import defaultdict
from random import randint
z = int(raw_input("How many sides should the dice(s) have?\n> "))
x = int(raw_input("How many dices do you want?\n> "))
counts = defaultdict(int) # store dices sides as keys, counts as values
# loop in range of how many dice
for _ in xrange(x):
counts[randint(1,z)] += 1
for side,count in counts.iteritems():
print("{} was rolled {} time(s)".format(side,count))
Output:
How many sides should the dice(s) have?
> 6
How many dices do you want?
> 10
1 was rolled 2 time(s)
2 was rolled 3 time(s)
3 was rolled 1 time(s)
4 was rolled 1 time(s)
5 was rolled 1 time(s)
6 was rolled 2 time(s)
If you want to include all dice sides in the output you can create the counts dict using xrange:
counts = {k:0 for k in xrange(1, z+1)}
So the output will then be:
How many sides should the dice(s) have?
> 6
How many dices do you want?
> 10
1 was rolled 0 time(s)
2 was rolled 2 time(s)
3 was rolled 0 time(s)
4 was rolled 0 time(s)
5 was rolled 5 time(s)
6 was rolled 3 time(s)

Trouble correctly adding numbers in a python program

I am trying to simulate dice being rolled. Die_1 + Die_2 five times. The program runs, but the math is wrong. I have tried this multiple ways, but cannot get the math correct. The die are only being rolled one at a time, so a 1 and a six are possibilities. It must be an overly tired oversight. Any ideas would be fantastic. Code and output below. Thank you to anyone who can help.
# This program will simulate dice rolls 5 different
# times and add the total of each roll.
import random
import math
MIN = 1
MAX = 6
ROLLS = 5
def main():
for count in range(ROLLS):
die_1 = (random.randint(MIN, MAX))
die_2 = (random.randint(MIN, MAX))
combined_roll = point(die_1, die_2)
print('Here are the combined rolls for the dice!')
print(random.randint(MIN, MAX))
print(random.randint(MIN, MAX))
print('The combined roll is:', combined_roll)
def point(die_1, die_2):
roll_1 = die_1 + die_2
combined_roll = roll_1
return combined_roll
main()
Here are the combined rolls for the dice!
4
3
The combined roll is: 4
Here are the combined rolls for the dice!
2
2
The combined roll is: 7
Here are the combined rolls for the dice!
5
4
The combined roll is: 5
Here are the combined rolls for the dice!
3
5
The combined roll is: 9
Here are the combined rolls for the dice!
3
1
The combined roll is: 11
The math and everything is correct. It is indeed a symptom of being tired.
You're printing out entirely new numbers in these 2 lines:
print(random.randint(MIN, MAX))
print(random.randint(MIN, MAX))
Compared to what your die rolls actually were, earlier in time.
die_1 = (random.randint(MIN, MAX))
die_2 = (random.randint(MIN, MAX))
Time has passed so your random number generation is going to be in a different state.
So change the prints to:
print(die_1)
print(die_2)
This is best achieved with a simple function and random.randint:
>>> from random import randint
>>> def roll_dice(n=1):
... return [randint(1, 6) for _ in range(n)]
...
1-die roll:
>>> roll_dice()
[2]
>>> roll_dice()
[2]
>>> roll_dice()
[5]
2-die roll:
>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[5, 5]
>>>
You can easily sum a 2-die roll by:
>>> sum(roll_dice(2))
6
>>> sum(roll_dice(2))
7
>>> sum(roll_dice(2))
8
The second set if print statements mean to print die_1 and die_2, nit calls to random again. If you call random again, you get new random numbers.

Categories