#!/usr/bin/env python # coding: utf-8 # # Battleship # ### You can learn a lot when you are having fun - [Gerard Gorman](http://www.imperial.ac.uk/people/g.gorman) # In[ ]: import random def create_board(size): ''''Initialise the board using a Python list.''' board = [] for x in range(0, size): board.append(["O"] * size) return board def print_board(board): '''Print out the current board.''' for row in board: print(" ".join(row)) return def generate_ship(max_ship_size, board_size): # We are going to define a ship as a list of board coordinates. ship = [] # Randomly select define the size of the ship. ship_size = random.randint(1, max_ship_size) # Randomly define the orientation. orientation = random.randint(0, 1) # Randomly select the seed point for the ship. iseed = random.randint(0, board_size) jseed = random.randint(0, board_size) # Generate ship - here I'm not going to worry if it goes off the edge. if orientation==0: for i in range(ship_size): ship.append((iseed+i, jseed)) else: for j in range(ship_size): ship.append((iseed, jseed+j)) return ship # Set the size of the board and initialise the board. board_size = 10 board = create_board(board_size) print_board(board) # Add the ship ship = generate_ship(6, board_size) print("Let's play Battleship!") for turn in range(4): try: row = int(input("Guess row:")) if row<0 or row>board_size-1: raise ValueError except: print("Value must be an integer between 0 and %d. Try again."%(board_size)) continue try: column = int(input("Guess column:")) if column<0 or column>board_size-1: raise ValueError except: print("Value must be an integer between 0 and %d. Try again."%(board_size)) continue if (row, column) in ship: print("Congratulations! You sunk my battleship!") break else: if turn == 3: board[row][column] = "X" print_board(board) print("Game Over") else: board[row][column] = "X" print_board(board) # In[ ]: