我最近开始学习Python,并决定尝试制作我的第一个项目。我正在尝试制作一款战舰游戏,随机在棋盘上放置两艘长度为3的船只。但是它并没有完全正常工作。我为第二艘船制作了一个while循环,它应该检查并查看其旁边的两个空格是否为空闲,然后在那里建造自己。但有时它会直接放在第一艘船的位置上。有人能帮帮我吗?
以下是代码的第一部分:
以下是代码的第一部分:
from random import randint
###board:
board = []
for x in range(7):
board.append(["O"] * 7)
def print_board(board):
for row in board:
print " ".join(row)
###ships' positions:
#ship 1
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
row_1 = random_row(board)
col_1 = random_col(board)
#ship 2
row_2 = random_row(board)
col_2 = random_col(board)
def make_it_different(r,c):
while r == row_1 and c == col_1:
r = random_row(board)
c = random_col(board)
row_2 = r
col_2 = c
make_it_different(row_2,col_2)
### Makes the next two blocks of the ships:
def random_dir():
n = randint(1,4)
if n == 1:
return "up"
elif n == 2:
return "right"
elif n == 3:
return "down"
elif n == 4:
return "left"
#ship one:
while True:
d = random_dir() #reset direction
if d == "up":
if row_1 >= 2:
#building...
row_1_2 = row_1 - 1
col_1_2 = col_1
row_1_3 = row_1 - 2
col_1_3 = col_1
break
if d == "right":
if col_1 <= len(board[0])-3:
#building...
row_1_2 = row_1
col_1_2 = col_1 + 1
row_1_3 = row_1
col_1_3 = col_1 + 2
break
if d == "down":
if row_1 <= len(board)-3:
#building...
row_1_2 = row_1 + 1
col_1_2 = col_1
row_1_3 = row_1 + 2
col_1_3 = col_1
break
if d == "left":
if col_1 >= 2:
#building...
row_1_2 = row_1
col_1_2 = col_1 - 1
row_1_3 = row_1
col_1_3 = col_1 - 2
break
ship_1 = [(row_1,col_1),(row_1_2,col_1_2),(row_1_3,col_1_3)]
这里是“船2”部分的内容:
#ship two:
while True:
d = random_dir() #reset direction
if d == "up":
if row_2 >= 2:
if (row_2 - 1,col_2) not in ship_1 and (row_2 - 2,col_2) not in ship_1:
#building...
row_2_2 = row_2 - 1
col_2_2 = col_2
row_2_3 = row_2 - 2
col_2_3 = col_2
break
if d == "right":
if col_2 <= len(board[0])-3:
if (row_2 ,col_2 + 1) not in ship_1 and (row_2,col_2 + 2) not in ship_1:
#building...
row_2_2 = row_2
col_2_2 = col_2 + 1
row_2_3 = row_2
col_2_3 = col_2 + 2
break
if d == "down":
if row_2 <= len(board)-3:
if (row_2 + 1 ,col_2) not in ship_1 and (row_2 + 2,col_2) not in ship_1:
#building...
row_2_2 = row_2 + 1
col_2_2 = col_2
row_2_3 = row_2 + 2
col_2_3 = col_2
break
if d == "left":
if col_2 >= 2:
if (row_2 ,col_2 - 1) not in ship_1 and (row_2,col_2 - 2) not in ship_1:
#building...
row_2_2 = row_2
col_2_2 = col_2 - 1
row_2_3 = row_2
col_2_3 = col_2 - 2
break
###test
board[row_1][col_1] = "X"
board[row_1_2][col_1_2] = "X"
board[row_1_3][col_1_3] = "X"
board[row_2][col_2] = "Y"
board[row_2_2][col_2_2] = "Y"
board[row_2_3][col_2_3] = "Y"
#Ship1 = X's and Ship2 = Y's
print_board(board)
make_it_different
函数没有做任何事情。在函数末尾加一个return
,然后用这个代替:row_2, col_2 = make_it_different(row_2,col_2)
。当你在函数内设置变量时,你并没有在全局范围内设置它(除非你想在函数中使用全局的row_2
和col_2
变量,但我不建议这样做)。 - scohe001board=[["O"]*WIDTH for i in range(HEIGHT)]
,其中我将魔法数字 7 移到变量以提高可读性。 - Blaine