2016-04-10 72 views
-1

我创建了一个功能齐全的网格。有一名玩家可以四处移动并收集宝箱和地精。虽然在我产卵的地精和地精中有问题。他们扩大了我不想发生的网格大小。任何人都可以帮助解决这个问题吗?需要修复的部分是ChestsandGoblins的功能。这是我的代码:Python使用列表操作

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() 

回答

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 
+0

谢谢!尽管我不明白你编写的其他代码的作用,但代码的最高位帮助不大。没有它,我的代码似乎可以正常工作。再次感谢 –

+0

啊,我现在明白了。虽然我不知道把它放在代码中。你可以帮我吗? –