如何仅使用其值删除变量

时间:2018-05-19 20:54:13

标签: python

我试图制作类似于这个的游戏,https://gyazo.com/8d8dff02a09d27ba28ed303979f64894它叫做Farkle!它是如何工作的,你掷骰子,如果你掷1并得到100分(或另一个骰子给你分数)那个骰子被带走直到你Farkle,改变转身或你赢得比赛。但我不确定如何在掷骰子后根据其价值暂时取消骰子。有人可以告诉我根据其值删除变量的方法吗?

from random import randint
score1 = 0
def dices():
    score1 = 0
    a = 0
    dice1 = randint(1, 6)
    dice2 = randint(1, 6)
    dice3 = randint(1, 6)
    dice4 = randint(1, 6)
    dice5 = randint(1, 6)
    dice6 = randint(1, 6)
    rolled_dice = [dice1, dice2, dice3, dice4, dice5, dice6]
    one_count = rolled_dice.count(1)
    a = [0, 100, 200, 300, 1000, 2000, 300][one_count]
    two_count = rolled_dice.count(2)
    score1 += a
    a = [0, 0, 0, 200, 1000, 2000, 3000][two_count]
    score1 += a
    three_count = rolled_dice.count(3)
    a = [0, 0, 0, 300, 1000, 2000, 3000][three_count]
    score1 += a
    four_count = rolled_dice.count(4)
    a = [0, 0, 0, 400, 1000, 2000, 3000][four_count]
    score1 += a
    five_count = rolled_dice.count(5)
    a = [0, 50, 100, 500, 1000, 2000, 3000][five_count]
    score1 += a
    six_count = rolled_dice.count(6)
    a = [0, 0, 0, 600, 1000, 2000, 3000][six_count]
    score1 += a

    print(score1)
    if score1 == 0:
        print("Farkle!")
    print(rolled_dice)

dices()

1 个答案:

答案 0 :(得分:0)

让我们像在现实生活中一样思考它。如果你掷骰子并希望保留一些结果,你可以将它们标记下来或将它们放在一边直到你滚动其他结果。 不要扔掉它们,因为结果仍然很重要。

编码时也会发生同样的情况,您不想丢弃以后可能需要的值。相反,你把它们写在安全的地方,直到你需要它们为止。

你可以通过将骰子的结果保存在list并编写reroll函数来实现这一点,该函数只会重新滚动一些骰子,而不是全部。

import random

def reroll(dices, *pos):
    for x in pos:
        dices[x] = random.randint(1, 6)

# This creates a list with 6 dices result in it
dices = [random.randint(1, 6) for _ in range(6)]
print(dices)  # [1, 5, 3, 6, 6, 5]

# We now only want to reroll the first and third dices
reroll(dices, 0, 2)
print(dices)  # [4, 5, 1, 6, 6, 5]

一个更好的解决方案是 mutate 您的数据,即允许您在重新注册时保留以前的结果,将使reroll返回一个新的值列表,其中它只重新滚动了一些骰子。

import random, copy

def reroll(dices, *pos):
    dices = copy.copy(dices)
    for x in pos:
        dices[x] = random.randint(1, 6)
    return dices

dices = [random.randint(1, 6) for _ in range(6)]

# reroll returns a new list of values
new_dices = reroll(dices, 0, 2)

print(dices)      # [6, 3, 4, 2, 4, 3]
print(new_dices)  # [1, 3, 2, 2, 4, 3]