2

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()
qu2021
  • 31
  • 2

3 Answers3

1
  1. 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.

  2. 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()
kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
  • Okay, I tried putting the total=0 outside of the while loop (after the if statement) and my total still doesn't update. Any other suggestions? – qu2021 Oct 24 '17 at 03:15
  • @qu2021 Please see my update. I used the `+=` operator. See [What exactly does += do in python?](https://stackoverflow.com/questions/4841436/what-exactly-does-do-in-python) – kgf3JfUtW Oct 24 '17 at 03:24
  • Yes, this makes a lot of sense. Thank you so much! – qu2021 Oct 24 '17 at 03:25
  • @qu2021 If you replace the `break` with `return`, it will work the same. Also, if you are using Python 2, make sure to write `str(input())` to make sure you have a string `'1'` instead of an integer `1`. – kgf3JfUtW Oct 24 '17 at 04:33
0

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()
kvivek
  • 3,321
  • 1
  • 15
  • 17
  • add a variable like `flag = True` above while loop. Then in the while loop the condition should be `while flag:` . And instead of break statement use `flag=False`. – kvivek Oct 24 '17 at 04:25
  • @qu2021: You can accept and upvote the answer if that suits you. – kvivek Oct 24 '17 at 04:31
0

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()
pylang
  • 40,867
  • 14
  • 129
  • 121