剛剛在Codecademy完成了BattleShip的練習,原本打算改成2P,不過我先把它改成Python34的格式再加入重新開始和結束的選項。老實說,這遊戲真的不太好玩,編碼如下:
from random import randint
#function for print out the board
def print_board(board):
for row in board:
print (" ".join(row))
#variable for restart
re=1
while (re==1):
#generate a game board
board = []
for row in range(5):
board.append(["O"]*5)
ship_row = randint(0,len(board)-1)
ship_col = randint(0,len(board[0])-1)
print ("Battle Ship!")
print_board(board)
#for debug, del it after finish
print ("(", ship_row, ",", ship_col, ")")
#give 4 turns to guess
for turn in range(4):
print ()
print ("Turn ",turn+1)
guess_row = int(input("Guess Row:"))
guess_col = int(input("Guess Col:"))
#different result according to the guess
if guess_row == ship_row and guess_col == ship_col:
board[guess_row][guess_col] = "W"
print ()
print ("Congratulations! You sunk my battleship!")
print_board(board)
break
else:
print ()
if guess_row not in range(5) or guess_col not in range(5):
print ("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print ("You guessed that one already.")
else:
board[guess_row][guess_col] = "X"
print ("You missed my battleship!")
print_board(board)
if turn == 3:
print ("Gome Over")
print ()
#variable for asking restart
res=1
while(res==1):
response = input("Restart(Y/N)? ")
print ()
response = response.upper()
if response == "Y":
res=0
elif response == "N":
res=0
re=0
else:
print ("Invalid Input")
print ()
print ()
print ()
print ()
raise SystemExit("See You!")
當中加入了while loop和raise SystemExit()來作重新開始和結束遊戲的選擇。