首页 > 解决方案 > 在 Python 中使用函数递增给定数字

问题描述

我正在尝试在 python 中模拟一个简单的游戏。在这个游戏中,玩家将掷一个骰子,然后根据骰子(编号从 1 到 6)从当前位置向终点线(位于位置 100)移动。

我正在尝试提出一个可以执行以下操作的函数:添加当前位置和骰子的结果。但是,如果此函数给出的数字大于 100,则该函数将忽略它并再次掷骰子,因为 100 之后没有位置。

您可以在下面找到我提出的“伪代码”(一半真实代码,一半我的想法/评论):

import random 

def movement(current_position, distance):
        current_position = 0 #a counter should be added here I guess to increment the position
        distance = random.randint(1,6)
        move = current_position + distance
              if move > 100; do:
                  #function telling python to ignore it and throw the dice again
              elif move = 100; do:
                  print("You reached position 100")
              else:
                  return move

你能帮我弄清楚怎么做吗?

标签: python

解决方案


您可以设置这样的条件,如果掷骰子将当前值推到 100 以上,它将被忽略,直到掷骰子创建的值等于 100

from random import randint

current = 0
while current != 100:
    r = randint(1, 6)
    if current + r > 100:
        continue
    else:
        current += r
    print(current)
4
8
...
89
93
96
98
99
100

推荐阅读