Recently learning Python, this is a small game written today.
fromRandomImportRandintclassBoard (object): Board= [] def __init__(self,row,col): Self.board=[] Self.row=Row Self.col=Col forIinchrange (Row): Self.board.append (["O"] *Col)defPrint_board (self): space= (Self.col * 2-8)/2Print "-"* Space +"Board"+"-"*SpacePrint "-"* Self.col * 2 forRinchSelf.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 was 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 hits 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=False whileTurn < 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: if notResult:Print "Game over"My_game= Game (5,5)
Python-written battle ship games-1.0