2

In my code, i'm trying to instantiate a simple battleship gameboard for two players. For each player, I am initializing two 5X5 boards and trying to add an "S" to one of the boards to represent a ship. I believe I am only adding the "S" to one of the boards but for some reason, both boards end up updating with the "S" - one should stay blank.

I don't know why this is happening - can anybody help explain?

class Gameboard:
    def __init__(self,  p1_boards = [[],[]], p2_boards = [[],[]], turn = 1):
        self.p1_boards = p1_boards
        self.p2_boards = p2_boards
        self.turn = turn
        i = 0 
        x = randint(0,4)
        y = randint(0,4)

        while i < 5:
            rows = [" "," "," "," "," "]
            self.p1_boards[0].append(rows)
            self.p1_boards[1].append(rows)
            self.p2_boards[0].append(rows)
            self.p2_boards[1].append(rows)
            i += 1
        self.p1_boards[0][randint(0,4)][randint(0,4)] = SHIP
        print(self.p1_boards[0])
        print(self.p1_boards[1])


The two print statements at the end produce:

[[' ', ' ', ' ', 'S', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' ']]

and 

[[' ', ' ', ' ', 'S', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' '],
 [' ', ' ', ' ', ' ', ' ']]
moose_DM
  • 31
  • 2

1 Answers1

0

You append rows to both Boards. If you do

x.append(rows)

You just hand over a reference. So in the end you end up with both p1_boards[0] and p1_boards1 pointing to the same list, similar to a and b in this image:

reference

So when you later change either rows or one value in one of the lists, it is also changed in the other list, because both lists reference on the same list. If you do

x.appends(rows.copy())

Instead the problem should be solved.

See also here

Tanja Bayer
  • 711
  • 5
  • 13