将变量迭代到下一个列表项

时间:2017-08-10 15:39:21

标签: python python-3.x

我试图找到一种方法将值(房间)增加到列表(地牢)中的下一个项目,这样我就可以在文本冒险中创建一个随机的房间实例。

def dungeon_generator(): #used to generate random dungeon order
    dungeon = random.sample(range(2, 19), 8)
    dungeon.append(20) #used to add Boss
    dungeon[:0]=[1] #used to add Entrance

伪代码:

room = dungeon[0] #i.e. room == 1
while room != 0

    if room == 1:
        do things in room
        room finished
        room = NEXT number in dungeon list

    elif room == 2
        do things in room
        room finished
        room = NEXT number in dungeon list

etc

    elif room == 0
        game over

有人能建议从地牢列表中读取下一项的最佳方法吗?由于我已使用random.sample,因此如果有帮助,列表项将是唯一的。

3 个答案:

答案 0 :(得分:2)

import random

def dungeon_generator(): #used to generate random dungeon order
    dungeon = random.sample(range(2, 19), 8)
    dungeon.append(20) #used to add Boss    
    dungeon[:0]=[1] #used to add Entrance
    return dungeon


room = 0 #i.e. room == 1

dungeon = dungeon_generator();

while room < len(dungeon) and dungeon[room] != 0:
    if dungeon[room] == 1:        
        # do something
        print (dungeon[room])
    elif dungeon[room] == 2:
        # do something
        print (dungeon[room])
    room = room + 1

答案 1 :(得分:1)

使用变量来访问地牢。

roomNumber = 1
room = dungeon[roomNumber]

if room == 1:
    do things in room
    roomNumber += 1

etc...

这样,您无需手动跟踪索引。

答案 2 :(得分:0)

您可以简单地使用for循环来迭代房间号码。

dungeon = [1, 3, 2, 20]

for room in dungeon:
    if room == 1:
        print('room 1')
    elif room == 2:
        print('room 2')
    elif room == 3:
        print('room 3')
    # etc.

如果你想尝试更好的东西,你可以为不同的房间定义功能(或类),然后将这些功能添加到dungeon列表而不是数字。

import random

def room1():
    print('In room1.')

def room2():
    print('In room2.')

def room3():
    print('In room3.')

def intro_room():
    print('Intro')

def boss_room():
    print('Boss')

def dungeon_generator():
    """Create a list of function objects (the rooms)."""
    dungeon = [intro_room]
    dungeon += random.sample((room1, room2, room3), 2)    
    dungeon.append(boss_room)
    return dungeon


dungeon = dungeon_generator()

for room in dungeon:  # Iterate over the room functions.
    room()  # Now call the current room function.