Python矩阵正在函数外重置

2024-04-26 05:45:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图建立一个系统,随机生成一个基本战舰游戏的船位。为了表示网格,我使用嵌套列表。但是一旦函数完成,矩阵就会恢复到我运行函数之前的状态。你知道吗

正如您通过运行此代码所看到的,当在函数中打印时,整个矩阵都能按预期工作,但之后就不能了。这是我第一次尝试建立自己的程序,我从来没有被困这么久以前。谢谢

import random

row, column = 10, 10;
Matrix = [[0 for x in range(row)] for y in range(column)] 

ships = {'battleship':5, 'cruiser':4,'destroyer':3}
any_left = 1

def position_ship(type):
  row, column = 10, 10;
  Matrix = [[0 for x in range(row)] for y in range(column)] 
  ship_size_to_assign = type
  start_pointV = 5 ### random.randint(0,10)
  start_pointH = 5 ### random.randint(0,10)
  start_point_direction = 1 ###random.randint(0,4)
  print start_pointV
  print start_pointH
  print start_point_direction
  start_point_direction = 1
  if start_point_direction == 1:
    n = 0
    if (start_pointV + type) <= 10:
      while ship_size_to_assign != 0:
        Matrix[(start_pointH-1)][(start_pointV+n-1)] = 1
        print "----------"
        print Matrix[(start_pointH-1)][(start_pointV+n-1)]
        print "----"
        n = n + 1
        ship_size_to_assign = ship_size_to_assign - 1
  if start_point_direction == 2:
    print "/////"
    n = 0
    if (start_pointH + type) <= 10:
      while ship_size_to_assign != 0:
        Matrix[start_pointH+n-1][start_pointV-1] = 1
        n = n + 1
        ship_size_to_assign = ship_size_to_assign - 1
  if start_point_direction == 3:
    print "/////"
    n = 0
    if (start_pointV - type) > 0:
      while ship_size_to_assign != 0:
        Matrix[start_pointH-1][start_pointV-n-1] = 1
        n = n + 1
        ship_size_to_assign = ship_size_to_assign - 1
  if start_point_direction == 4:
    print "/////"
    n = 0
    if (start_pointH - type) > 0:
      while ship_size_to_assign != 0:
        Matrix[start_pointH-1][start_pointV+n-1] = 1
        n = n + 1
        ship_size_to_assign = ship_size_to_assign - 1
  print "####"
  print Matrix[0]
  print Matrix[1]
  print Matrix[2]
  print Matrix[3]
  print Matrix[4]
  print Matrix[5]
  print Matrix[6]
  print Matrix[7]
  print Matrix[8]
  print Matrix[9]

position_ship(5)

print "/////"
print Matrix[0]
print Matrix[1]
print Matrix[2]
print Matrix[3]
print Matrix[4]
print Matrix[5]
print Matrix[6]
print Matrix[7]
print Matrix[8]
print Matrix[9]

Tags: tosizeiftyperandomstartmatrixrow