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.
They take turn 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 scores, wins the game.
When I run this code, I get the same randomly generated number's over and over. I am not sure how to get different number's on each roll. I also don't understand how to keep up with each player's score at the end of their turn's.
Any help at all would be greatly appreciated.
import random
def main():
print("Welcome to the Two Dice Pig Game. You are Player 1!")
Player1 = 0
Player2 = 0
while(Player1<100 or 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"):
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.")
elif(choose1=="y"):
print("It's player 2's turn.")
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.")
main()
Try changing the line
Player1 = p1dice+p1dice2
to
Player1 += p1dice+p1dice2
The old version replaces the value of Player1 each time. The new version adds to it.
By the way, the += is a shorthand for
Player1 = Player1+p1dice+p1dice2
Many of Python's other operators have a similar "augmented assignment" notation.
So your problem is that the random numbers don't work like you want rather than something about "starting your loop"?
I really only see this happening because your system clock is messed up(random uses the current time as seed for random).
Have you tried instantiating random.Random() and calling from that?
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 have to make a card game in which the starting player changes after each round or mini round (up to me to decide) but I have no clue how to alternate between the 2 players. After reading online, I tried using the cycle function from itertools but that creates further problems...
The problem is that I do not know how to alternate between the 2 players without messing up the rest of the program (displaying the player's hand and the scoring system)
To clarify in advance, the code snippets I am about to provide work perfectly as long as I do not alternate between the starting players.
Code:
print("Player 1, your cards are: ", hands[0])
print("Player 2, your cards are: ", hands[1])
In this case I want the hands index to change accordingly to the Player if i use the cycle function.
if cards.bigger_card(hands[0][play_1 - 1], hands[1][play_2 - 1], trump[0][1]) == 0:
print("Congrats Player 2! You won this mini round.")
score["score_2"] += 1
else:
print("Congrats Player 1! You won this mini round.")
score["score_1"] += 1
Here the score should update according to the Player that won the round.
I'm not sure if I've understood your question well enough. But I'll try.
To simply alternate between two index i.e. 0, 1, you can add a variable to store current turn and alternating it like this:
currentTurn = 0
def switchTurn():
return (currentTurn + 1) % 2
Usage:
print(currentTurn)
# output: 0
switchTurn()
print(currentTurn)
# output: 1
print(hands[currentTurn])
# output player 2nd's hands (or cards)
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.
I'm writing a 2 player dice game where two 6-sided dice are randomly rolled. If the sum of the dice are even, + 10 to the total of the two dice thrown. If the sum of the dice are odd, -5 from the total of the dice thrown. If the user rolls doubles, they roll another die and their score is the sum of all 3 die.
There are 5 rounds and the code shown is Player 1's 1st round.
1) Why is there suddenly an "invalid syntax" (2nd last line, highlighted in code)?
2) Why is only the if statement read? (the other two elif statements are ignored)
even if doubles are rolled or an even number, the game still subtracts 5 from the sum of the two dice, regardless of the outcome.
Thanks in advance.
Here is my code below:
import time
import random
print("Rolling dice for Player 1...")
time.sleep(1)
P1_dice1A = (random.randint(1, 6)) #1st die
print("Dice 1 =",str(P1_dice1A)) #prints 1st die
time.sleep(1)
P1_dice1B = (random.randint(1, 6)) #2nd die
print("Dice 2 =",str(P1_dice1B)) #prints 2nd die
P1_dicetotal1 = P1_dice1A + P1_dice1B #adds both die
print("You rolled",str(P1_dicetotal1)) #prints result of line above
P1_score = 0 #total score for all 5 rounds, starts at 0
if P1_dicetotal1 == 1 or 3 or 5 or 7 or 9 or 11:
print("Oh no! You rolled an odd number, so -5 points from your score :(.")
P1_score_r1 = P1_dicetotal1 - 5 #subtracts 5 from total score and score this round
print("Player 1's score this round =",str(P1_score_r1)) #prints score this round
P1_score == P1_score_r1 #total score is same as score this round because this is round 1 out of 5 for player 1
print(P1_score) #prints total score
if P1_score_r1 < 0:
print("Unlucky. Your score reached below 0. Game Over.")
print("Thank you for playing and I hope you enjoyed playing.")
import sys
sys.exit()
elif P1_dice1A == P1_dice1B: #if dice are the same
print("You rolled a double, so you get to roll another dice...")
time.sleep(1)
P1_dice1C = (random.randint(1, 6)) #3rd die is rolled
P1_score_r1 = P1_dicetotal1 + P1_dice1C #adds die 1, 2 and 3 to toal for this round and whole game
print("Player 1's score this round =",str(P1_score_r1))
P1_score == P1_score_r1
print(P1_score)
elif P1_dicetotal1 == 2 or 4 or 6 or 8 or 10 or 12:
print("Your total was an even number, so +10 points to your total.")
P1_score_r1 = P1_dicetotal1 + 10 #adds 10 to total score and score this round
print("Player 1' score this round =",str(P1_score_r1)
P1_score == P1_score_r1 #ERROR LINE - "P1_score" is highlighted red
print(P1_score) #prints total score after every round
You need to close the print statement in the 3rd last line:
print("Player 1' score this round =",str(P1_score_r1)
should be:
print("Player 1' score this round =",str(P1_score_r1))
Also your ifs statements are wrong, you need to use P1_dicetotal1 == 1 with all the other values, that's why it's always true.
I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.
Here is my code:
import random
def main():
name = eval(input("Hello user, please enter your name: "))
print("Hello", name ,"This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N):")
if yn == Y:
elif yn == N:
print("Ok have a nice day!")
heads = 0
tails = 0
count = tails + heads
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
elif coin == 2:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
main()
Here is the sample output that I'm looking for:
Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!
I think you should say on line 6 if yn == 'Y' and not if yn == Y. You treat Y as a variable while it is actually a string from the input.
To run your coin toss simulation multiple times you can put it inside a while loop.
Your if yn == Y: test won't work because you haven't defined the variable Y, so when Python tries to execute that line you get a NameError. What you actually should be doing there is to test the value of yn against the string 'Y'.
I've made a couple of other minor adjustments to your code. I got rid of that potentially dangerous eval function call, you don't need it. I've also made a loop that asks for the desired flip count; we break out ofthe loop when count is a positive number.
import random
def main():
name = input("Hello user, please enter your name: ")
print("Hello", name , "This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
while True:
heads = tails = 0
while True:
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
else:
break
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
else:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
yn = input("Would you like to run another coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
main()
This code is for Python 3. On Python 2 you should use raw_input in place of input, and you should also put
from future import print_function
at the top of the script so you get the Python 3 print function instead of the old Python 2 print _statement.
There are several improvements that can be made to this code. In particular, it should handle a non-integer being supplied for the count. This version will just crash if it gets bad input. To learn how to fix that, please see Asking the user for input until they give a valid response.