Home > database >  How to create a python game board using 2d array?
How to create a python game board using 2d array?

Time:12-26

I am very new to Python but I am trying to create a text based game board for dots and boxes. I am not too sure where to start with the code yet but my idea is to get a desired output of a 3X4 board like this:

(1,1) (1,2) (1,3) (1,4)

(2,1) (2,2) (2,3) (2,4)

(3,1) (3,2) (3,3) (3,4)

The player input I am planning for later is, for example with input of (1,3)(2,3) it would draw a line between the two and so on.

(1,1) (1,2) (1,3) (1,4)
                    |
(2,1) (2,2) (2,3) (2,4)

(3,1) (3,2) (3,3) (3,4)

Can anyone help me with understanding how to draw the board? I am new to python data types and data structures but reading up on it makes me think I need to be creating a 2d array. Any help is greatly appreciated, thanks!

CodePudding user response:

There are lots of options depending on exactly what state you need to store. One way is to store the links between cells as tuples in a set, and check for these when drawing the board.

width = 4
height = 3
links = set()

def draw_board():
    for row in range(1, height 1):
        for col in range(1, width 1):
            if ((row, col), (row, col 1)) in links:
                sep = "-"
            else:
                sep = " "
            print((f"({row},{col}) {sep} "), end="")
        print()
        for col in range(1, width 1):
            if ((row, col), (row 1, col)) in links:
                print("  |     ", end="")
            else:
                print("        ", end="")
        print()

draw_board()
# add some links to test
links.add(((1,2),(1,3))) 
links.add(((2,2),(3,2)))
links.add(((2,4),(3,4)))
draw_board()

CodePudding user response:

Actually you don't need to specify two input one is enough .Here is the code that allow you to draw the board :

myBorad = [[str((i,j)) for j in range(1,5)] for i in range(1,4)]
for i in range(1,4,2):
    myBorad.insert(i,["    " for j in range(4)])

a,b = [int(i) for i in input().split(" ")]

myBorad[a][b]=" |"

for i in myBorad:
    print(" ".join(i))

Input:

1 3

Output :

(1, 1) (1, 2) (1, 3) (1, 4)
                |
(2, 1) (2, 2) (2, 3) (2, 4)

(3, 1) (3, 2) (3, 3) (3, 4)

Note : In order to make it more active you could add a loop that ask for the input and each time you print out the board because all the previous result are already saved in the list myBord

  • Related