Python学习笔记1204

 

BattleShip,这两个是新接触到的

1)生成a,b之间的随机数:

1 from random import randint
2 randint(a,b)

2)去掉list中的引号和逗号

1 def print_board(board):
2     for row in board:
3         print " ".join(row)

 

以下是代码

 1 from random import randint
 2 
 3 board = []
 4 
 5 for x in range(5):
 6     board.append(["O"] * 5)
 7 
 8 def print_board(board):
 9     for row in board:
10         print " ".join(row)
11 
12 print "Let‘s play Battleship!"
13 print_board(board)
14 
15 def random_row(board):
16     return randint(0, len(board) - 1)
17 
18 def random_col(board):
19     return randint(0, len(board[0]) - 1)
20 
21 ship_row = random_row(board)
22 ship_col = random_col(board)
23 print ship_row
24 print ship_col
25 
26 for turn in range(4):
27     print"Turn",turn+1
28     guess_row = int(raw_input("Guess Row:"))
29     guess_col = int(raw_input("Guess Col:"))
30     
31     if guess_row == ship_row and guess_col == ship_col:
32         print "Congratulations! You sunk my battleship!"
33         break
34     else:
35         if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
36             print "Oops, that‘s not even in the ocean."
37         elif(board[guess_row][guess_col] == "X"):
38             print "You guessed that one already."
39         else:
40             print "You missed my battleship!"
41             board[guess_row][guess_col] = "X"
42             print_board(board)
43     if turn==3:
44         print"Game Over"
45         

 

进度有点慢,需要多写代码!

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。