Программа игры в кости со счетчиком - PullRequest
0 голосов
/ 30 мая 2020

Я новичок в программировании, и у меня есть задача, которую я не могу решить самостоятельно.

Задача состоит в том, чтобы создать программу, которая позволит вам решать, сколько кубиков бросить, от 1 до 5, с проверкой правильности ввода. После каждого броска будет отображаться число d ie и сумма на текущий момент. Если d ie выпадает 6, то он не включается в общую сумму, и вы получаете больше бросков. Вот где я застрял. Я хочу, чтобы моя программа перезапустила l oop, если d ie превращается в 6 и просто ad 2 переходит к sumDices и продолжает l oop, но я не могу заставить его работать.

вот мой код:

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

Ответы [ 4 ]

0 голосов
/ 30 мая 2020

Использование рекурсивной функции

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}")
0 голосов
/ 30 мая 2020

Чтобы решить вашу проблему, я бы заменил ваш текущий на l oop на время l oop

Более того, я вижу в вашем коде много неактуальных вещей, я постараюсь их перечислить:

  • Почему вы используете так много «while True»?

  • Почему бы вам просто не использовать функцию exit () для выхода вместо используя переменную?

  • Действительно ли вся часть if действительно необходима, не могли бы вы просто напечатать число?

Вот мое предложение:

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()
0 голосов
/ 30 мая 2020
for i in range(numDices):

Ваш for l oop ограничивает количество итераций, как только range(numDices) оценивается / выполняется. Когда вы пытаетесь увеличить количество итераций с помощью numDices+=2, это не дает никакого эффекта, потому что range(numDices) оценивается только один раз.

Если вы хотите иметь возможность изменить количество итераций, используйте другое, пока l oop и используйте i как счетчик. Что-то вроде.

i = 0
while i <= numDices:
    ...
    ...
    if ...:
        ...
    elif ...:
    ...
    i += 1

Тогда в наборе для elif dicesArray[i] == 6: оператор numDices += 2 эффективно увеличит количество итераций.


Я вижу еще одну проблему, которую вы не знаете. т упомянул. Вы начинаете со списка фиксированной длины на основе исходного значения numDices и используете i в качестве индекса для этого списка.

dicesArray = list(range(numDices))`
...
dicesArray[i]
...

Если i потенциально может быть больше оригинала numDices (больше len(dicesArray)), вы в конечном итоге получите IndexError. Вероятно, вам следует начать с пустого списка и добавить к нему. Чтобы получить последний бросок кубиков, используйте dicesArray[-1] вместо dicesArray[i].

...
dicesArray = []
i = 0
while i <= numDices:
    dicesArray.append(random.randint(1, 6))
    total += dicesArray[-1]
    if dicesArray[-1] == 1:
        ...
    ...

6.3.2. Подписки

0 голосов
/ 30 мая 2020

Вы можете сделать это следующим образом, немного изменив свой код, подсчитав количество доступных кубиков. Я там тоже уменьшил вложенные циклы

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...