Why is my code not printing an output of the dice diagram?

Question:

in my code I have already inserted the ASCII diagram of the dice. The first part of the function, I’ve created a function to generate random number from 1-6 to stimulate a rolling dice. On the second part of the code which is where I am stuck at, I am supposed to print out the diagram of the dice based on the rolls that I got and it must be printed horizontally instead of vertically. However, when I attempt to print the diagram using the for second for loop that I created, it’s not working and nothing get printed out.output that i received Below is the instruction that I’ve received.

import random


def roll_dice(num_of_dice=1):
    """
    Rolls dice based on num_of_dice passed as an argument.

    Arguments:
      - num_of_dice: Integer for amount of dice to roll

    Returns the following tuple: (rolls, display_string)
      - rolls: A list of each roll result as an int
      - display_string: A string combining the dice art for all rolls into one string
    """
    die_art = {
        1: ["┌─────────┐", "│         │", "│    ●    │", "│         │", "└─────────┘"],
        2: ["┌─────────┐", "│  ●      │", "│         │", "│      ●  │", "└─────────┘"],
        3: ["┌─────────┐", "│  ●      │", "│    ●    │", "│      ●  │", "└─────────┘"],
        4: ["┌─────────┐", "│  ●   ●  │", "│         │", "│  ●   ●  │", "└─────────┘"],
        5: ["┌─────────┐", "│  ●   ●  │", "│    ●    │", "│  ●   ●  │", "└─────────┘"],
        6: ["┌─────────┐", "│  ●   ●  │", "│  ●   ●  │", "│  ●   ●  │", "└─────────┘"]
    }

    rolls = []

    for i in range(num_of_dice):
        r = random.randint(1, 6)
        rolls.append(r)

    display_string = ""

    for roll in rolls:
        for line in die_art[roll]:
            if die_art[roll] == rolls:
                display_string.append(die_art[line])

    return(rolls, display_string)

result = roll_dice()
print(result[0])
print(result[1])
Asked By: lli

||

Answers:

Several issues, mostly not sure what you were trying to achieve with if die_art[roll] == rolls:

This is what you want:

display_string = []

for roll in rolls:
    for line in die_art[roll]:
        display_string.append(line) # line is already what you want to print
display_string = "n".join(display_string) # add new line breaks between lines

Edit: to print dice horizontally:

display = []
for roll in rolls:
    display.append(die_art[roll])
display_string = 'n'.join((' '.join(line) for line in zip(*display)))

This is just taking the first lines and stiching them with a space in between, then repeat with 2nd, 3rd, etc lines for each die. Finally add the line breaks as before.

Answered By: Julien
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.