[英]How to move forward and possibly backward a specified number of steps in a python list?
我正在尝试用 Python 制作棋盘游戏。 但是,我坚持其中的一部分。
例如:
如果你有一个清单:
lst = [1, 2, 3, 4, 5, 6, 'E']
玩家可以掷出 1-6,并且可以从“E”以外的任何位置开始,因为那是获胜空间。 如果玩家处于索引 3 或值 4,并且掷出 3,他们会降落在“E”空间,一切都很好。 但是,例如,如果他们掷出 6,他们将向前移动 3 步到“E”值,然后“反弹”3 个空格回到索引 3 或值 4,总共移动 6 次。 如果他们从索引 5 开始,滚动 5,他们将回到索引 2 总共 5 次移动等。我不确定如何实现这样的东西,或者是否有更好的方法来构造它? 任何帮助表示赞赏。
你可以做这样的事情; 我已开始在列表中指定为索引 3,即“4”。
lst = [1, 2, 3, 4, 5, 6, 'E']
start = 3
roll = 6
if start + roll >= len(lst):
finish = 2 * len(lst) - 2 - (start + roll)
else:
finish = start + roll
print(lst[finish])
输出:
4
我写了一个小逻辑,可能会有所帮助。 我不确定您如何输入您的第一个值(随机化或输入),但您可以稍微更改一下以解决您需要的问题。
lst = [1, 2, 3, 4, 5, 6, 'E']
lost = 1 #to loop
count = 0 #to remember the carry
while(lost):
number = int(input("What do you wanna role? "))
if number > 0 and number < 7:
newVal = number+count
if newVal > 6:
subtract = 6 - newVal
newVal = 6+subtract
elif lst[newVal] == "E":
print("WIN")
lost = 0;
count = newVal;
print(newVal)
else:
print("Number should be in 1-6")
您可以将 while 循环中的所有 print(current_position) 变量替换为您的列表:print(list1[current_position-1]),这基本上是相同的。 您也可以使用列表更改所有内容,除非您真的真的需要像那样遍历列表,否则我认为这样做没有任何意义。
import random
Running = True
current_position = int(input('select a number 1-6: '))
while Running == True:
option = str(input('type Y to roll, type Q to quit: '))
if option == 'Y':
roll = random.randint(1,6)
print('current position: ',current_position)
print('rolled number: ',roll)
if (current_position + roll) == 7:
print(f'!!!!!!!!Congatulations !!!!!!!!, You have scored {current_position + roll}')
Running = False
if (current_position + roll)>7:
current_position = (current_position-(6-roll))
print('current_position: ',current_position)
elif (current_position + roll) <= 6:
current_position = current_position + roll
print('current position: ',current_position)
else: Running = False
outputs:
select a number 1-6: 3
type Y to roll, type Q to quit: Y
current position: 3
rolled number: 2
current position: 5
type Y to roll, type Q to quit: Y
current position: 5
rolled number: 1
current position: 6
type Y to roll, type Q to quit: Y
current position: 6
rolled number: 4
current_position: 4
type Y to roll, type Q to quit: Y
current position: 4
rolled number: 3
!!!!!!!!Congatulations !!!!!!!!, You have scored 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.