使用python的压路机

时间:2014-07-12 04:12:24

标签: python

所以我一直在组建一个基于文本的小游戏,我想知道这是否是执行模具滚轮的最佳方式:

import random

def roll_die(die_type, roll_times, print_op):
    total_roll = 0
    for roll_times:
        roll_result = random.randint(1, die_type)
        roll_result += total_roll
        if print_op == True:
            print(roll_result)
            print(total_roll)

我在python中没有做太多的事情,所以如果这是我理解的超乎理解的可怕。

2 个答案:

答案 0 :(得分:2)

这是一个把握事物分成小的,自包含的函数并传递参数的好时机。在我看来,你在这里有两个任务:

  1. 滚动一个模具一次;和
  2. 多个卷的总和。
  3. 所以这应该是两个功能:

    import random
    
    def roll_die(die_type, print_op=False):
        roll_result = random.randint(1, die_type)
        if print_op:
            print("Roll: {0}.".format(roll_result))
        return roll_result
    
    def roll_dice(die_type, roll_times, print_op=False):
        total_roll = 0
        for _ in range(roll_times):
            total_roll += roll_die(die_type, print_op)
            if print_op:
                print("Running total: {0}.".format(total_roll))
        return total_roll
    

    使用中:

    >>> print("Output: {0}.".format(roll_dice(6, 3, True)))
    Roll: 5.
    Running total: 5.
    Roll: 1.
    Running total: 6.
    Roll: 5.
    Running total: 11.
    Output: 11.
    

答案 1 :(得分:1)

如果我是你,我会做什么,使你的代码适应有效的东西,似乎做你想做的事情:

import random

def roll_die(die_type, roll_times, print_op=False):
    total_roll = 0              # you need to use an iterable to iterate over
    for _ in range(roll_times): # range is made for this
        roll_result = random.randint(1, die_type)
        total_roll += roll_result # you mixed these up
        if print_op:
            print(roll_result)
    if print_op:
        print(total_roll)
    return total_roll # don't forget to return your result

使用演示:

>>> print('returning:', roll_die(6, 3, True))
1
6
5
12
('returning:', 12)