最近学python,这是今天写的一个小游戏。
from random import randint class Board(object): board = [] def __init__(self,row,col): self.board = [] self.row = row self.col = col for i in range(row): self.board.append( ["O"] * col ) def print_board(self): space = (self.col * 2 - 8)/2 print "-" * space + " Board " + "-" * space print "-" * self.col * 2 for r in self.board: print " ".join(r) print "-" * self.col * 2 class Game(object): loop_time = 4 def __init__(self,row,col): self.row = row self.col =col self.actual_row = -1 self.actual_col = -1 self.guess_row = -100 self.guess_col = -100 self.main_loop() def random_row(self): return randint(1, self.row) def random_col(self): return randint(1, self.col) def set_ship(self): """the battle ship is here:""" self.actual_col = self.random_col() self.actual_row = self.random_row() print self.actual_row print self.actual_col self.my_board_actual.board[self.actual_row - 1][self.actual_col - 1] = "S" def get_input_from_player(self): print "Please select where to hit on the board:" self.guess_row = int(raw_input("To hit Row:")) - 1 self.guess_col = int(raw_input("To hit Col:")) - 1 def check_if_hit(self): if self.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" return True else: if self.guess_row < 0 or self.guess_col < 0 or self.guess_row > self.row or self.guess_col > self.col: print "Ooops, that‘s not even in the ocean." elif self.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" return False def main_loop(self): print "Game Start: Let‘s play Battleship!" turn = 1 #print "Turn", turn my_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 = False while turn < self.loop_time + 1: print "\nTurn", turn self.get_input_from_player() result = self.check_if_hit() my_board.print_board() if result: turn = self.loop_time + 2 else: turn += 1 else: if not result: print "Game Over" my_game = Game(5,5)
时间: 2024-10-11 01:35:23