{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Battleship\n", "### You can learn a lot when you are having fun - [Gerard Gorman](http://www.imperial.ac.uk/people/g.gorman)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", "def create_board(size):\n", " ''''Initialise the board using a Python list.'''\n", " board = []\n", " for x in range(0, size):\n", " board.append([\"O\"] * size)\n", " return board\n", "\n", "def print_board(board):\n", " '''Print out the current board.'''\n", " for row in board:\n", " print(\" \".join(row))\n", " return\n", "\n", "def generate_ship(max_ship_size, board_size):\n", " # We are going to define a ship as a list of board coordinates.\n", " ship = []\n", " \n", " # Randomly select define the size of the ship.\n", " ship_size = random.randint(1, max_ship_size)\n", " \n", " # Randomly define the orientation.\n", " orientation = random.randint(0, 1)\n", "\n", " # Randomly select the seed point for the ship.\n", " iseed = random.randint(0, board_size)\n", " jseed = random.randint(0, board_size)\n", "\n", " # Generate ship - here I'm not going to worry if it goes off the edge.\n", " if orientation==0:\n", " for i in range(ship_size):\n", " ship.append((iseed+i, jseed))\n", " else:\n", " for j in range(ship_size):\n", " ship.append((iseed, jseed+j))\n", "\n", " return ship\n", " \n", "# Set the size of the board and initialise the board.\n", "board_size = 10\n", "board = create_board(board_size)\n", "print_board(board)\n", "\n", "# Add the ship\n", "ship = generate_ship(6, board_size)\n", "\n", "print(\"Let's play Battleship!\")\n", "\n", "for turn in range(4):\n", " try:\n", " row = int(input(\"Guess row:\"))\n", " if row<0 or row>board_size-1:\n", " raise ValueError\n", " except:\n", " print(\"Value must be an integer between 0 and %d. Try again.\"%(board_size))\n", " continue\n", "\n", " try:\n", " column = int(input(\"Guess column:\"))\n", " if column<0 or column>board_size-1:\n", " raise ValueError\n", " except:\n", " print(\"Value must be an integer between 0 and %d. Try again.\"%(board_size))\n", " continue\n", " \n", " if (row, column) in ship:\n", " print(\"Congratulations! You sunk my battleship!\")\n", " break\n", " else:\n", " if turn == 3:\n", " board[row][column] = \"X\"\n", " print_board(board)\n", " print(\"Game Over\")\n", " else:\n", " board[row][column] = \"X\"\n", " print_board(board)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.6", "language": "python", "name": "python36" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.0" } }, "nbformat": 4, "nbformat_minor": 1 }