蟒蛇使用定义的函数后,我无法调用该函数

问题描述

我想写一个船舶游戏,玩家必须猜测计算机“隐藏”在棋盘上的位置。我的问题是,看起来一切正常,程序编译时没有错误,但是我预定的功能不起作用,我也不知道为什么。我感觉我的变量 board 在被函数 ship 处理后迷失了,之后我再也无法打印带有装运的木板了。我尝试在 ship 函数的末尾使用 return bo ,但是它也不起作用。 有什么问题吗? 我真的迷路了,不知道这里可能是什么问题:(

import random
board = []

for i in range(0,10):
   board.append([0])
   for j in range(0,9):
    board[i].append(0)
def board_print(bo):
for i in range(len(bo)):
    if i == 0:
        print("--------------------")
    for j in range(len(bo[0])):
        if j == 9:
            print(bo[i][j])
        else:
            print(str(bo[i][j]) + " ",end="")
    print("--------------------")
def ship_start():
  pos_x = random.randint(0,9)
  pos_y = random.randint(0,9)
  return(pos_x,pos_y) # coordinates of ships first point
def ship(bo): # creates ship with 4 hp points
  row,col = ship_start()
  print(row,col)
  coin_flip = 1 #random.randint(0,1) # 0 - horizontal,1 - vertical
  if coin_flip == 1:
    i = 0
    while 3 - i > 0:
       if bo[row + i][col] in bo == True:
          bo[row][col] = 1
          i =i + 1
       else:
          j = 4 - i
          for x in range(j):
            bo[row - x][col] = 1
ship(board)
board_print(board)

解决方法

此行以两种不同的方式断开:

if bo[row + i][col] in bo == True:

第一个问题是Python具有称为chained comparisons的功能。

这可以创建漂亮的数学风格比较链,例如0 <= foo < 5a == b == c,但是有些意外地比较是任意的,这意味着您可以编写a < b in c > d,并且可以有效地以(a < b) and (b in c) and (c > d)的身份执行(仅计算每个表达式一次)。

这是

bo[row + i][col] in bo == True

未解析为

(bo[row+1][col] in bo) == True

(顺便说一句,是多余的),但是

(bo[row+1][col] in bo) and (bo == True)

由于bo不是布尔值,所以永远不可能成立,因此i永远不会更新,循环永远不会终止。

不是什么都丢失了,而是ship 从不终止

然后还有第二个逻辑问题:

bo[row + i][col]

是一个整数,但是bo是一个列表列表,因此即使没有中断的比较

bo[row + i][col] in bo

永远不可能为真,因此ship still 永远不会终止。我实在无能为力,因为我不知道此功能实际上在做什么。

还有很多其他小问题/语言缺陷,例如board_print可以直接在bo上进行迭代,或者您可以使用列表理解和列表乘法来初始化您的开发板:

board = [[0] * 10 for _ in range(10)]
def board_print(bo):
    print("--------------------")
    for row in bo:
        for cell in row:
            print(cell,end=' ')
        print()
    print("--------------------")

您可能应该将电路板尺寸存储为常数,并使用randrange以使所有内容都匹配(randrange(10)randint(0,9)相同)。而且return不是一个函数,通常,关键字与要返回的任何内容之间都有一个空格。