I'm a beginner and I can't figure out why I can't get the output I
want. It's a craps game. It's suppose to go like:
How many games do you want to play > 6 You rolled 5 + 2 = 7 You
win
What I got is something like: You rolled 1 + 6 = 7 You rolled 1 + 6 =
7 You rolled 1 + 6 = 7 You lose
import random
def rollDice():
roll_1 = random.randint(1,7)
roll_2 = random.randint(1,7)
return roll_1, roll_2
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == '2' or '3' or '12':
return 0
elif sum == '7' or '11':
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == '7':
return 0
print("You rolled", x, "+", y, "=", sum )
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
determine_win_or_lose(x, y)
if determine_win_or_lose(x, y) == 1:
print("You win")
win = win + 1
elif determine_win_or_lose(x, y) == 0:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Your issue come from the main, because you call the determine_win_or_lose function 3 times, the first one before the if (and i'm not sure why since you do nothing with it), a second time to check the condition of the if and a third time to check the condition of the elif.
Since it's this function that print the message, and you call the function 33 times each iteration of the for loop, it's normal to get the message printed 3 times.
(
Also since the determine_win_or_lose will always return 0 or 1 you don't really need an elif you can just do an if/else to achieve the same thing and simplify your code a bit.
)
So i'd suggest the following :
#==== MAIN =====
win = 0
lose = 0
game = int(input("How many games do you want to play > "))
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
else:
print("You lose")
lose = lose + 1
print("Game results: ", win, "wins and", lose, "losses")
Obvious issues:
You call determine_win_or_lose too many times in your for loop. Change it to:
for i in range(game):
x, y = rollDice()
result = determine_win_or_lose(x, y)
if result == 1:
print("You win")
win = win + 1
elif result == 0:
print("You lose")
lose = lose + 1
Your check in determine_win_or_lose is incorrect. It should be something like:
def determine_win_or_lose(dice1,dice2):
sum = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", sum )
if sum == 2 or sum == 3 or sum == 12:
return 0
elif sum == 7 or sum == 11:
return 1
else:
print("Point is", sum)
determinePointValueResult(sum)
if determinePointValueResult(sum) == 1:
return 1
elif determinePointValueResult(sum) == 0:
return 0
In determinePointValueResult you shouldn't compare sum to a string, but an integer:
def determinePointValueResult(sum):
point = sum
while sum != 7 and sum != point:
x, y = rollDice()
sum = x + y
if sum == point:
return 1
elif sum == 7:
return 0
print("You rolled", x, "+", y, "=", sum )
It's possible that determine_win_or_lose and determinePointValueResult are returning None. You may need to change your elifs to elses or create a new else case.
Related
I wrote a Rock, Paper and Scissor game in Python. And I want to have a function that scores the game. The only way I managed to do that was by using global variables inside the function. I know that's not a good practice and I'd like to know how can I make this function without the need for global variables.
import random
def validate_user_input(input):
"""Verify if user input is a valid."""
try:
usr_input = int(input)
except:
return 0
else:
if (usr_input >= 1) and (usr_input <= 3):
return usr_input
else:
return 0
def compare_results(player_choice):
"""Get computer choice and compare it with user choice"""
computer_option = random.randint(1,3)
result_to_word = {0:'- Draw', 1:'- You loose.', 2:'- You Win'}
if player_choice == computer_option:
result = 0
if (player_choice == 1 and computer_option == 2):
result = 1
if (player_choice == 1 and computer_option == 3):
result = 2
if (player_choice == 2 and computer_option == 1):
result = 2
if (player_choice == 2 and computer_option == 3):
result = 1
if (player_choice == 3 and computer_option == 1):
result = 1
if (player_choice == 3 and computer_option == 2):
result = 2
return (result, result_to_word[result], computer_option)
def codify_result(input):
"Transform number of choice into word"
num_to_word = {1: "Rock", 2: "Paper", 3:"Scissor"}
return num_to_word[input]
def make_score(result):
global computer_score
global player_score
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
player_score = 0
computer_score = 0
intro = "\nHello!\nLet's play 'Rock, Paper and Scissors'.\nChoose an option and wait to see the result (Press 'q' at any time to exit)"
print(intro)
while True:
user_input = input("\n1) Rock, 2) Paper os 3) Scissors?: ")
if (user_input == 'q'):
break
else:
user_choice = validate_user_input(user_input)
if user_choice == 0:
print("You have to choose a number between 1 and 3.")
else:
result = compare_results(user_choice)
print("You chose: " + codify_result(user_choice) + ".")
print("The computer chose: " + codify_result(result[2]) + '.')
print(result[1])
make_score(result[0])
print("You: " + str(player_score) + "\nComputer: " + str(computer_score))
So how could I implement this function in a better way?
A "pure functional" approach could be to change your make_score function to take the old scores as arguments, and then return the updated scores:
def make_score(result, computer_score, player_score):
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
return computer_score, player_score
When you call make_score you pass the old scores and assign the new scores:
computer_score, player_score = make_score(result[0], computer_score, player_score)
Taking a step back, though, I might suggest taking an approach that doesn't require you to have a function that translates an opaque result int value into a modification to one or another variable. Maybe put the scores in a dict:
scores = {
"computer": 0,
"player": 0,
}
and then instead of a magic result int, assign a winner that matches one of the dict keys:
if (player_choice == 1 and computer_option == 2):
winner = "computer"
and then you can get rid of the make_score function completely and just do:
scores[winner] += 1
I would recommend making a dictionary which you can then pass into make_score
score_dict = {'computer_score': 0, 'player_score': 0}
make_score(score_dict, result):
if result == 1:
score_dict['computer_score'] += 1
...
I am trying to write a program to play 100 games of Craps and print out the overall results. I have an infinite loop at the end of my code.
Does anyone see the problem?
I assume my 2nd function could be calling diceRoll again for secondRoll. Trying that now...
Specs:
The player must roll two six-side dice and add the total of both
dice.
The player will win on the first roll if they get a total of 7 or 11
The player will lose on the first roll if they get a total of 2, 3,
or 12
If they get any other result (4, 5, 6, 8, 9, 10), they must roll
again until they either match their first roll (a win) or get a
result of 7 (a loss)
Use at least two functions in your program
from random import randrange as rd
winTuple = 7, 11
lossTuple = 2, 3, 12
wins = 0
losses = 0
x = 1
def diceRoll (number, type = 6):
result = 0
for i in range(number):
result += rd(1, type +1)
return result
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
while secondRoll != 7 or secondRoll != firstRoll:
if secondRoll == 7:
wins += 1
elif secondRoll == firstRoll:
wins += 1
else:
secondRoll = diceRoll(2)
x += 1
print("wins: ", wins)
print("losses: ", losses)
Looks like you need to eliminate your inner loop. First, the loop conditions are in direct conflict with your conditional statements, so the loop never exits. Second, why would you want a loop here? Even if you fixed it, all it would do is keep rolling the second dice until a win is scored.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
secondRoll = diceRoll(2)
if secondRoll == 7 or secondRoll == firstRoll:
wins += 1
x += 1
In response to your comment, this is how you create your second loop. You make an infinite loop with while True and break out of it when the conditions are met.
while x < 101:
firstRoll = diceRoll(2)
if firstRoll in winTuple:
wins += 1
elif firstRoll in lossTuple:
losses += 1
else:
while True:
secondRoll = diceRoll(2)
if secondRoll == 7:
losses += 1
break
elif secondRoll == firstRoll:
wins += 1
break
x += 1
If your firstRoll != 7 (let's say firstRoll = 8) then your script cannot exit the second nested loop because either secondRoll != 7 or secondRoll = 7 and therefore firstRoll != secondRoll (7 != 8)
I am not sure how your program goes through 100 games of craps, here is an example of a program I wrote quick that goes through 100 games. Games being times you either hit or don't hit the point.
Clearly you need to understand how craps works to make something like this, so I am assuming you do. The program you were trying to write, even though you were stuck in the loop, was not actually playing a full game of craps.
You can choose the amount of games you want and the only thing it stores is if you won or lost.
You can add other statistics if you would like, for example points hit and which points they were etc.,
I added text to, also, make it user friendly if this is for a school project.
There are many different ways to do this, I used a main while loop and created two functions for whether the button is on or off.
You could obviously condense this, or write a class instead but I simply put this together quick to give you an idea and see how it goes through every loop and statement.
I am still a novice, so I apologize to anyone else reading, I know the below is not the most efficient/does not perfectly follow PEP8 especially the long if statement in the main loop.
This does perform what you wanted and feel free to change the number of games. Enjoy!
import random
wins = 0
losses = 0
gamenum = 0
#Used a list to pull the dice numbers from but not mandatory
dicenum = [2,3,4,5,6,7,8,9,10,11,12]
#Function when point is off
def roll_off():
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("Point is 4")
return(4)
elif roll == 5:
print("Point is 5")
return(5)
elif roll == 6:
print("Point is 6")
return(6)
elif roll == 7:
print("Winner 7")
elif roll == 8:
print("Point is 8")
return(8)
elif roll == 9:
print("Point is 9")
return(9)
elif roll == 10:
print("Point is 10")
return(10)
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Function when point is on
def roll_on(x):
#Random roll from list
roll = random.choice(dicenum)
if roll == 2:
print("2 craps")
elif roll == 3:
print("3 craps")
elif roll == 4:
print("You rolled a 4")
elif roll == 5:
print("You rolled a 5")
elif roll == 6:
print("You rolled a 6")
elif roll == 7:
print("7 out")
elif roll == 8:
print("You rolled a 8")
elif roll == 9:
print("You rolled a 9")
elif roll == 10:
print("You rolled a 10")
elif roll == 11:
print("Yo 11")
elif roll == 12:
print("12 craps")
#Check if you hit the point
if x == 4 and roll == 4:
print("You win!")
return (True)
elif x == 5 and roll == 5:
print("You win!")
return (True)
elif x == 6 and roll == 6:
print("You win!")
return (True)
elif x == 7 and roll == 7:
print("You win!")
return (True)
elif x == 8 and roll == 8:
print("You win!")
return (True)
elif x == 9 and roll == 9:
print("You win!")
return (True)
elif x == 10 and roll == 10:
print("You win!")
return (True)
#Check if you 7'ed out
if roll == 7:
print("You lose!")
return (False)
#Main game, change the amount of games you want to play
while gamenum < 100:
diceresult = roll_off()
#If statement to check the point
if diceresult == 4 or diceresult == 5 or diceresult == 6 or diceresult == 8 or diceresult == 9 or diceresult == 10:
active = True
print("The point is on!")
while active == True:
curentstate = roll_on(diceresult)
if curentstate == False:
gamenum += 1
losses += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
elif curentstate == True:
gamenum += 1
wins += 1
print("------------")
print("Games:", gamenum)
print("Losses:", losses)
print("Wins:", wins)
print("------------")
break
I'm new to programming and I have a task that I can't figure out on my own.
The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.
here is my code:
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
while True:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
while True:
if reset==True:
break
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(1, 6)
print(dicesArray[i])
total += dicesArray[i]
if dicesArray[i] == 1:
print("You rolled a one, the total is: ",str(total))
elif dicesArray[i] == 2:
print("You rolled a two, the total is: ",str(total))
elif dicesArray[i] == 3:
print("You rolled a three, the total is: ",str(total))
elif dicesArray[i] == 4:
print("You rolled a four, the total is: ",str(total))
elif dicesArray[i] == 5:
print("You rolled a five, the total is: ",str(total))
elif dicesArray[i] == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
reset=True
print("The total sum is",str(total),"with",numDices,"number of rolls.")
print()
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit=True
break
else:
print()
break
if exit==True:
break
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
total = 0
dices_counter = 0
while numDices > 0 :
eyes = random.randint(1, 6)
dices_counter+=1
total += eyes
if eyes == 1:
print("You rolled a one, the total is: ",str(total))
numDices-=1
elif eyes == 2:
print("You rolled a two, the total is: ",str(total))
numDices-=1
elif eyes == 3:
print("You rolled a three, the total is: ",str(total))
numDices-=1
elif eyes == 4:
print("You rolled a four, the total is: ",str(total))
numDices-=1
elif eyes == 5:
print("You rolled a five, the total is: ",str(total))
numDices-=1
elif eyes == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
print()
start=(input("Do you want to restart press Enter, to quit press 9. "))
if start=="9":
break
else:
print()
start = True
To solve your problem I would replace your current for loop with a while loop
Moreover, I see a lot of unacessary things in your code, I will try to list them :
Why do you use so many "while True"?
Why don't you just use exit() function to exit instead of using a
variable?
Is all the if part really necessary, can't you just print the
number?
Here's my proposal:
import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
while True:
remaining_dices=int(input("How many dices to throw? (1-5) "))
if remaining_dices<1 or remaining_dices>5:
print("Wrong input, try again")
break
dicesArray = list()
while remaining_dices>0:
dice_value = random.randint(1, 6)
dicesArray.append(dice_value)
print(dice_value)
total += dice_value
remaining_dices -= 1
if(dice_value == 6):
total-=6
remaining_dices +=2
print("You rolled a 6, rolling two new dices")
else:
print("You rolled a " + str(dice_value) + ", the total is : " +str(total))
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit()
else:
print()
for i in range(numDices):
Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed. When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.
If you want to be able to change the number of iterations, use another while loop and use i as a counter. Something like.
i = 0
while i <= numDices:
...
...
if ...:
...
elif ...:
...
i += 1
Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.
I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.
dicesArray = list(range(numDices))`
...
dicesArray[i]
...
If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError. You should probably start with an empty list and append to it. To get the most recent dice roll use dicesArray[-1] instead of dicesArray[i].
...
dicesArray = []
i = 0
while i <= numDices:
dicesArray.append(random.randint(1, 6))
total += dicesArray[-1]
if dicesArray[-1] == 1:
...
...
6.3.2. Subscriptions
Using a recursive function
import random
total = 0
diceRollList = []
# Define dice rolling function
def rollDice():
rollResult = random.randint(1, 6)
if rollResult == 6:
# If 6 Rolled run two more rolls and sum the results
print("Rolled a 6 Rolling 2 more")
return sum([rollDice() for _ in range(2)])
# If 6 not rolled return the result
print(f"Rolled a {rollResult}")
return rollResult
while True:
numberOfDice = int(input("How many Die to throw: "))
if numberOfDice not in range(1, 6):
print("Number of dice should be between 1 and 5")
break
for dice in range(numberOfDice):
print(f"Rolling Dice {dice}")
# Add result to the total
total += rollDice()
print(f"Running Total: {total}")
This one tracks how many it has rolled:
import random
a = int(0)
b = int(0)
c = int(0)
d = int(0)
e = int(0)
f = int(0)
limit = 101
count = 0
while True:
g = (random.randint(1, 6))
print(g)
count += 1
if g == 1:
a += 1
elif g == 2:
b += 1
elif g == 3:
c += 1
elif g == 4:
d += 1
elif g == 5:
e += 1
elif g == 6:
f += 1
if count > limit:
break
print(f"There are {a} 1's")
print(f"There are {b} 2's")
print(f"There are {c} 3's")
print(f"There are {d} 4's")
print(f"There are {e} 5's")
print(f"There are {f} 6's")
My problem is, my rock, paper, scissors program seems trapped in a loop somewhere. I suspect it's either the inner loop that asks the user for the number of rounds, or the outer loop that asks the user how many players should play; both might even have indentation problems but I am not sure.
import random
from os import system, name
from time import sleep
#variable declarations and initializations
computer,players, rounds, wins, loses, draws, yourPlay, count, rec, playerRange = 0, 0, 0, 0, 0, 0, 0, 0, 0, 3
#function definitions
def RoundsWonResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[yourPlay] + " beats " + playerMoves[computer] +"!")
print ("You win!")
return
def RoundsLostResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[computer] + " beats " + playerMoves[yourPlay] +"!")
print ("You lose!")
return
def DrawMatch():
global draws
while (yourPlay == computer):
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print ("It's a draw!")
draws+=1
return
def WinsMatch():
global wins
while (yourPlay != computer):
if (yourPlay == 0 and computer != 1):
if (computer == 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 1 and computer == 0):
if (computer != 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 2 and computer != 0):
if (computer == 1):
RoundsWonResult()
wins+=1
return
def LosesMatch():
global loses
while (yourPlay != computer):
if (yourPlay == 0 and computer == 1):
if (computer != 2):
RoundsLostResult()
loses+=1
elif (yourPlay == 1 and computer == 2):
if (computer != 0):
RoundsLostResult()
loses+=1
elif (yourPlay == 2 and computer == 0):
if (computer != 1):
RoundsLostResult()
loses+=1
return
try:
players = int(input("Enter number of players[1-3]:"))
while (players < 1 or players > playerRange):
print ("Invalid range selected!")
players = int(input("Enter number of players[1-3]:"))
except ValueError:
print ("Only numeric values are allowed!")
players = int(input("Enter number of players[1-3]:"))
if (players > 0 and players <= 3):
print ("Good luck to all " + str(players) + " of you. May the better player win!")
while (rec < players):
try:
rounds = int (input("Enter number of rounds to play:"))
while (rounds <= 0):
print ("Value must be greater than zero!")
rounds = int (input("Enter number of rounds to play:"))
print(rec)
print(rounds)
except ValueError:
print ("Only numeric values are allowed!")
rounds = int (input("Enter number of rounds to play:"))
if (rounds != "" and rounds > 0):
print ("Let the games begin!")
else:
print ("Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. Good Luck!")
print("You entered " + str(rounds) + " round(s)!")
playerMoves = ["Rock","Paper","Scissors"]
while (count < rounds):
try:
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
while (yourPlay < 0 or yourPlay > 2):
print ("Invalid selection!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
except ValueError:
print ("Only numeric values are allowed!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
else:
computer = random.randint(0,2) #randomizes the numbers 0 - 2
if (yourPlay == computer):
DrawMatch()
elif (yourPlay != computer):
WinsMatch()
LosesMatch()
count+=1
print ("End of Round ", count)
if (count == rounds):
print ("Wins:",wins)
print ("Loses:",loses)
print ("Draws:",draws)
#resultLog = {"Wins":wins,"Loses":loses,"Draws":draws}
fileName = input("Enter Your name: ")
#print (resultLog)
with open (fileName,"w") as plyrRec:
print ("Your file has been created!")
plyrRec.close()
with open (fileName, "a") as plyrRec:
plyrRec.write ("{}{}\n{}{}\n{}{}\n".format("Wins:",wins,"Loses:",loses,"Draws:",draws))
plyrRec.close()
rec+=1
print ("End of Record ", rec)
So the code works fairly well except that at the end of the first round it repeatedly asks the user to enter number of rounds to play. I hope someone can advise me please.
#Date first created: September 6, 2018 v.0
#Version: v.1, modified 2021/08/31
#This is a Rock, Paper, Scissors game.
#Rock beats scissors, scissors beats paper, and paper beats rock.
import random
#variable declaration and initialization
game_moves = ["Rock","Paper","Scissors"]
def is_input_numeric(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY numeric values greater than zero
>>> is_input_numeric('4')
True
>>> is_input_numeric("like 7")
False
'''
return str_val.isnumeric() and int(str_val) > 0 and int(str_val) <= 20
def is_input_numeric_range(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY a numeric value greater than zero but less than
or equal to two
>>> is_input_numeric_range('y')
False
>>> is_input_numeric_range('3')
False
>>> is_input_numeric_range('2')
True
'''
return str_val.isnumeric() and int(str_val) >= 0 and int(str_val) <= 2
def validate_rounds():
'''(string) -> string
checks str_val and passes control to is_input_numeric function, then returns a string value
>>> validate_rounds() -> is_input_numeric("time")
False
>>> validate_rounds() -> is_input_numeric('0')
False
>>> validate_rounds()-> is_input_numeric('10')
True
'''
valid_rounds = False
while not valid_rounds:
rounds = input("Enter number of rounds to play[min = 1, max = 20]: ")
valid_rounds = is_input_numeric(rounds)
return rounds
def validate_player_input():
'''(string) -> string
checks string and passes control to is_input_numeric_range function, then returns the string value
>>> validate_player_input() -> is_input_numeric_range('-1')
False
>>> validate_player_input() -> is_input_numeric_range('i')
False
>>> validate_player_input() -> is_input_numeric_range('3')
False
>>> validate_player_input() -> is_input_numeric_range('0')
True
'''
valid_player_control = False
while not valid_player_control:
player_move = input("ONLY (0)Rock,(1)Paper,(2)Scissors, allowed: ")
valid_player_control = is_input_numeric_range(player_move)
return player_move
def get_computer_play():
'''Returns a whole number in the range 0:2
'''
computer_move = random.randint(0,2)
return computer_move
def human_player_wins(plyr, comp):
wins = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 2:
rock_beats_scissors = True
elif human_hand == 1 and computer_hand == 0:
paper_beats_rock = True
elif human_hand == 2 and computer_hand == 1:
scissors_beats_paper = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[human_hand] + " beats " + game_moves[computer_hand] + "!")
print("You Win!")
wins += 1
return wins
def human_player_lose(plyr, comp):
lose = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 1:
paper_beats_rock = True
elif human_hand == 1 and computer_hand == 2:
scissors_beats_paper = True
elif human_hand == 2 and computer_hand == 0:
rock_beats_scissors = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[computer_hand] + " beats " + game_moves[human_hand] + "!")
print("You Lose!")
lose += 1
return lose
def players_draw():
draws = 0
print("It's a draw!")
draws += 1
return draws
def start_game():
rounds_played = 0
total_wins = 0
total_losses = 0
total_draws = 0
highest_score = 0
game_rounds = input("Enter number of rounds to play[Max = 20]: ")
rounds_valid = is_input_numeric(game_rounds)
if not rounds_valid:
game_rounds = validate_rounds()
while rounds_played < int(game_rounds):
player_hand = input("(0)Rock,(1)Paper,(2)Scissors: ")
valid_control = is_input_numeric_range(player_hand)
print('plyr:', player_hand)
if not valid_control:
player_hand = validate_player_input()
computer_hand = get_computer_play()
print('comp:', computer_hand)
if int(player_hand) == computer_hand:
total_draws += players_draw()
if int(player_hand) != computer_hand:
total_wins += human_player_wins(int(player_hand),computer_hand)
total_losses += human_player_lose(int(player_hand),computer_hand)
rounds_played += 1
if total_wins > highest_score:
highest_score = total_wins * 10
print('\n--------------------------GAME RESULTS--------------------------')
print('\nHigh Score = ', highest_score )
print('\nrounds played = ', rounds_played, '||','wins = ', total_wins,'||', 'losses = ', total_losses, '||','draws = ', total_draws )
print('\n--------------------------END OF RESULTS------------------------')
start_game()
Thanks to those who tried to helped me it was appreciated. This is the new version now after four years. Yikes!
I'm trying to write a program that allows the user to roll 2 dice and keep a running total of the points they have gained.
Update: Thank you so much, I figured it out :)
This solution worked:
import random
def roll_dice():
total = 0
while(True):
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = input()
if user_input == '1':
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print (d1, d2)
score = 0 # score this round
if d1 == d2:
score = 10
elif d1 == 6 or d2 == 6:
score = 4
elif d1 + d2 == 7:
score = 7
total += score # update total
print ("The score this round is ", score)
print ("The total number of points is", total)
elif user_input == '2':
print ("Thanks for playing!")
break
roll_dice()
Your line total = 0 resets total back to zero every time the two dice are rolled. Try putting total = 0 outside of your while loop.
subtotal = sum(both_dice) What is the purpose of this variable both_dice? Why is it a list? In your code, it can only contain one number or nothing at all.
This program should work. Please reason carefully line-by-line why this program works. Ask if anything is unclear.
import random
def roll_dice():
total = 0
while(True):
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = str(input()) # str() needed for Python 2
if user_input == '1':
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print (d1, d2)
score = 0 # score this round
if d1 == d2:
score = 10
elif d1 == 6 or d2 == 6:
score = 4
elif d1 + d2 == 7:
score = 7
total += score # update total
print ("The score this round is ", score)
print ("The total number of points is", total)
elif user_input == '2':
print ("Thanks for playing!")
break
roll_dice()
You can write the code in this manner.
import random
def roll_dice():
total = 0
while True:
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = input()
if user_input == 1:
# Get die_one and die_two entry
die_one, die_two = random.randint(1,6), random.randint(1,6)
print ("Got %d in die_one and %d in die_two" % (die_one, die_two))
score = 0
if die_one == die_two:
score = 10
elif die_one == 6 or die_two ==6:
score = 4
elif die_one + die_two == 7:
score = 7
print ("The current score is %d" % score)
total += score
print ("The total score is %d " % total)
elif user_input == 2:
print ("Thanks for playing!")
break
if __name__ == "__main__":
roll_dice()
Without break statement.
import random
def roll_dice():
total = 0
flag = True
while flag:
print ("Enter '1' to roll 2 dice, enter '2' to stop rolling")
user_input = input()
if user_input == 1:
# Get die_one and die_two entry
die_one, die_two = random.randint(1,6), random.randint(1,6)
print ("Got %d in die_one and %d in die_two" % (die_one, die_two))
score = 0
if die_one == die_two:
score = 10
elif die_one == 6 or die_two ==6:
score = 4
elif die_one + die_two == 7:
score = 7
print ("The current score is %d" % score)
total += score
print ("The total score is %d " % total)
elif user_input == 2:
print ("Thanks for playing!")
flag = False
if __name__ == "__main__":
roll_dice()
Refactored using itertools to create the die and hoisting the scoring logic.
import random
import itertools as it
import collections as ct
def roll(n=2):
"""Return a random result of two die."""
return random.choice(list(it.product(range(1,7), repeat=n)))
def score(die):
"""Return a score for a given rule."""
if len(set(die)) == 1:
return 10
elif 6 in die:
return 4
elif sum(die) == 7:
return 7
else:
return 0
def dice_game():
"""Run game."""
total = 0
while True:
user_input = input("Enter '1' to roll two die. Enter '2' to stop rolling. ")
if user_input == "1":
result = roll()
pts = score(result)
total += pts
print("Result:", result)
print ("The score this round is", pts)
print ("The total number of points is", total)
print()
elif user_input == "2":
print ("Thanks for playing!")
return
dice_game()