Py学习  »  Python

在python中使用函数递增给定的数字

Me All • 6 年前 • 1632 次点击  

我正在尝试用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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38996
 
1632 次点击  
文章 [ 2 ]  |  最新文章 6 年前
Turtalicious
Reply   •   1 楼
Turtalicious    6 年前

你可以随时检查它是否超过100,然后再回到原来的位置。然后你从你的主要功能调用movement,说 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
vash_the_stampede
Reply   •   2 楼
vash_the_stampede    6 年前

您可以设置这样的条件:如果骰子掷骰子使当前值超过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