我試圖讓遊戲採取用戶將有多少船隻等的輸入,並把許多船隻的用戶輸入。我已經把座標放在一個列表中,這就是我如何存儲它們,並檢查它是否是一個命中。但船舶獲得放置在對方,而與此列表的方法,我不知道如何首先檢查他們不重疊,並且所有的第二,改變它,以便他們不是。Python的戰列艦:讓他們有多少船隻要
from random import randint
print('Welcome to Battleships for 1 player! Please be careful with entries, as if you get it wrong, you will still lose a go!')
print('Good luck!')
print('')
no_of_goes = int(input("How many goes would you like: "))
size_of_board = int(input("And how big would you like the board to be: "))
if size_of_board > 56:
print("That board will be too big to fit on the screen (max 56)")
size_of_board = int(input("And choose a more sensible number: "))
no_of_ships = int(input("And finally, how many ships would you like?: "))
board = []
# printing out the board
for x in range(size_of_board):
board.append(["O"] * size_of_board)
def print_board(board):
for row in board:
print (" ".join(row))
print_board(board)
# the lists that will become the locations
ship_rows = []
ship_cols = []
# generating random locations
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board) - 1)
# adding locations to lists
ships = list(range(no_of_ships))
for i in ships:
row = random_row(board)
col = random_col(board)
ship_rows.append(row)
ship_cols.append(col)
##
## And this is my attempt (didn't work)
##
for row in ship_cols:
if row == ship_cols and col == ship_cols:
ship_rows[-1] = random_row(board)
ship_cols[-1] = random_col(board)
# allowing to see where ships are and logging how many ships have been hit
print(ship_rows)
print(ship_cols)
ship_count = [1]
## I couldn't find a way of ending the game once the ships were sunk, so I stuck in a recursive function (sorry)
def printing_stars():
print('You have won!! ' +'*' * 56)
printing_stars()
for turn in range(no_of_goes):
# asking for their guesses
print('Turn ' + str(turn + 1) + ' out of ' + str(no_of_goes))
guess_col = int(input("Guess Col:")) - 1
guess_row = int(input("Guess Row:")) - 1
for item in ship_rows:
# If they hit, it gives a '!'
if len(ship_count) == no_of_ships and guess_row == item and guess_col == ship_cols[ship_rows.index(item)]:
print("You have won!!!! Congratulations")
board [guess_row][guess_col] = '!'
print_board(board)
printing_stars()
elif guess_row == item and guess_col == ship_cols[ship_rows.index(item)]:
print ("Congratulations! You sunk one of my battleships")
board [guess_row][guess_col] = '!'
print_board(board)
ship_count.append(1)
break
else:
# all misses
if (guess_row < 0 or guess_row > size_of_board - 1) or (guess_col < 0 or guess_col > size_of_board - 1):
print ("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "!":
print ("You guessed that one already.")
turn -= 1
else:
print ("You missed my battleship!")
board[guess_row][guess_col] = "X"
print_board(board)
if turn == (no_of_goes - 1):
print('Game Over')
break
任何想法?將不勝感激:)
這是從codecademy嗎? –