Card trick program - python

I've been trying to create a program that deals 21 cards into 3 piles. The user is then asked to think of a card and tell the program in which pile is their card. this step is repeated 4 more times until the card is found exactly in the middle of the 21 cards. The program the is supposed to go to the end() function where it prints the users card, the problem is, everything works fine but it prints the statement in the end() function 5 times. I know it is probably something really stupid but I can't think of a solution. Thanks in advance.
import random
cards = []
count = 0
def end():
print("Your card is: ", cards[10])
def split():
def choice():
global count
while True:
if count >=0 and count <= 3:
global cards
user = input("Think of a card. Now to which pile does your card belong to?: ")
count = count + 1
if user == "1":
del cards[:]
cards = (pile_2 + pile_1 + pile_3)
print(cards)
split()
elif user == "2":
del cards[:]
cards = (pile_1 + pile_2 + pile_3)
print(cards)
split()
elif user == "3":
del cards[:]
cards = (pile_1 + pile_3 + pile_2)
print(cards)
split()
else:
print("Invalid input")
main()
elif count == 4:
end()
break
pile_1 = []
pile_2 = []
pile_3 = []
counter = 0
sub_counter = 0
while True:
if sub_counter >= 0 and sub_counter <= 20:
for item in cards:
if counter == 0:
pile_1.append(item)
counter = counter + 1
elif counter == 1:
pile_2.append(item)
counter = counter + 1
elif counter == 2:
pile_3.append(item)
counter = 0
sub_counter = sub_counter + 1
elif sub_counter == 21:
False
break
print()
print("first pile: ", pile_1)
print("second pile: ", pile_2)
print("third pile: ", pile_3)
choice()
def main():
file = open('cards.txt.', 'r')
for line in file:
cards.append(line)
file.close
random.shuffle(cards)
print(cards)
split()
main()

You've got recursive calls. split() calls choice() which then calls split() again, which can calls main() which again calls split().

By the time you get to the elif count == 4 line, count will always be 4. That's why. I got a hunch it could work if you changed the order:
...
if count == 4:
end()
break
elif count >= 0 and count <=3:
...
However, it would be even nicer if you could write it without global variables. Instead of global variables you have local ones that are passed over to the next function as arguments. Like this:
import random
def end(cards):
print("Your card is: ", cards[10])
def choice(count,pile_1,pile_2,pile_3):
while True:
user = input("Think of a card. Now to which pile does your card belong to?: ")
if user == "1":
cards = (pile_2 + pile_1 + pile_3)
print(cards)
split(count+1, cards)
break
elif user == "2":
cards = (pile_1 + pile_2 + pile_3)
print(cards)
split(count+1, cards)
break
elif user == "3":
cards = (pile_1 + pile_3 + pile_2)
print(cards)
split(count+1, cards)
break
else:
print("Invalid input")
def split(count,cards):
if count == 4:
end(cards)
return
pile_1 = []
pile_2 = []
pile_3 = []
for i in range(0,21,3):
pile_1.append(cards[i])
pile_2.append(cards[i+1])
pile_3.append(cards[i+2])
print()
print("first pile: ", pile_1)
print("second pile: ", pile_2)
print("third pile: ", pile_3)
choice(count,pile_1,pile_2,pile_3)
def main():
cards = []
file = open('cards.txt.', 'r')
for line in file:
cards.append(line.strip())
file.close
random.shuffle(cards)
print(cards)
split(0, cards)
main()

I have found a solution:
It was just a matter of an ident,
instead of:
elif count == 4:
end()
break
I put the break statement on the same line as elif:
elif count == 4:
end()
break
which seems to solve it

Related

How to make a function to score a Rock, Paper and Scissor game in Python?

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 dont know how to go about looping a specific part of my code

I'm writing a casino-based game and I'm having some trouble with coding blackjack, I run into a problem where you only have the option to "hit" once, and I'm not sure how to make it loop. Once you've "hit" it just settles with your score as if it was final even tho you might still be far under 21. Every time I try to fix it some other part of the code just breaks.
(keep in mind this is not the full code but just the blackjack part)
import os
import random
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4
bal = 100
balstr = str(bal) + "$"
def clear():
os.system('cls')
def deal(deck):
hand = []
for i in range(2):
random.shuffle(deck)
card = deck.pop()
if card == 11:card = "J"
if card == 12:card = "Q"
if card == 13:card = "K"
if card == 14:card = "A"
hand.append(card)
return hand
def newRound():
again = input("Do you want to play again? (Y/N): ").lower()
if again == "y":
blackjack()
else:
#takes you back to main menu in the full code, just ignore this
position()
def total(hand):
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total+= 10
elif card == "A":
if total >= 11:
total+= 1
else: total+= 11
else:
total += card
return total
def hit(hand):
card = deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def currentHands(dealerHand, playerHand):
clear()
print(("The dealer has a ") + str(dealerHand) + " for a total of " + str(total(dealerHand)))
print(("You have a ") + str(playerHand) + " for a total of " + str(total(playerHand)))
def score(dealerHand, playerHand, usrbetint):
global bal
if total(playerHand) == 21 or total(dealerHand) > 21 or total(playerHand) > total(dealerHand) and total(playerHand) < 21:
currentHands(dealerHand, playerHand)
bal += usrbetint
print("Congratulations, you win!\n \nYour new balance is {}$".format(bal))
else :
currentHands(dealerHand, playerHand)
bal -= usrbetint
print("Sorry, you lose.\n \nYour new balance is {}$".format(bal))
def blackjack():
choice = 0
clear()
print("Let's play blackjack!\n")
userbet = input("(for help type help) How much money do you want to use: ").upper()
if userbet == "HELP" :
if userbet == "HELP" :
print("Instructions")
else :
print("Something went wrong")
pass
else :
usrbetint = int(userbet)
dealerHand = deal(deck)
dealerHandShow = [dealerHand[0]]
dealerHandShow = total(dealerHandShow)
playerHand = deal(deck)
print(("The dealer is showing a ") + str(dealerHand[0]) + " for a total of " + str(dealerHandShow))
print(("You have a ") + str(playerHand) + " for a total of " + str(total(playerHand)))
choice = input("Do you want to [H]it or [S]tand?: ").lower()
clear()
if choice == "h":
hit(playerHand)
while total(dealerHand) < 17:
hit(dealerHand)
score(dealerHand, playerHand, usrbetint)
newRound()
elif choice == "s":
while total(dealerHand) < 17:
hit(dealerHand)
score(dealerHand, playerHand, usrbetint)
newRound()
blackjack()
i assume the fix would be somewhere around the last 20 lines of the "blackjack" function but didnt know how to explain everything without sending the clump of code.
If someone please could give me tips on where to change stuff i'd really appreciate that and ignore the "global bal" part, it was the only way i knew to add a truly global variable.
Since you don't know how many times you'll be looping (it is based on user input), you probably want a while loop. Your current code mixes the dealer behavior into the player handling, you you'll need to separate that out, since we don't want to loop it.
print("You have a " + str(playerHand) + " for a total of " + str(total(playerHand)))
choice = input("Do you want to [H]it or [S]tand?: ").lower()
while choice == "h":
clear()
hit(playerHand)
print("You have a " + str(playerHand) + " for a total of " + str(total(playerHand)))
choice = input("Do you want to [H]it or [S]tand?: ").lower()
while total(dealerHand) < 17:
hit(dealerHand)
score(dealerHand, playerHand, usrbetint)
You might want to add an additional condition to stop asking the player if they want to hit when they've already busted.

Making Mastermind in Python

I am simply wondering how I can make my game of Mastermind work, more specifically how I would go about making "finish" global, how I would call these functions so that the program works correctly, and overall tips that would help enhance my code. I would also like to know how to make it so the program doesn't 'reroll' the computer-generated number every single loop. This was just a difficult problem for me and I can't seem to understand how to close it out with the correct function calls and niche aspects such as that. Thank you.
run = True
def get_guess():
while run:
guess = input("Provide four unique numbers: ")
count = 0
if len(guess) == 4:
guessdupe = guess[0] == guess[1] or guess[0] == guess[2] or guess[0] == guess[3] or guess[1] == guess[2] or guess[1] == guess[3] or guess[2] == guess[3]
else:
guessdupe = False
try:
try:
for i in range(4):
if int(guess[i]) <= 7 and int(guess[i]) >= 1 and len(guess) == 4:
count += 1
if len(guess) != 4:
print "Your guess must consist of 4 numbers!"
if guessdupe:
count -= 1
print "You can only use each number once!"
except ValueError:
print "You can only use numbers 1-7 as guesses"
except IndexError:
print "You can only use numbers 1-7 as guesses"
if count == 4:
break
return guess
def check_values(computer_list, user_list):
final_list = [''] * 4
for i in range(4):
if user_list[i] in computer_list:
if user_list[i] == computer_list[i]:
final_list[i] = "RED"
else:
final_list[i] = "WHITE"
else:
final_list[i] = "BLACK"
random.shuffle(final_list)
print final_list
return final_list
def check_win(response_list):
if response_list[0] == "RED" and response_list[1] == "RED" and response_list[2] == "RED" and response_list[3] == "RED":
print "Congratulations! You've won the game!"
global finish
finish = True
def create_comp_list():
while run:
compList = [random.randint(1, 7), random.randint(1, 7), random.randint(1, 7), random.randint(1, 7)]
listBool = compList[0] == compList[1] or compList[0] == compList[2] or compList[0] == compList[3] or compList[1] == compList[2] or compList[1] == compList[3] or compList[2] == compList[3]
if listBool:
continue
else:
return compList
def play_game():
for i in range(5):
print create_comp_list()
print get_guess()
check_win(check_values(create_comp_list(), get_guess()))
if finish:
break
play_game()```

Avoid a recurring loop that repeats an instruction every time it reaches the end

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!

keeping final point

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()

Categories

Resources