背景
通过python的pygame模块可以快速的构建2D游戏。以下为学习这个模块的时候写的一个demo,其中的部分功能逻辑实现上比较简单,未考虑复杂情况,尽请包涵。
源码案例(demo)
1. 运行前需要先修改下图片资源路径和名称。
2. 计时器功能未实现
3. 消除逻辑未完善:只能消除连续的两个。
import sys
import pygame
import random
# 初始化游戏界面和数据
# 生成游戏棋盘
# 判断两个图案是否可以消除
# 计时器功能
# 游戏结束判断
class GameObject:
def __init__(self, game_name, row_num, coloum_num, width, height):
pygame.init()
# 行数
self.row_num = row_num
# 列数
self.coloum_num = coloum_num
# 每个单元格的宽度、高度
self.height = height
self.width = width
# 初始化窗口大小
self.screen = pygame.display.set_mode((self.row_num * self.height, self.coloum_num * self.width))
pygame.display.set_caption(game_name)
# 游戏棋盘
self.game_map = None
# 加载图片资源,并重新绘制游戏地图
def init_image(self, image_dir, image_num):
# 定义图片资源路径
# image_dir = "./static/image/animal/"
# 加载图片资源
image_list = []
for i in range(1, image_num + 1):
image_file = image_dir + "re_image_" + str(i) + ".png"
image_list.append(pygame.image.load(image_file))
# 生成游戏棋盘
self.game_map = [[random.choice(image_list) for _ in range(self.row_num)] for _ in range(self.coloum_num)]
def draw_map(self):
self.screen.fill((255, 255, 255))
# 绘制游戏地图
for i in range(self.coloum_num):
for j in range(self.row_num):
if self.game_map[i][j] is not None:
self.screen.blit(self.game_map[i][j], (i * self.width, j * self.height))
# 更新屏幕
pygame.display.flip()
def listen_event_and_action(self):
global start_x
global start_y
global end_x
global end_y
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
x, y = event.pos
index_x = x // self.width
index_y = y // self.height
print(f"x,y:{x},{y};index_x,_y:{index_x},{index_y}")
if start_x is not None and start_y is not None:
# print("给第2个坐标赋值")
end_x = index_x
end_y = index_y
if self.can_eliminate(start_x, start_y, end_x, end_y):
print(f"可以消除,start:{start_x},{start_y},end:{end_x},{end_y}")
self.game_map[start_x][start_y] = None
self.game_map[end_x][end_y] = None
start_x = start_y = end_x = end_y = None
else:
start_x = start_y = end_x = end_y = None
else:
# print("给第一个初始坐标赋值")
start_x = index_x
start_y = index_y
print(f"start_x,start_y:{start_x},{start_y};end_x,end_y:{end_x},{end_y}")
# 判断是否可以消除
def can_eliminate(self, x1, y1, x2, y2):
print(f"x1,y1,x2,y2:{x1},{y1},{x2},{y2}")
type1 = self.game_map[x1][y1]
type2 = self.game_map[x2][y2]
if type1 != type2:
return False
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dx, dy in directions:
x, y = x1 + dx, y1 + dy
print(f"x,y:{x},{y}")
if 0 <= x < len(self.game_map) and 0 <= y < len(self.game_map) and self.game_map[x][y] == type1:
print("true")
return True
print("false")
return False
if __name__ == "__main__":
# 定义运行flag
running = True
image_dir = "./static/image/animal/"
gm = GameObject("连连看", 6, 6, 80, 80)
gm.init_image(image_dir, 9)
start_x = start_y = end_x = end_y = None
while running:
gm.draw_map()
gm.listen_event_and_action()