Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Battleship game in python
#1
Hello, I'm kinda new to python and programming in general, but I would like to code the battleship game.
But I'm currently struggling at implementing larger battleships than a battleship with the width of 1. And deleting the random part to make it work for 2 players.
And I'm not sure if my "You guessed than one already works" , I think not.

Thanks.

#!/usr/bin/python3 
# -*- coding : utf-8 -*-


#MIT License

# Copyright (c) [2016] [Colpyin]

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


from random import randint #To create an imaginary opponent when you have no friends.
import os #To have a nice and clean interface for the game.

board = []

rules = str(input("Do you know how to play ?" "(" + '\x1b[1;31;1m' + 'n' + '\x1b[0m' + "/" + '\x1b[1;32;1m' + 'y' + '\x1b[0m' + ")"))

for x in range(5):
    board.append(["O"] * 5) #Creates the 5x5 matrix.

def print_board(board):
    os.system('clear') #Clear the screen each turn of the game
    print("Let's play some Battleships ! :D")
    if rules == "n":
        print()
        print("How to play : Each turn you can guess an unique position for the ship. You need to sunk the ship before you reach the maximum number of turns authorized.")
        print()
    print("Good Luck & Have Fun :P")
    print("Version -2.0")
    print()
    print("Display of Quality.")
    print("  0|1|2|3|4")
    for row in range(len(board)): 
        print(str(row) + "|" + "|".join(board[row])) #To have a nice matrix display without "[" , "]" and "," 
    print()
print_board(board) #Initializes the board

def random_row(board):
    return(randint(0, len(board) - 1)) #Generates a random number between 0 and 4 for the rows.

def random_col(board): 
    return(randint(0, len(board[0]) - 1)) #Generates a random number between 0 and 4 for the collumns.

#Assigning the generated random numbers to ship_row and ship_col who are respectively the [j] and [i] coordinates.
# of the ship 
ship_row = random_row(board) 
ship_col = random_col(board)

p1 = str(input("Enter your nickname : "))
# n = int(input("Enter the desired number of turns : "))

for turn in range(6): #For loop with the desired number of turns.
    print("Turn", turn) #Displays the actual turn number.

    guess_col = int(input("Guess Col:")) #Lets the player guess the [i] coordinate of the ship.
    guess_row = int(input("Guess Row:")) #Lets the player guess the [j] coordinate of the ship.
   
    if guess_row == ship_row and guess_col == ship_col: #Tests if guess of the player is right and if he won.
        print()
        print('\x1b[1;32;1m' + 'Congratulations' + '\x1b[0m' +" "+ p1 + ", " + 'you sunk my battleship!')
        break #Preventing the game to continue running.
    else:
        if ((guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)): #Doesn't allow coordinates greater
                                                                                   # than 4 and lower than 0.
            print()
            print("Oops, that's not even in the ocean.")
        elif(board[guess_row][guess_col] == "•"): #Tests if the player already played on those coordinates.
            print()
            print("You guessed that one already.")
        else:
            board[guess_row][guess_col] = "•" 
            print()
            print("You missed my battleship !") 
            if turn == 5: #Equivalent to the number of turns. If the ship isn't hit it's a Game-Over.
                print('\x1b[1;31;1m' + 'Game' + '\x1b[0m' + " " + '\x1b[1;31;1m' + 'Over.' + '\x1b[0m')
                print()
                break
        print_board(board)
Reply
#2
One way you could implement multiple ships is create a second board. On that board, mark where the computer's ships are. Then when the user moves, check that move against the board with the computer's ships to see if there's a hit. Then you can record on the printable (public) board whether it was a hit or a miss. The trick here is how to check that a multi-square ship has been sunk, so you can notify the user.

Another way you could do is to have a list for each ship recording the squares that have not been hit (as a tuple). When a square is hit, you can mark that on the board and remove that cell from the ship's list. Then when the list is empty, you know the ship has been sunk. You could even do this as a list of lists (ships).
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020