我正在尝试建立一个系统来随机生成基本战舰游戏的船位。使用嵌套列表表示网格。然而,一旦函数完成,矩阵似乎恢复到我运行函数之前的状态。
正如您通过运行此代码所看到的那样,整个矩阵在函数内打印时按预期工作,但事后却没有。这是我第一次尝试自己建造的项目,而且我很久以前从未陷入困境。感谢
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]