最近学python,这是今天写的一个小游戏。
fromrandomimportrandintclassBoard(object):
board=[]def__init__(self,row,col):
self.board=[]
self.row=row
self.col=colforiinrange(row):
self.board.append( ["O"] *col )defPRint_board(self):
space= (self.col * 2 - 8)/2print"-"* space +"Board"+"-"*spaceprint"-"* self.col * 2forrinself.board:print"".join(r)print"-"* self.col * 2classGame(object):
loop_time= 4def__init__(self,row,col):
self.row=row
self.col=col
self.actual_row= -1self.actual_col= -1self.guess_row= -100self.guess_col= -100self.main_loop()defrandom_row(self):returnrandint(1, self.row)defrandom_col(self):returnrandint(1, self.col)defset_ship(self):"""the battle ship is here:"""self.actual_col=self.random_col()
self.actual_row=self.random_row()printself.actual_rowprintself.actual_col
self.my_board_actual.board[self.actual_row- 1][self.actual_col - 1] ="S"defget_input_from_player(self):print"Please select where to hit on the board:"self.guess_row= int(raw_input("To hit Row:")) - 1self.guess_col= int(raw_input("To hit Col:")) - 1defcheck_if_hit(self):ifself.my_board_actual.board[self.guess_row][self.guess_col] =="S":print"Congratulations! You sunk my battle ship!"self.my_board.board[self.guess_row][self.guess_col]="S"returnTrueelse:ifself.guess_row < 0orself.guess_col < 0orself.guess_row > self.roworself.guess_col >self.col:print"Ooops, that's not even in the ocean."elifself.my_board.board[self.guess_row][self.guess_col] =="X":print"You guessed that one already."else:print"You missed my battleship!"self.my_board.board[self.guess_row][self.guess_col]="X"returnFalsedefmain_loop(self):print"Game Start: Let's play Battleship!"turn= 1#print "Turn", turnmy_board =Board(self.row,self.col)
my_board_actual=Board(self.row,self.col)
self.my_board=my_board
self.my_board_actual=my_board_actual
my_board.print_board()
self.set_ship()
result=Falsewhileturn < self.loop_time + 1:print"\nTurn", turn
self.get_input_from_player()
result=self.check_if_hit()
my_board.print_board()ifresult:
turn= self.loop_time + 2else:
turn+= 1else:ifnotresult:print"Game Over"my_game= Game(5,5)