简体   繁体   中英

How do I toggle between 1 and 0 within a 5x5 matrix and update the matrix? Lights out logic game

I am currently working on a python3 project that recreates the logic game LightsOut in the terminal. Basically, I have a 5x5 matrix that contains 1's and 0's (1 = light on, 0 = light off). It looks something like this:

[0, 1, 1, 1, 0]
[0, 1, 1, 0, 0]
[0, 1, 0, 1, 0]
[1, 1, 1, 0, 0]
[1, 1, 1, 0, 0]

The game is supposed to work in a way that a user enters a row and column (I'm calling this the index) and all indexes adjacent to the user-entered index toggle from 1 → 0 or from 0 → 1. For example, if the user is playing on the matrix above and selects the index [0][0] the matrix should update to the following:

[1, 0, 1, 1, 0]
[1, 0, 1, 0, 0]
[0, 1, 0, 1, 0]
[1, 1, 1, 0, 0]
[1, 1, 1, 0, 0]

The goal of the game is to toggle all of the lights off (so the matrix is all 0's).

So far I have been able to generate a matrix with random 1's and 0's. I have also figured out how to toggle a specific index by using ^= 1 .

I am unsure how to toggle the adjacent indexes. I think it would be something like matrix[row+1][col] , but I am not sure.

I am also unsure how to update the matrix with the correctly toggled indexes. Maybe using .append(index) ?

I have pasted my code below. This is what I have so far.

import random
from pprint import pprint

ON = 1
OFF = 0
matrix = [[random.choice([1, 0]) for j in range(5)] for i in range(5)]
pprint(matrix)


# This function will toggle 0 and 1 in a specific row and column. But I
# do not know how to toggle adjacent indexes and append it to a new
# matrix.
def toggle(row, col, matrix):
    index = matrix[row][col]
    index ^= 1
    return(index)


print(toggle(0, 0, matrix))

def newmatrix():
    pass

def gameover():
    pass

Add -1, 0 and 1 to each dimension of the user provided coordinates, check that the generated coordinate is on the board, if it is, set it to the opposite of what it is already:

BOARD_SIZE = 5
def toggle(row, col, matrix):
    for x_delta in [-1, 0, 1]:
        for y_delta in [-1, 0, 1]:
            x = row + x_delta
            y = col + y_delta
            if 0 <= y < BOARD_SIZE and 0 <= x < BOARD_SIZE:
                matrix[x][y] = 0 if matrix[x][y] else 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM