这是只有一艘船的原始代码:
#Battleships
from random import randint
board = []
for x in range(8):
board.append(["O "] * 8)
def print_board(board):
for row in board:
print (" ".join(row))
print ("Let's play Battleship!\n\n")
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
for turn in range(5):
guess_row = int(input("Guess Row:"))
guess_col = int(input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print ("Congratulations! You sunk my battleship!")
break
else:
if turn==5:
print ("Game Over")
elif (guess_row < 0 or guess_row > 7) or (guess_col < 0 or guess_col > 7):
print ("Oops, that's not even in the ocean.")
elif(board[guess_row][guess_col] == "X "):
print ("You guessed that one already.")
else:
print ("You missed my battleship!")
board[guess_row][guess_col] = "X "
print ("Turn:",turn+1)
print_board(board)
然后我尝试添加更多船只,但它不起作用:
#Battleships
from random import randint
board = []
for x in range(8):
board.append(["O "] * 8)
def print_board(board):
for row in board:
print (" ".join(row))
print ("Let's play Battleship!\n\n")
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
import random
ships = [['row',random_row,'col',random_col]]
for i in range(9):
ships.append(['row',random_row,'col',random_col])
random.choice(ships)() #i am lost
def main():
for turn in range(64):
guess_row = int(input("Guess Row:"))
guess_col = int(input("Guess Col:"))
if guess_row == random_row in ships and guess_col == random_col in ships:
print ("Congratulations! You sunk my battleship!")
continue
else:
if turn==65:
print ("Game Over")
break
elif (guess_row < 0 or guess_row > 7) or (guess_col < 0 or guess_col > 7):
print ("Oops, that's not even in the ocean.")
elif(board[guess_row][guess_col] == "X "):
print ("You guessed that one already.")
else:
print ("You missed my battleship!")
board[guess_row][guess_col] = "X "
print ("Turn:",turn+1)
print_board(board)
main()
答案 0 :(得分:0)
我要做的是制作Ship
课程,然后制作list
Ship
个。像这样的东西。
class Ship:
def __init__(self, col, row):
self.col = col
self.row = row
# Say you want 5 ships
NUMBER_OF_SHIPS = 5
ships = []
for i in range(NUMBER_OF_SHIPS):
# random_row, random_col, and board are just like you had them
ships.append(Ship(random_col(board), random_row(board)))
# After you get the guesses...
for i in ships:
if guess_row == i.row and guess_col == i.col:
# Player wins...
break
finally:
# Player loses