使用 python 的单人AI 扫雷游戏
扫雷是一款单人益智游戏,相信大部分人都在以前上微机课的时候玩过。游戏的目标是借助每个区域中相邻地雷数量的线索,清除包含隐藏的“地雷”或炸弹的单元格,但不引爆其中任何一个,全部清除后即可获胜。今天我们用 Python 完成这个小程序,并且用AI来学习并实现它。
前期准备: 1.确保安装了Python 3.6+。 2.安装Pygame。 3.复制下面代码。 ** **
设置游戏元素
# 颜色 BLACK = (0, 0, 0) GRAY = (180, 180, 180) WHITE = (255, 255, 255) # 创建游戏 pygame.init() size = width, height = 600, 400 screen = pygame.display.set_mode(size) # 字体 OPEN_SANS = r"C:UsersXYSMPycharmProjectspythonProject7Font.ttf" smallFont = pygame.font.Font(OPEN_SANS, 20) mediumFont = pygame.font.Font(OPEN_SANS, 28) largeFont = pygame.font.Font(OPEN_SANS, 40) # 计算面板尺寸 BOARD_PADDING = 20 board_width = ((2 / 3) * width) - (BOARD_PADDING * 2) board_height = height - (BOARD_PADDING * 2) cell_size = int(min(board_width / WIDTH, board_height / HEIGHT)) board_origin = (BOARD_PADDING, BOARD_PADDING) # 添加图片 flag = pygame.image.load(r"C:UsersXYSMPycharmProjectspythonProject7flag.png") flag = pygame.transform.scale(flag, (cell_size, cell_size)) mine = pygame.image.load(r"C:UsersXYSMPycharmProjectspythonProject7mine.png") mine = pygame.transform.scale(mine, (cell_size, cell_size))
字体
字体可以在自己电脑中
C:WindowsFonts
的位置选择自己喜欢的复制到项目中 assets/fonts目录下即可 我这里用的字体展示在下图: 添加图片 这里我们只用了两张图,一个是地雷,一个是用来标记地雷的旗帜
创建游戏和 AI 代理
# 创建游戏和 AI 代理 game = Minesweeper(height=HEIGHT, width=WIDTH, mines=MINES) ai = MinesweeperAI(height=HEIGHT, width=WIDTH) # 跟踪显示的单元格、标记的单元格以及是否被地雷击中 revealed = set() flags = set() lost = False
#设置 AI 移动按钮
# AI 移动按钮 aiButton = pygame.Rect( (2 / 3) * width + BOARD_PADDING, (1 / 3) * height - 50, (width / 3) - BOARD_PADDING * 2, 50 ) buttonText = mediumFont.render("AI Moving", True, BLACK) buttonRect = buttonText.get_rect() buttonRect.center = aiButton.center pygame.draw.rect(screen, WHITE, aiButton) screen.blit(buttonText, buttonRect) # 重置按钮 resetButton = pygame.Rect( (2 / 3) * width + BOARD_PADDING, (1 / 3) * height + 20, (width / 3) - BOARD_PADDING * 2, 50 ) buttonText = mediumFont.render("Replay", True, BLACK) buttonRect = buttonText.get_rect() buttonRect.center = resetButton.center pygame.draw.rect(screen, WHITE, resetButton) screen.blit(buttonText, buttonRect)
全部代码:
学Python的伙伴,欢迎加入新的交流【君羊】:**905229245** 一起探讨编程知识,成为大神,群里还有软件安装包,实战案例、学习资料
上一篇:
IDEA上Java项目控制台中文乱码