# Libraries Section # from random import randint # Introduction Section # print("Welcome to BattleShip! \n") print("This version only includes single player mode. You battle AI. \n") print("-----") print("\nWould you like instructions on how to play? \n yes \n no \n") response = str(input()) if response == "yes": print("⠀") print("Here's the basic rundown: \n") print("You're an idiot. \n") elif response == "no": print("⠀") print("No? All right! \n") print("----- \n") # Board Creation Section # board = [] dimensions = int(input("Enter the width and length you want the board to be: ")) for x in range(dimensions): board.append(["O"] * dimensions) def print_board(board): for row in board: print(" ".join(row)) print("⠀") print_board(board) print() # AI Battleship Creation Section # def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_rows = [] ship_cols = [] number_of_ships = int(input("Enter how many ships you want: ")) for ship_row in range(number_of_ships): ship_rows.append(random_row(board)) for ship_col in range(number_of_ships): ship_cols.append(random_col(board)) # print(ship_rows) # --> for testing # print(ship_cols) # --> for testing # Gameplay Section # print("⠀") print("-----") print("⠀") print("Try and guess the random placement of the ships done by AI. \n") print("----- \n") for turn in range(dimensions): print("You are currently on turn", turn + 1) print() print("Remember that rows and columns start from 0 in code. \n") guess_row = int(input("Guess Row: ")) guess_col = int(input("Guess Col: ")) print("⠀") if guess_row in ship_rows: matching_coord = ship_rows.index(guess_row) if guess_col in ship_cols and ship_cols.index(guess_col) == matching_coord: if (board[guess_row][guess_col] == "X"): print("You guessed that one already.") print() else: print("Congratulations! You sunk one of my battleships!") board[guess_row][guess_col] = "X" number_of_ships -= 1 print("There are", number_of_ships, "remaining. \n") else: if (guess_row < 0 or guess_row > dimensions - 1) or (guess_col < 0 or guess_col > dimensions - 1): print("Oops, that's not even in the ocean.") print() elif(board[guess_row][guess_col] == "X"): print("You guessed that one already.") print() else: print("You missed my battleship!") board[guess_row][guess_col] = "X" print() print_board(board) print() print("----- \n") if turn == dimensions - 1: print("Game Over. \nYou lost, lol.") print("You had", number_of_ships, "ships remaining.") if number_of_ships == 0: print("Game Over. \nYou won! Good job.") break
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter