现在的位置: 首页 > 综合 > 正文

Python 入门教程 12 —- Battleship!

2013年10月16日 ⁄ 综合 ⁄ 共 1818字 ⁄ 字号 评论关闭


 第一节

     1 介绍了list的一种方法board.append(["O"] * 5),是把'O'这个元素复制5遍

     2 练习:利用这个方法,使得空列表board为一个5*5的矩阵,元素值为O

board = []
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)

 

 第二节

     1 通过第一节的学习我们知道,5*5的矩阵就是一个二维的列表

     2 我们可以通过for循环来打印二维列表的每一行

     3 练习:通过for循环把二维列表的每一行打印出来

board = []
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)

def print_board(board):
    for row in board:
        print row;


 第三节

     1 介绍了Python中的一种方法join

     2 join方法用来连接字符串,比如

li = ['my','name','is','bob'] 
print ' '.join(li) 
>>'my name is bob' 

     3 练习:把第二节中的board二维列表中的每一行,利用join方法使得每一个O之间都有一个空格

board = []
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)
board.append(["O"]*5)

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


 第四节

     1 首先介绍了Python中产生一个随机数的方法,我们必须要从random里面导出randint,然后利用randint(x,y)产生[x,y]之间的随机数

# generate a random integer between x and y
from random import randint 
randint(x , y)

     2 练习:利用randint(x,y)方法随机产生两个行和列的下标,并且这两个值要小于行和列的长度

# generate a random integer between x and y
from random import randint 

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

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

# Add your code below!
def random_row(board):
    x = randint(0 , len(board)-1)
    return x

def random_col(board):
    x = randint(0 , len(board)-1)
    return x


 第五节

     1 首先回顾了Python的方法raw_input(),用来表示标准的输入,但是返回的值都是认为是字符串

     2 接着介绍了Python的另外一个函数int(),表示把值强制转化为整数,比如int(raw_input())就是把输出的字符串转化成整数

     3 练习:利用int()和raw_input()函数得到两个数,保存到变量ship_row和ship_col中

from random import randint

board = []

for x in range(0,5):
    board.append(["O"] * 5)

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

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)

# Add your code below!
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

抱歉!评论已关闭.