珠海中小企业网站建设,怎么知道一个网站是哪家公司做的,在线识别图片百度识图,重庆seo培训今天看到几个关于pygame模块的博客和视频#xff0c;感觉非常有趣#xff0c;这里照猫画虎写了一个贪吃蛇小游戏#xff0c;目前还有待完善#xff0c;但是基本游戏功能已经实现#xff0c;下面是代码#xff1a;# 导入模块import pygameimport random# 初始化pygame.ini…今天看到几个关于pygame模块的博客和视频感觉非常有趣这里照猫画虎写了一个贪吃蛇小游戏目前还有待完善但是基本游戏功能已经实现下面是代码# 导入模块import pygameimport random# 初始化pygame.init()w 720 #窗口宽度h 600 #窗口高度ROW 30 #行数COL 36 #列数#将所有的坐标看作是一个个点定义点类class Point:row 0col 0def __init__(self, row, col):self.row rowself.col coldef copy(self):return Point(row self.row,col self.col)#显示窗口和标题size (w, h)window pygame.display.set_mode(size)pygame.display.set_caption(贪吃蛇)#定义蛇头坐标head Point(row ROW/2, col COL/2)#蛇身体snake_list [Point(row head.row,col head.col1),Point(row head.row,col head.col2),Point(row head.row,col head.col3)]#产生食物def pro_food():#食物不能与蛇重叠while True:pos Point(rowrandom.randint(1,ROW-2), colrandom.randint(1,COL-2))is_coll Falseif head.row pos.row and head.col pos.col:is_coll Truefor snake in snake_list:if snake.col pos.col and snake.row pos.row:is_coll Truebreakif not is_coll:return posfood pro_food()#定义颜色bg_color (255, 255, 255)head_color (0, 128, 128)food_color (255, 255, 0)snake_color (200,200,200)#给定初始方向dire leftdef rect(point, color):cell_width w/COLcell_height h/ROWleft point.col*cell_widthtop point.row*cell_heightpygame.draw.rect(window, color,(left,top,cell_width, cell_height, ))pass# 游戏循环quit Trueclock pygame.time.Clock()while quit:for event in pygame.event.get():#退出方式if event.type pygame.QUIT:quit Falseelif event.type pygame.KEYDOWN:#键盘控制if event.key 273 or event.key 119:if dire left or dire right:dire upelif event.key 274 or event.key 115:if dire left or dire right:dire downelif event.key 276 or event.key 97:if dire up or dire down:dire leftelif event.key 275 or event.key 100:if dire up or dire down:dire right#吃eat(head.row food.row and head.col food.col)if eat:food pro_food()#处理身体#1.原来的头换到身体最前端snake_list.insert(0,head.copy())#2.删除身体最后一个if not eat:snake_list.pop()#移动if dire left:head.col - 1elif dire right:head.col 1elif dire up:head.row - 1elif dire down:head.row 1#检测deadFalse#1.撞墙if head.col 0 or head.row 0 or head.col COL or head.row ROW:deadTrue#2.撞自己for snake in snake_list:if head.col snake.col and head.row snake.row:deadTruebreakif dead:print(dead)quit False#绘制背景pygame.draw.rect(window, bg_color, (0, 0, w, h))#蛇头rect(head, head_color)#食物rect(food,food_color)#蛇身for snake in snake_list:rect(snake,snake_color)pygame.display.flip()#游戏帧数clock.tick(20)效果总结到此这篇关于使用Python第三方库pygame写个贪吃蛇小游戏的文章就介绍到这了,更多相关python 贪吃蛇游戏内容请搜索菜鸟教程www.piaodoo.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持菜鸟教程www.piaodoo.com