Created
May 8, 2023 14:11
-
-
Save ssaurel/de417b5a1921d660f9fc4476515c694d to your computer and use it in GitHub Desktop.
FlippingBitsGame class for a Flipping Bits Game on the SSaurel's Blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FlippingBitsGame: | |
def __init__(self, level): | |
self.level = level # Level = size of the square | |
self.target = [[0] * level for _ in range(level)] # the board to obtain when you play | |
self.board = [[0] * level for _ in range(level)] # the current board played by the user | |
self.solved = True | |
self.newgame() # new game method to define later | |
# method to flip a column | |
def flipcol(self, r): | |
for i in range(len(self.board[r])): | |
self.board[r][i] ^= 1 # 0 -> 1, 1 -> 0 | |
# method to flip a row | |
def fliprow(self, c): | |
for row in self.board: | |
row[c] ^= 1 | |
# method to shuffle the board | |
def shuffle(self): | |
for _ in range(self.level * self.level): | |
if random.random() > 0.5: | |
self.flipcol(random.randint(0, self.level - 1)) | |
else: | |
self.fliprow(random.randint(0, self.level - 1)) | |
# new game | |
def newgame(self): | |
if self.solved: | |
# generate a new game | |
while True: | |
self.shuffle() | |
self.target = deepcopy(self.board) # we make a deep copy of board into the target | |
self.shuffle() # then we shuffle the board | |
if self.issolved() == False: | |
break | |
self.solved = False | |
# is solved method. We check if board == target | |
def issolved(self): | |
for i in range(self.level): | |
for j in range(self.level): | |
if self.board[i][j] != self.target[i][j]: | |
return False | |
self.solved = True | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment