1、python贪吃蛇程序设计报告_20192411Python程序设计实验四报告实验代码#pygame游戏库,sys操控python运的环境import pygame,sys,randomfrom pygame.locals import*#1,定义颜变量,0-255 0 255redColor=pygame.Color(255,0,0)#背景为blackColor=pygame.Color(0,0,0)#贪吃蛇为whiteColor=pygame.Color(255,255,255)#定义游戏结束的函数def gameover():pygame.quit()sys.exit()#定义main函
2、数:定义我们的函数def main():#初始化pygamepygame.init()fpsClock=pygame.time.Clock()#创建pygame显层,创建个界playsurface=pygame.display.set_mode(640,480)pygame.display.set_caption(贪吃蛇)snakePosition=100,100#贪吃蛇初始坐标位置snakeBody=100,100,80,100,60,100#初始化贪吃蛇的长度列表中有个元素就代表有段体targetPosition=300,300#初始化标向和位置#判断是否吃掉了这个标块1 就是没有吃 0就
3、是吃掉targetflag=1direction=right#初始化向(向右)changeDirection=directionwhile True:for event in pygame.event.get():#从队列中获取事件if event.type=QUIT:pygame.quit()sys.exit()elif event.type=KEYDOWN:if event.key=K_d:changeDirection=rightif event.key=K_a:changeDirection=leftif event.key=K_w:changeDirection=upif event
4、key=K_s:changeDirection=down#对应键盘上的esc件if event.key=K_ESCAPE:pygame.event.post(pygame.event.Event(QUIT)#确定向if changeDirection=left and not direction=right:direction=changeDirectionif changeDirection=right and not direction=left:direction=changeDirectionif changeDirection=up and not direction=down:d
5、irection=changeDirectionif changeDirection=down and not direction=up:direction=changeDirection#根据向移动蛇头if direction=right:snakePosition0+=20if direction=left:snakePosition0-=20if direction=up:snakePosition1-=20if direction=down:snakePosition1+=20#增加蛇的长度snakeBody.insert(0,list(snakePosition)#如果贪吃蛇和标块的
6、位置重合if snakePosition0=targetPosition0 and snakePosition1=targetPosition1:targetflag=0else:snakeBody.pop()if targetflag=0:x=random.randrange(1,32)y=random.randrange(1,24)targetPosition=int(x*20),int(y*20)targetflag=1#填充背景颜playsurface.fill(blackColor)for position in snakeBody:#第个参数serface指定个serface编辑区
7、在这个区域内绘制。第个参数color:颜。#第三个参数:rect:返回个矩形(xy),(width,height)。第四个参数:width:表线条的粗细 width0填充 实pygame.draw.rect(playsurface,redColor,Rect(position0,position1,20,20)pygame.draw.rect(playsurface,whiteColor,Rect(targetPosition0,targetPosition1,20,20)#更新显到屏幕表pygame.display.flip()#判断是否游戏结束if snakePosition0 620 or snakePosition0 460 or snakePosition1 0:gameover()#控制蛇移动的速度fpsClock.tick(10)#启动函数if _name_=_main_:main()