Swolerosis
Swolerosis

Reputation: 93

Creating a matching game in Python

I'm trying to create a class for a matching game in a 5x5 grid. The user will pick the ranges, based on row and column number. I've spent the last couple hours trying to figure out how to set this up, and I'm thinking it should either be a set or a list of tuples with the x,y coordinates. I can get the list of coordinates generated in a set, by doing:

board = set((x,y)
        for x in range(5)
        for y in range(5))

I can't figure out how to actually turn this into a workable board though. I am trying to create a "real board" with the matched values, and a "show" board that just has X's until the user gets the match, and then the real values will be shown on their board.

So ideally, there should be one board that looks like

X X X X X
X X X X X
X X X X X
X X X X X
X X X X X

and another with random pairs:

A M F H I
C D B J E
G I F A C
D J G H L
K E L B M

Upvotes: 0

Views: 3991

Answers (2)

Christian Tapia
Christian Tapia

Reputation: 34146

I'd do it with a list of lists:

board = []

def initializeBoard(board):
    for i in range(5):
        board.append([])
    for l in board:
        for i in range(5):
            l.append('X')

def printBoard(board):
    for l in board:
        for e in l:
            print e,
        print 


initializeBoard(board)
board[0][1] = 'A' # To access an element        
printBoard(board)

>>> 
X A X X X
X X X X X
X X X X X
X X X X X
X X X X X

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122376

Perhaps a better way to represent the board is to use a dictionary:

board = {}
for x in range(5):
    for y in range(5):
        board[x, y] = 'X'

You can update a character by doing: board[3, 4] = 'D'.

You can even specify the board using a dictionary comprehension:

board = {(x, y): 'X' for x in range(5) for y in range(5)}

Upvotes: 1

Related Questions