利用python画图的步骤(python小游戏代码)
admin
2023-09-14 17:27:32
0

前言:

本期我们将制作一个拼图小游戏。让我们愉快地开始吧~~~

先来看看效果是这样子的:

开发工具

**Python版本:**3.6.4

私信小编01即可获取大量python学习资源

相关模块:

pygame模块;

以及一些Python自带的模块

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

原理介绍

游戏简介:

将图像分为m×n个矩形块,并将图像右下角的矩形块替换为空白块后,将这些矩形块随机摆放成原图像的形状。游戏目标为通过移动非空白块将随机摆放获得的图像恢复成原图像的模样,且规定移动操作仅存在于非空白块移动到空白块。

例如下图所示:

逐步实现:

Step1:游戏初始界面

既然是游戏,总得有个初始界面吧?

OK,我们先写一个游戏初始界面:

'''显示游戏开始界面'''def ShowStartInterface(screen, width, height):screen.fill(cfg.BACKGROUNDCOLOR)tfont = pygame.font.Font(cfg.FONTPATH, width//4)cfont = pygame.font.Font(cfg.FONTPATH, width//20)title = tfont.render('拼图游戏', True, cfg.RED)content1 = cfont.render('按H或M或L键开始游戏', True, cfg.BLUE)content2 = cfont.render('H为5*5模式, M为4*4模式, L为3*3模式', True, cfg.BLUE)trect = title.get_rect()trect.midtop = (width/2, height/10)crect1 = content1.get_rect()crect1.midtop = (width/2, height/2.2)crect2 = content2.get_rect()crect2.midtop = (width/2, height/1.8)screen.blit(title, trect)screen.blit(content1, crect1)screen.blit(content2, crect2)while True:for event in pygame.event.get():if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):pygame.quit()sys.exit()elif event.type == pygame.KEYDOWN:if event.key == ord('l'): return 3elif event.key == ord('m'): return 4elif event.key == ord('h'): return 5pygame.display.update()复制代码

根据玩家自身水平,可以选择不同难度的拼图游戏。

Step2:定义移动操作

定义移动操作的目的是为了移动拼图(好像是废话T_T),具体实现起来十分简单:

'''将空白Cell左边的Cell右移到空白Cell位置'''def moveR(board, blank_cell_idx, num_cols):if blank_cell_idx % num_cols == 0: return blank_cell_idxboard[blank_cell_idx-1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx-1]return blank_cell_idx - 1'''将空白Cell右边的Cell左移到空白Cell位置'''def moveL(board, blank_cell_idx, num_cols):if (blank_cell_idx+1) % num_cols == 0: return blank_cell_idxboard[blank_cell_idx+1], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx+1]return blank_cell_idx + 1'''将空白Cell上边的Cell下移到空白Cell位置'''def moveD(board, blank_cell_idx, num_cols):if blank_cell_idx < num_cols: return blank_cell_idxboard[blank_cell_idx-num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx-num_cols]return blank_cell_idx - num_cols'''将空白Cell下边的Cell上移到空白Cell位置'''def moveU(board, blank_cell_idx, num_rows, num_cols):if blank_cell_idx >= (num_rows-1) * num_cols: return blank_cell_idxboard[blank_cell_idx+num_cols], board[blank_cell_idx] = board[blank_cell_idx], board[blank_cell_idx+num_cols]return blank_cell_idx + num_cols复制代码

Step3:游戏主界面

OK,有了前面的铺垫,我们可以开始实现我们的游戏主界面了。

首先,我们需要打乱拼图, 但是随机打乱很可能导致拼图无解,因此我们通过随机移动拼图来实现打乱拼图的效果 ,这也是我们先定义拼图的移动操作的主要原因:

'''获得打乱的拼图'''def CreateBoard(num_rows, num_cols, num_cells):board = []for i in range(num_cells): board.append(i)# 去掉右下角那块blank_cell_idx = num_cells - 1board[blank_cell_idx] = -1for i in range(cfg.NUMRANDOM):# 0: left, 1: right, 2: up, 3: downdirection = random.randint(0, 3)if direction == 0: blank_cell_idx = moveL(board, blank_cell_idx, num_cols)elif direction == 1: blank_cell_idx = moveR(board, blank_cell_idx, num_cols)elif direction == 2: blank_cell_idx = moveU(board, blank_cell_idx, num_rows, num_cols)elif direction == 3: blank_cell_idx = moveD(board, blank_cell_idx, num_cols)return board, blank_cell_idx复制代码

游戏主界面初始化:

最后实现主界面的显示刷新以及事件响应等功能:

while True:game_board, blank_cell_idx = CreateBoard(num_rows, num_cols, num_cells)if not isGameOver(game_board, size):break# 游戏主循环is_running = Truewhile is_running:# --事件捕获for event in pygame.event.get():# ----退出游戏if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):pygame.quit()sys.exit()# ----键盘操作elif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT or event.key == ord('a'):blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols)elif event.key == pygame.K_RIGHT or event.key == ord('d'):blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols)elif event.key == pygame.K_UP or event.key == ord('w'):blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols)elif event.key == pygame.K_DOWN or event.key == ord('s'):blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols)# ----鼠标操作elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:x, y = pygame.mouse.get_pos()x_pos = x // cell_widthy_pos = y // cell_heightidx = x_pos + y_pos * num_colsif idx == blank_cell_idx-1:blank_cell_idx = moveR(game_board, blank_cell_idx, num_cols)elif idx == blank_cell_idx+1:blank_cell_idx = moveL(game_board, blank_cell_idx, num_cols)elif idx == blank_cell_idx+num_cols:blank_cell_idx = moveU(game_board, blank_cell_idx, num_rows, num_cols)elif idx == blank_cell_idx-num_cols:blank_cell_idx = moveD(game_board, blank_cell_idx, num_cols)# --判断游戏是否结束if isGameOver(game_board, size):game_board[blank_cell_idx] = num_cells - 1is_running = False# --更新屏幕screen.fill(cfg.BACKGROUNDCOLOR)for i in range(num_cells):if game_board[i] == -1:continuex_pos = i // num_colsy_pos = i % num_colsrect = pygame.Rect(y_pos*cell_width, x_pos*cell_height, cell_width, cell_height)img_area = pygame.Rect((game_board[i]%num_cols)*cell_width, (game_board[i]//num_cols)*cell_height, cell_width, cell_height)screen.blit(game_img_used, rect, img_area)for i in range(num_cols+1):pygame.draw.line(screen, cfg.BLACK, (i*cell_width, 0), (i*cell_width, game_img_used_rect.height))for i in range(num_rows+1):pygame.draw.line(screen, cfg.BLACK, (0, i*cell_height), (game_img_used_rect.width, i*cell_height))pygame.display.update()clock.tick(cfg.FPS)复制代码

Step4:游戏结束界面

当玩家完成拼图后,需要显示游戏结束界面,和游戏初始界面类似,实现起来都比较简单:

'''显示游戏结束界面'''def ShowEndInterface(screen, width, height):screen.fill(cfg.BACKGROUNDCOLOR)font = pygame.font.Font(cfg.FONTPATH, width//15)title = font.render('恭喜! 你成功完成了拼图!', True, (233, 150, 122))rect = title.get_rect()rect.midtop = (width/2, height/2.5)screen.blit(title, rect)pygame.display.update()while True:for event in pygame.event.get():if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):pygame.quit()sys.exit()pygame.display.update()复制代码

文章到这里就结束了,感谢你的观看

以上就是python小游戏代码(利用python画图的步骤)的相关内容了,更多精彩内容请关注!

相关内容

热门资讯

中央网信办从严处置一批违规网络... 近期,中央网信办深入推进“清朗·网络娱乐团播乱象整治”专项行动,针对团播违规PK刺激打赏、不当玩法诱...
酷暑如何运动不伤身?养阳、择时... 运动有度:宜舒缓顺势而行夏季,人体阳气浮于体表,腑脏阳气相对亏虚,此时进行马拉松等高强度的剧烈运动,...
解放军报钧声:中方维护黄岩岛主... 7月31日,中国外交部就菲律宾在中国领土黄岩岛划设所谓“领海基线”发布声明。8月1日,中国人民解放军...
查实作弊!河南通报“三支一扶”... 针对近期备受关注的2026年河南省“三支一扶”计划招募相关舆情,河南省“三支一扶”领导小组协调办公室...
美军称对伊朗海上封锁仍在继续 美军中央司令部2日在社交媒体上表示,美国对伊朗的海上封锁仍在继续。截至8月2日,美军已迫使35艘船只...
最高法发布5起典型案例 规范平... 今天(8月3日),最高人民法院发布5起依法规范平台经营、保护消费者合法权益典型案例。平台经济是数字经...
震感明显!四川宜宾高县发生4.... 据中国地震台网正式测定,2026年8月3日2时21分,在四川宜宾市高县(北纬28.54度,东经104...
局地特大暴雨!中央气象台发布暴... 中央气象台8月3日6时发布暴雨橙色预警和强对流天气蓝色预警。暴雨橙色预警预计,8月3日8时至4日8时...
美国波特兰发生枪击事件 致1死... 央视记者获悉,当地时间8月2日凌晨,美国俄勒冈州波特兰一处住宅发生大规模枪击事件,造成包括一名青少年...
广西灵山县一公司在建楼发生火灾... 2026年8月2日12时许,广西钦州灵山县十里工业园区园园丰食品有限公司一在建楼发生火灾,接报后,灵...
西南、华南等地有强降水 国家防... 8月2日上午,国家防总办公室、应急管理部组织中国气象局、水利部、自然资源部、工业和信息化部、住房城乡...
“欧佩克+”主要产油国宣布9月... 当地时间8月2日,石油输出国组织(欧佩克)发布声明称,沙特阿拉伯、俄罗斯、伊拉克、科威特、哈萨克斯坦...
国家外汇局:将继续稳步扩大外汇... 记者8月2日从国家外汇管理局获悉,今年下半年,外汇管理部门将继续稳步扩大外汇领域制度型开放。国家外汇...
解放军报钧声:中方加强黄岩岛管... 近期,菲律宾在中国领土黄岩岛划设所谓“领海基线”,妄图为2016年那场非法仲裁“续命”,并掀起新一轮...
驻日美军多名士兵涉嫌酒驾和猥亵... 日本冲绳县近日发生多起驻日美军士兵被捕案件,其中两人涉嫌酒驾,一人涉嫌公然猥亵。据冲绳县警方通报,2...
伊朗称重开霍尔木兹海峡计划纯属... 据伊朗方面2日消息,有消息人士称,重开霍尔木兹海峡的计划纯属谣言。一名相关消息人士说,目前尚未就重开...
中东部高温闷热持续 热带低压或... 今天,本轮中东部高温闷热天气持续,多地继续“全天桑拿”模式,动不动就大汗淋漓,户外仿佛大蒸笼,走出空...
看完《八仙!》,来这里“沉浸式... 最近,动画电影《八仙!》热映影片中青绿山水间的蓬莱仙境让无数观众心驰神往而真实的蓬莱比电影里还要“仙...
水利部针对重庆市启动洪水防御Ⅳ... 据预报,8月2日至4日,重庆将有中到大雨,其中重庆中部和东南部将有暴雨,局部将有大暴雨;长江上游干流...
巴基斯坦雪崩致1名中国公民失联... 7月30日,一支国际登山队在喀喇昆仑山脉布洛阿特峰遭遇雪崩后失联。8月1日,中国驻巴基斯坦大使馆领侨...