The idea is, you enter an amount of ships, for example 10. It will then place 10 ships on a 10x10 grid (0-9). You may enter a coordinate, and it will tell you if it is a hit or a miss. A simplified version of the well-known board game.
- C indicates 'Computer'. These are not shown on the grid, but are stored in the 2D array.
- H indicates 'Hit'. Self explanatory.
- M indicates 'Miss'. Also self explanatory.
- Null / whitespace indicates that nothing has been set at that coordinate.
I created this program with the intent of making it as efficient and readable as possible. It's difficult to explain the inner workings of my mind, so I apologize for no comments.
best ran outside of IDE (in console)
import random, os ships = int(input("Enter ship count: ")) gridSize = 10 game = [[' ' for x in range(gridSize)] for y in range(gridSize)] def getGrid(x,y): return game[x][y] def setGrid(x,y,char): game[x][y] = char for i in range(ships): x = random.randint(0,gridSize-1) y = random.randint(0,gridSize-1) setGrid(x,y,'C') xLabel = " " * 3 for i in range(gridSize): xLabel += str(i) + " " result = "Make a move!" hits = 0 while hits != ships: os.system("cls") print(" " + result + " [Ships: " + str(ships) + ", Size: " + str(gridSize) + ", Hits: " + str(hits) + "]\n") print(xLabel) for x in range(gridSize): print(" " + str(x) + " ",end="") for y in range(gridSize): print(" " * 2 if getGrid(x,y) == 'C' else getGrid(x,y) + " ",end="") print("") xGuess = int(input("\n X: ")) yGuess = int(input(" Y: ")) if getGrid(xGuess,yGuess) == 'C': result = "Hit! (" + str(xGuess) + ":" + str(yGuess) + ")" setGrid(xGuess,yGuess,'H') hits += 1 else: result = "Miss! (" + str(xGuess) + ":" + str(yGuess) + ")" setGrid(xGuess,yGuess,'M') print("\nCongratulations, you won the game!") os.system("pause >nul")