Simple Battleships game implementation in Python

2024/10/5 14:50:01

Okay I'm not sure how to develop another board with hidden spaces for the computers ships per-se, and have it test for hits. Again I'm not even sure how I'm going to test for hits on the board I have now. Make note: The player turn function will be migrated to the computer board since you wouldn't be attacking your own ships. Here is the code. It may not be the best formatting (as in with Methods and objects and such) but I can polish it up a little later. Also would there be another way to make placing the ships all in one function? Or with the way I have it, will it have to stay that way?

class battleship(object):def __init__(self):self.board = [["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ]self.printboard()self.placeAircraftCarrier()self.placeBattleShip()self.placeSubmarine()self.placeDestroyer()self.placePatrolBoat()for i in range(100):self.playerTurn()def printboard(self):print "Game Board\n"print "1","2","3","4","5","6","7","8","9","10"for row in self.board:print "|".join(row)
def placeBattleShip(self):while True:self.vOrHPlacement = input("Would you like to place the Battleship (1) Vertically or (2)Horizontally?:")if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:breakelse:print "You must press 1 or 2."while True:self.battleshipRow = input("With the head as the starting place what row would you like to place the Battleship (Takes 4 Spaces)?:")self.battleshipCol = input("What column would you like to start the BattleShip at?:")if self.vOrHPlacement == 1:if self.battleshipRow > 7 or self.battleshipRow <= 0:print "\nIf placing vertically you can only choose 1-7 for the row."elif self.battleshipCol <= 0 or self.battleshipCol > 10:print "You must choose 1 - 10 for a column."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 2self.battleshipCol -= 1for i in range(4):self.board[self.battleshipRow + 1][self.battleshipCol] = "X"self.battleshipRow += 1breakelif self.vOrHPlacement == 2:if self.battleshipCol > 7 or self.battleshipCol <= 0:print "\nIf placing horizontally you can only choose 1-7 for a column."elif self.battleshipRow <= 0 or self.battleshipRow > 10:print "\n You must choose 1 - 10 as a row choice."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 1self.battleshipCol -= 2for i in range(4):self.board[self.battleshipRow][self.battleshipCol + 1] = "X"self.battleshipCol += 1breakself.printboard()
def placeAircraftCarrier(self):while True:self.vOrHPlacement = input("Would you like to place the Aircraft Carrier (1) Vertically or (2)Horizontally?:")if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:breakelse:print "You must press 1 or 2."while True:self.battleshipRow = input("With the head as the starting place what row would you like to place the Aircraft Carrier (Takes 5 Spaces)?:")self.battleshipCol = input("What column would you like to start the Aircraft Carrier at?:")if self.vOrHPlacement == 1:if self.battleshipRow > 6 or self.battleshipRow <= 0:print "\nIf placing vertically you can only choose 1-6 for the row."elif self.battleshipCol <= 0 or self.battleshipCol > 10:print "You must choose 1 - 10 for a column."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 2self.battleshipCol -= 1for i in range(5):self.board[self.battleshipRow + 1][self.battleshipCol] = "X"self.battleshipRow += 1breakelif self.vOrHPlacement == 2:if self.battleshipCol > 6 or self.battleshipCol <= 0:print "\nIf placing horizontally you can only choose 1-6 for a column."elif self.battleshipRow <= 0 or self.battleshipRow > 10:print "\n You must choose 1 - 10 as a row choice."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 1self.battleshipCol -= 2for i in range(5):self.board[self.battleshipRow][self.battleshipCol + 1] = "X"self.battleshipCol += 1breakself.printboard()
def placeSubmarine(self):while True:self.vOrHPlacement = input("Would you like to place the Submarine (1) Vertically or (2)Horizontally?:")if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:breakelse:print "You must press 1 or 2."while True:self.battleshipRow = input("With the head as the starting place what row would you like to place the Submarine (Takes 3 Spaces)?:")self.battleshipCol = input("What column would you like to start the Submarine at?:")if self.vOrHPlacement == 1:if self.battleshipRow > 8 or self.battleshipRow <= 0:print "\nIf placing vertically you can only choose 1-8 for the row."elif self.battleshipCol <= 0 or self.battleshipCol > 10:print "You must choose 1 - 10 for a column."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 2self.battleshipCol -= 1for i in range(3):self.board[self.battleshipRow + 1][self.battleshipCol] = "X"self.battleshipRow += 1breakelif self.vOrHPlacement == 2:if self.battleshipCol > 8 or self.battleshipCol <= 0:print "\nIf placing horizontally you can only choose 1-8 for a column."elif self.battleshipRow <= 0 or self.battleshipRow > 10:print "\n You must choose 1 - 10 as a row choice."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 1self.battleshipCol -= 2for i in range(3):self.board[self.battleshipRow][self.battleshipCol + 1] = "X"self.battleshipCol += 1breakself.printboard()
def placeDestroyer(self):while True:self.vOrHPlacement = input("Would you like to place the Destroyer (1) Vertically or (2)Horizontally?:")if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:breakelse:print "You must press 1 or 2."while True:self.battleshipRow = input("With the head as the starting place what row would you like to place the Destroyer (Takes 3 Spaces)?:")self.battleshipCol = input("What column would you like to start the Destroyer at?:")if self.vOrHPlacement == 1:if self.battleshipRow > 8 or self.battleshipRow <= 0:print "\nIf placing vertically you can only choose 1-8 for the row."elif self.battleshipCol <= 0 or self.battleshipCol > 10:print "You must choose 1 - 10 for a column."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 2self.battleshipCol -= 1for i in range(3):self.board[self.battleshipRow + 1][self.battleshipCol] = "X"self.battleshipRow += 1breakelif self.vOrHPlacement == 2:if self.battleshipCol > 8 or self.battleshipCol <= 0:print "\nIf placing horizontally you can only choose 1-8 for a column."elif self.battleshipRow <= 0 or self.battleshipRow > 10:print "\n You must choose 1 - 10 as a row choice."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 1self.battleshipCol -= 2for i in range(3):self.board[self.battleshipRow][self.battleshipCol + 1] = "X"self.battleshipCol += 1breakself.printboard()
def placePatrolBoat(self):while True:self.vOrHPlacement = input("Would you like to place the Patrol Boat (1) Vertically or (2)Horizontally?:")if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:breakelse:print "You must press 1 or 2."while True:self.battleshipRow = input("With the head as the starting place what row would you like to place the Patrol Boat (Takes 2 Spaces)?:")self.battleshipCol = input("What column would you like to start the Patrol Boat at?:")if self.vOrHPlacement == 1:if self.battleshipRow > 9 or self.battleshipRow <= 0:print "\nIf placing vertically you can only choose 1-9 for the row."elif self.battleshipCol <= 0 or self.battleshipCol > 10:print "You must choose 1 - 10 for a column."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 2self.battleshipCol -= 1for i in range(2):self.board[self.battleshipRow + 1][self.battleshipCol] = "X"self.battleshipRow += 1breakelif self.vOrHPlacement == 2:if self.battleshipCol > 9 or self.battleshipCol <= 0:print "\nIf placing horizontally you can only choose 1-9 for a column."elif self.battleshipRow <= 0 or self.battleshipRow > 10:print "\n You must choose 1 - 10 as a row choice."elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":print "There is already a ship there."else:self.battleshipRow -= 1self.battleshipCol -= 2for i in range(2):self.board[self.battleshipRow][self.battleshipCol + 1] = "X"self.battleshipCol += 1breakself.printboard()
def playerTurn(self):while True:self.row = input("What row coordinate would you like to hit?:")self.column = input("What column coordinate would you like to hit?")if self.row > 10 or self.row < 0:print "You must pick a row coordinate between 1 and 10."elif self.column > 10 or self.column < 0:print "You must pick a column coordinate between 1 and 10."elif self.board[self.row - 1][self.column - 1] == "*":print "You have already hit there."else:self.board[self.row - 1][self.column - 1] = "*"breakself.printboard()b = battleship()
Answer

You need a lot of code organisation. I would suggest keeping Classes free from any sort of looping or inputs! Input stuff from the user & then add that to the class instance, not the other way round. Organize your code & add documentation to it so that others can help you.

You can do some stuff like this

class BattleShip:""" Ship object container"""def __init__(self, position_x, position_y, size):""" Necessary variables for the ship go here """self.position_x = position_xself.position_y = position_yself.size = sizedef contains(self, position_x, position_y):""" Returns true if supplied point lies inside this ship """# codedef destroy(self, position_x, position_y):""" Destroys the ship's point supplied if it contains it """assert self.contains(position_x, position_y)# Now update the gameboard# codedef isCompletelyDestroyed(self):""" Returns True if ship is completely destoryed else False """# codeclass GameBoard:""" The container for the ships """def __init__(self, size):"""Initialize clean GameBoard depending on size, etc """self.occupied = "+" # representation for shipsself.destroyed = 'x' # representation for destroyed areaself.clear = '-' # representation for clear waterdef printBoard(self):""" Print the current gameboard state """def update(self, ship):""" Updates the gameboard according to updated ship """# Now do the mainloop
while game_not_over:# run game
https://en.xdnf.cn/q/119667.html

Related Q&A

How to remove WindowsPath and parantheses from a string [duplicate]

This question already has an answer here:Reference - What does this regex mean?(1 answer)Closed 4 years ago.I need to remove WindowsPath( and some of the closing parentheses ) from a directory string.…

How to escape escape-characters

I have a string variable which is not printing properly, I guess because it contains escape characters. How to escape these escape-characters?>>> print "[p{Aa}\\P{InBasic_Latin}\r\t\n]&q…

Python Multiprocessing a large dataframe on Linux

As shown in the title, I have a big data frame (df) that needs to be processed row-wise, as df is big (6 GB), I want to utilize the multiprocessing package of python to speed it up, below is a toy exam…

How to pass more arguments through tkinter bind

How do I pass more arguments through tkinters bind method? for the example:tk = Tk() def moveShip(event,key):if event.keysym == Down and player1.selectedCoord[1] != 9:if key == place:player1.selectedC…

Python Class method definition : unexpected indent [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 6 months ago.I am getting started with Django and Python so naturally Im doing …

pandas python - round() not behaving correctly

Im rounding values in a dataframe to 1 decimal place. Here is the dfVren 2015 Hsten 2014 Vren 2014 Question 1) Maten r vllagad oc…

Converting dictionary into string

d={a:Apple,b:ball,c:cat}The above dictionary I have and I want my Output like the below-mentioned resultres="a=Apple,b=ball,c=cat"Is it possible in a pythonic way then please answer it I have…

Django Getting QuerySet.values() based on condition

Lets say I have a model Class Parent and a Class Child. And child has a field called status and a ForeignKey relationship to Parent.Lets say I retrieve one parent by calling filter (so as to have a Que…

Condition checking in python with user input [duplicate]

This question already has answers here:If...else statement issue with raw_input on Python(2 answers)Closed 8 years ago.I tried taking an input from keyboard. the checking that input with an if else sta…

Triangle of T in Python

EDIT ** I cant multiply strings by an integer. Its for a homework and those were the instructions **I need to do a triangle in python using for loops or while loops(mandatory). The final output should …