Python使用列表操作

时间:2016-04-10 12:49:19

标签: python random grid

我创建了一个功能齐全的网格。有一个玩家可以四处移动并收集宝箱和地精。虽然我在tresures和地精中产卵时会出现问题。它们扩展了我不希望发生的网格大小。有谁可以帮忙解决这个问题?需要修复的部分是ChestsandGoblins功能。这是我的代码:

from random import *
# Set up Initial Variables
Money = "0"
grid = []
character = "X" 
# player_loc will hold the x, y location of the player
player_loc = (0, 0)
# These are a mapping of direction
treasure_loc = (0, 0)
NORTH = "N"
SOUTH = "S"
EAST  = "E"
WEST  = "W"   #All variables used for Later on
Treasure = "T"
Goblin = "G"





def setupGrid():
global grid
global row
global N
N = input("How big would you like the grid to be?")
for x in range(0, (int(N))):
    row = []
    for y in range(0, (int(N))):
        if x == player_loc[0] and y == player_loc[1]:
            row.append(character)
        else:
            row.append('O')
    grid.append(row)

def Chests_and_Goblins():
   global grid
   global row
   global N
   print("How many chests would you like in the grid?")     
   B = input("The amount of chests you like is given by the amount of C's")
   for each in B:
      grid[randint(0, (int(N)))].insert(randint(0, (int(N))), Treasure)
      grid[randint(0, (int(N)))].insert(randint(0, (int(N))), Goblin)









def moveSouth(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0] + n][player_loc[1]] = character
    player_loc = (player_loc[0] + n, player_loc[1])

def moveNorth(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0] - n][player_loc[1]] = character
    player_loc = (player_loc[0] - n, player_loc[1])

def moveEast(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0]][player_loc[1] + n] = character
    player_loc = (player_loc[0], player_loc[1] + n)

def moveWest(n):
    global player_loc
    grid[player_loc[0]][player_loc[1]] = "O"
    grid[player_loc[0]][player_loc[1] - n] = character
    player_loc = (player_loc[0], player_loc[1] - n)

def gridRunner():
    while True:
        for row in grid:
            print (row)

        switch = {NORTH : moveNorth,
                  SOUTH : moveSouth,
                  EAST  : moveEast,
                  WEST  : moveWest }
        P = input("What direction would you like to move in? North (N), South(S), East(E) or West(W)?").upper()

        if P not in switch:
            print ("invalid move")
            continue

        distance = int(input("How far would you like to move in this direction? (blocks are the units)"))
        switch[P](distance)







setupGrid()
Chests_and_Goblins()
gridRunner()

1 个答案:

答案 0 :(得分:0)

insert将列表的大小增加一个。要保留列表的原始大小,请改为使用赋值。

grid[randint(0, int(N)-1)][randint(0, int(N)-1)] = Treasure

请注意,这可能会覆盖现有哥布林/宝贝/玩家的位置。首先生成对象的x和y坐标,然后验证该点中没有任何内容,然后才执行赋值可能是个好主意。

while True:
    x = randint(0, int(N))
    y = randint(0, int(N))
    if grid[x][y] == "O":
        grid[x][y] = Treasure
        break