patternpythonMinor
Designing a simple Battleship game in Python
Viewed 0 times
simpledesigninggamepythonbattleship
Problem
I am trying to code Battleship. It should be a text one-player game against computer where computer and human player take turns in shooting at opponent's ships. I decided to start implementation with this part: A human types target coordinates and computer answers if a ship has been hit or even if it has been sunk. Ship positions are fixed (predefined in the program). For some time I wondered how to represent game plan and ships to get this working as smoothly as possible. This is what I have put together:
EDIT:
There are a few things I a
class GamePlan:
DIMX = 10
DIMY = 10
SHIP_MISS = 0
SHIP_HIT = 1
SHIP_DEAD = 2
SHIP_COUNTS = {
2: 1,
3: 1,
}
def __init__(self):
self.ships = [
[(1,1), (1,2)],
[(5,6), (5,7), (5,8)],
]
def hit(self, target):
hit_ship = None
hit_ship_index = None
for i, ship in enumerate(self.ships):
if target in ship:
ship.pop(ship.index(target))
hit_ship = ship
hit_ship_index = i
if hit_ship == []:
self.ships.pop(hit_ship_index)
return self.SHIP_DEAD
if hit_ship:
return self.SHIP_HIT
return self.SHIP_MISS
def main():
game_plan = GamePlan()
while True:
raw_coords = raw_input('Enter coords: ')
str_coords = raw_coords.split()
coords = tuple([int(c) for c in str_coords])
if len(coords) != 2:
print 'Bad input'
continue
result = game_plan.hit(coords)
if result == GamePlan.SHIP_DEAD:
print 'Ship dead'
if result == GamePlan.SHIP_HIT:
print 'Ship hit'
if result == GamePlan.SHIP_MISS:
print 'Missed'
if __name__ == "__main__":
main()EDIT:
GamePlan should be probably called Board as answer of Janne Karila suggests. Just to clarify what I meant by that name with my flawed English.There are a few things I a
Solution
Perhaps
1,3,4: The ships are static, they just occupy some space on the board. However, a ship object would be aware which squares belong to the ship, and perhaps should be responsible to determine if it has been sunk.
2:
5: If the player hits the same coordinates twice, you'll report a miss, which is wrong.
GamePlan would better be named eg. Board? English is not my mother tongue, but AFAIK game plan == strategy.1,3,4: The ships are static, they just occupy some space on the board. However, a ship object would be aware which squares belong to the ship, and perhaps should be responsible to determine if it has been sunk.
2:
hit is perfect; in OOP the object is often the object also in grammatical sense. Think of file.close().5: If the player hits the same coordinates twice, you'll report a miss, which is wrong.
Context
StackExchange Code Review Q#25541, answer score: 2
Revisions (0)
No revisions yet.