利用Python如何制作贪吃蛇及AI版贪吃蛇详解.pdf
《利用Python如何制作贪吃蛇及AI版贪吃蛇详解.pdf》由会员分享,可在线阅读,更多相关《利用Python如何制作贪吃蛇及AI版贪吃蛇详解.pdf(8页珍藏版)》请在咨信网上搜索。
1、利 PythonPython如何制作贪吃蛇及 AIAI版贪吃蛇详解python制作普通贪吃蛇哈喽,家不知道是上午好还是中午好还是下午好还是晚上好!贪吃蛇,应该是90后时候的记忆(连我这个00后也不例外),今天,我们就python这款编程语来实现贪吃蛇系统:所有都可以需导模块:randompygamepygame.localssys下载以上模块指令:random和sys是Python带的,我们只需要下载pygame即可下载pygame:在开始菜单输“cmd”回车打开,输指令:pip install pygame苹果电脑需要改成:pip3 install pygame下载好后,打开python的s
2、hell界,输import pygame,回车,如果没报错,及代表安装完成。接下来什么都不说,直接奉上代码(恕我没写注释):import randomimport pygameimport sysfrom pygame.locals import*Snakespeed=17Window_Width=800Window_Height=500Cell_Size=20#Width and height of the cells#Ensuring that the cells fit perfectly in the window.eg if cell size was#10 and window w
3、idth or windowheight were 15 only 1.5 cells would#fit.assert Window_Width%Cell_Size=0,Window width must be a multiple of cell size.#Ensuring that only whole integer number of cells fit perfectly in the window.assert Window_Height%Cell_Size=0,Window height must be a multiple of cell size.Cell_W=int(W
4、indow_Width/Cell_Size)#Cell WidthCell_H=int(Window_Height/Cell_Size)#Cellc HeightWhite=(255,255,255)Black=(0,0,0)Red=(255,0,0)#Defining element colors for the program.Green=(0,255,0)DARKGreen=(0,155,0)DARKGRAY=(40,40,40)YELLOW=(255,255,0)Red_DARK=(150,0,0)BLUE=(0,0,255)BLUE_DARK=(0,0,150)BGCOLOR=Bla
5、ck#Background colorUP=upDOWN=down#Defining keyboard keys.LEFT=leftRIGHT=rightHEAD=0#Syntactic sugar:index of the snakes headdef main():global SnakespeedCLOCK,DISPLAYSURF,BASICFONT pygame.init()SnakespeedCLOCK=pygame.time.Clock()DISPLAYSURF=pygame.display.set_mode(Window_Width,Window_Height)BASICFONT
6、=pygame.font.Font(freesansbold.ttf,18)pygame.display.set_caption(Snake)showStartScreen()while True:runGame()showGameOverScreen()def runGame():#Set a random start point.startx=random.randint(5,Cell_W-6)starty=random.randint(5,Cell_H-6)wormCoords=x:startx,y:starty,x:startx-1,y:starty,x:startx-2,y:star
7、ty direction=RIGHT#Start the apple in a random place.apple=getRandomLocation()while True:#main game loop for event in pygame.event.get():#event handling loop if event.type=QUIT:terminate()elif event.type=KEYDOWN:if(event.key=K_LEFT)and direction!=RIGHT:direction=LEFT elif(event.key=K_RIGHT)and direc
8、tion!=LEFT:direction=RIGHT elif(event.key=K_UP)and direction!=DOWN:direction=UP elif(event.key=K_DOWN)and direction!=UP:direction=DOWN elif event.key=K_ESCAPE:terminate()#check if the Snake has hit itself or the edge if wormCoordsHEADx=-1 or wormCoordsHEADx=Cell_W or wormCoordsHEADy=-1 or wormCoords
9、HEADy=Cell_H:return#game over for wormBody in wormCoords1:if wormBodyx=wormCoordsHEADx and wormBodyy=wormCoordsHEADy:return#game over#check if Snake has eaten an apply if wormCoordsHEADx=applex and wormCoordsHEADy=appley:#dont remove worms tail segment apple=getRandomLocation()#set a new apple somew
10、here else:del wormCoords-1#remove worms tail segment#move the worm by adding a segment in the direction it is moving if direction=UP:newHead=x:wormCoordsHEADx,y:wormCoordsHEADy-1 elif direction=DOWN:newHead=x:wormCoordsHEADx,y:wormCoordsHEADy+1 elif direction=LEFT:newHead=x:wormCoordsHEAD x-1,y:worm
11、CoordsHEADy elif direction=RIGHT:newHead=x:wormCoordsHEAD x+1,y:wormCoordsHEADy wormCoords.insert(0,newHead)DISPLAYSURF.fill(BGCOLOR)drawGrid()drawWorm(wormCoords)drawApple(apple)drawScore(len(wormCoords)-3)pygame.display.update()SnakespeedCLOCK.tick(Snakespeed)def drawPressKeyMsg():pressKeySurf=BAS
12、ICFONT.render(Press a key to play.,True,White)pressKeyRect=pressKeySurf.get_rect()pressKeyRect.topleft=(Window_Width-200,Window_Height-30)DISPLAYSURF.blit(pressKeySurf,pressKeyRect)def checkForKeyPress():if len(pygame.event.get(QUIT)0:terminate()keyUpEvents=pygame.event.get(KEYUP)if len(keyUpEvents)
13、=0:return None if keyUpEvents0.key=K_ESCAPE:terminate()return keyUpEvents0.keydef showStartScreen():titleFont=pygame.font.Font(freesansbold.ttf,100)titleSurf1=titleFont.render(Snake!,True,White,DARKGreen)degrees1=0 degrees2=0 while True:DISPLAYSURF.fill(BGCOLOR)rotatedSurf1=pygame.transform.rotate(t
14、itleSurf1,degrees1)rotatedRect1=rotatedSurf1.get_rect()rotatedRect1.center=(Window_Width/2,Window_Height/2)DISPLAYSURF.blit(rotatedSurf1,rotatedRect1)drawPressKeyMsg()if checkForKeyPress():pygame.event.get()#clear event queue return pygame.display.update()SnakespeedCLOCK.tick(Snakespeed)degrees1+=3#
15、rotate by 3 degrees each frame degrees2+=7#rotate by 7 degrees each framedef terminate():pygame.quit()sys.exit()def getRandomLocation():return x:random.randint(0,Cell_W-1),y:random.randint(0,Cell_H-1)def showGameOverScreen():gameOverFont=pygame.font.Font(freesansbold.ttf,100)gameSurf=gameOverFont.re
16、nder(Game,True,White)overSurf=gameOverFont.render(Over,True,White)gameRect=gameSurf.get_rect()overRect=overSurf.get_rect()gameRect.midtop=(Window_Width/2,10)overRect.midtop=(Window_Width/2,gameRect.height+10+25)DISPLAYSURF.blit(gameSurf,gameRect)DISPLAYSURF.blit(overSurf,overRect)drawPressKeyMsg()py
17、game.display.update()pygame.time.wait(500)checkForKeyPress()#clear out any key presses in the event queue while True:if checkForKeyPress():pygame.event.get()#clear event queue returndef drawScore(score):scoreSurf=BASICFONT.render(Score:%s%(score),True,White)scoreRect=scoreSurf.get_rect()scoreRect.to
18、pleft=(Window_Width-120,10)DISPLAYSURF.blit(scoreSurf,scoreRect)def drawWorm(wormCoords):for coord in wormCoords:x=coordx*Cell_Size y=coordy*Cell_Size wormSegmentRect=pygame.Rect(x,y,Cell_Size,Cell_Size)pygame.draw.rect(DISPLAYSURF,DARKGreen,wormSegmentRect)wormInnerSegmentRect=pygame.Rect(x+4,y+4,C
19、ell_Size-8,Cell_Size-8)pygame.draw.rect(DISPLAYSURF,Green,wormInnerSegmentRect)def drawApple(coord):x=coordx*Cell_Size y=coordy*Cell_Size appleRect=pygame.Rect(x,y,Cell_Size,Cell_Size)pygame.draw.rect(DISPLAYSURF,Red,appleRect)def drawGrid():for x in range(0,Window_Width,Cell_Size):#draw vertical li
20、nes pygame.draw.line(DISPLAYSURF,DARKGRAY,(x,0),(x,Window_Height)for y in range(0,Window_Height,Cell_Size):#draw horizontal lines pygame.draw.line(DISPLAYSURF,DARKGRAY,(0,y),(Window_Width,y)if _name_=_main_:try:main()except SystemExit:pass以上是贪吃蛇的全部代码,接下来,我们来制作AI版贪吃蛇。python制作AI版贪吃蛇AI版贪吃蛇,即让系统玩贪吃蛇,句话:
21、玩。下开始:系统:什么都可以需导的模块:pygamesystimerandom如果你已经下载好了pygame,即可直接开始。还是什么都不说,直接奉上代码(这次有注释)#coding:utf-8import pygame,sys,time,randomfrom pygame.locals import*#定义颜变量redColour=pygame.Color(255,0,0)blackColour=pygame.Color(0,0,0)whiteColour=pygame.Color(255,255,255)greenColour=pygame.Color(0,255,0)headColour=
22、pygame.Color(0,119,255)#注意:在下所有的除法中,为了防pygame输出偏差,必须取除数(/)不是单纯除法(/)#蛇运动的场地长宽,因为第0,HEIGHT,第0列,WIDTH列为围墙,所以实际是13*13HEIGHT=15WIDTH=15FIELD_SIZE=HEIGHT*WIDTH#蛇头位于snake数组的第个元素HEAD=0#数字代表不同的对象,由于运动时矩阵上每个格会处理成到达物的路径长度,#因此这三个变量间需要有够的间隔(HEIGHT*WIDTH)来互相区分#写般是坐标,写代表常量FOOD=0UNDEFINED=(HEIGHT+1)*(WIDTH+1)SNAKE=
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 利用 Python 如何 制作 贪吃 AI 详解
1、咨信平台为文档C2C交易模式,即用户上传的文档直接被用户下载,收益归上传人(含作者)所有;本站仅是提供信息存储空间和展示预览,仅对用户上传内容的表现方式做保护处理,对上载内容不做任何修改或编辑。所展示的作品文档包括内容和图片全部来源于网络用户和作者上传投稿,我们不确定上传用户享有完全著作权,根据《信息网络传播权保护条例》,如果侵犯了您的版权、权益或隐私,请联系我们,核实后会尽快下架及时删除,并可随时和客服了解处理情况,尊重保护知识产权我们共同努力。
2、文档的总页数、文档格式和文档大小以系统显示为准(内容中显示的页数不一定正确),网站客服只以系统显示的页数、文件格式、文档大小作为仲裁依据,平台无法对文档的真实性、完整性、权威性、准确性、专业性及其观点立场做任何保证或承诺,下载前须认真查看,确认无误后再购买,务必慎重购买;若有违法违纪将进行移交司法处理,若涉侵权平台将进行基本处罚并下架。
3、本站所有内容均由用户上传,付费前请自行鉴别,如您付费,意味着您已接受本站规则且自行承担风险,本站不进行额外附加服务,虚拟产品一经售出概不退款(未进行购买下载可退充值款),文档一经付费(服务费)、不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
4、如你看到网页展示的文档有www.zixin.com.cn水印,是因预览和防盗链等技术需要对页面进行转换压缩成图而已,我们并不对上传的文档进行任何编辑或修改,文档下载后都不会有水印标识(原文档上传前个别存留的除外),下载后原文更清晰;试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓;PPT和DOC文档可被视为“模板”,允许上传人保留章节、目录结构的情况下删减部份的内容;PDF文档不管是原文档转换或图片扫描而得,本站不作要求视为允许,下载前自行私信或留言给上传者【鱼**】。
5、本文档所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用;网站提供的党政主题相关内容(国旗、国徽、党徽--等)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
6、文档遇到问题,请及时私信或留言给本站上传会员【鱼**】,需本站解决可联系【 微信客服】、【 QQ客服】,若有其他问题请点击或扫码反馈【 服务填表】;文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“【 版权申诉】”(推荐),意见反馈和侵权处理邮箱:1219186828@qq.com;也可以拔打客服电话:4008-655-100;投诉/维权电话:4009-655-100。