在Python中使用函数递增给定数字

时间:2018-10-02 21:27:25

标签: 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

您能帮我弄清楚该怎么做吗?

2 个答案:

答案 0 :(得分:1)

您可以这样设置条件:如果掷骰子将当前值推到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

答案 1 :(得分:0)

您始终可以检查它是否超过100,然后恢复到原来的位置。然后,您可以从主函数说def playGame():

调用移动
def playGame():
    position = 0
    while(position != 100):
         position = movement(position)

def movement(current_position):
    distance = random.randint(1,6)
    current_position += distance
          if move > 100:
              current_position -= distance
          else:
              return current_position