基于 python消消乐小游戏
使用一个二维数组表示游戏区域
随机生成初始游戏区
检查并标记要消除的区域,移动元素后重新填充空白
import random
# 随机数生成
def get_random_number():
return random.randint(1, 5)
# 创建二维数组
def create_matrix(rows, columns):
return [[get_random_number() for _ in range(columns)] for _ in range(rows)]
# 找到和给定位置相同且相邻的位置
def find_neighbors(x, y, matrix, value):
max_x = len(matrix[0]) - 1
max_y = len(matrix) - 1
neighbors = []
if x > 0 and matrix[y][x - 1] == value:
neighbors.append((x - 1, y))
if x < max_x and matrix[y][x + 1] == value:
neighbors.append((x + 1, y))
if y > 0 and matrix[y - 1][x] == value:
neighbors.append((x, y - 1))
if y < max_y and matrix[y + 1][x] == value:
neighbors.append((x, y + 1))
return neighbors
# 移除标记的点
def remove_marked(matrix, marked):
for y, row in enumerate(matrix):
for x, value in enumerate(row):
if (x, y) in marked:
matrix[y][x] = 0
# 移动元素到下一行
def shift_down(matrix):
for x in range(len(matrix[0])):
column = [row[x] for row in matrix]
column = [value for value in column if value != 0]
shift = len(matrix) - len(column)
for y, value in enumerate(column):
matrix[y + shift][x] = value
for y in range(shift):
matrix[y][x] = get_random_number()
# 检查是否有相同元素相邻
def has_neighbors(matrix):
for y, row in enumerate(matrix):
for x, value in enumerate(row):
neighbors = find_neighbors(x, y, matrix, value)
if neighbors:
return True
return False
# 主游戏循环
def game_loop(matrix):
while has_neighbors(matrix):
marked_locations = set()
for y, row in enumerate(matrix):
for x, value in enumerate(row):
neighbors = find_neighbors(x, y, matrix, value)
if neighbors:
marked_locations.update(neighbors)
marked_locations.add((x, y))
remove_marked(matrix, marked_locations)
shift_down(matrix)
# 打印游戏区域
def print_matrix(matrix):
for row in matrix:
print(" ".join(str(value) for value in row))
def main():
rows, columns = 10, 10
matrix = create_matrix(rows, columns)
print("Initial board:")
print_matrix(matrix)
game_loop(matrix)
print("Final board:")
print_matrix(matrix)
if __name__ == "__main__":
main()
以上代码定义了一个消消乐游戏,首先生成一个 10x10 的随机游戏区,然后持续消除相邻的元素,直到没有相邻的元素为止。可以通过修改 create_matrix 函数中的参数来改变游戏区域的大小。