| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 656 人关注过本帖
标题:用python怎么做贪吃蛇
只看楼主 加入收藏
一张纸白
Rank: 2
等 级:论坛游民
帖 子:32
专家分:24
注 册:2023-8-31
结帖率:100%
收藏
 问题点数:0 回复次数:8 
用python怎么做贪吃蛇
用python怎么做贪吃蛇
搜索更多相关主题的帖子: 贪吃蛇 python 
2023-09-01 10:09
一张白纸123
Rank: 2
等 级:论坛游民
帖 子:40
专家分:24
注 册:2023-8-31
收藏
得分:0 
建议你要先拥有一个第三方库:Pygame

一张有内容的白纸
2023-09-02 11:21
一张白纸123
Rank: 2
等 级:论坛游民
帖 子:40
专家分:24
注 册:2023-8-31
收藏
得分:0 
程序代码如下:
import pygame,sys
from pygame.locals import *
from sys import exit

class Snake(pygame.sprite.Sprite):

    snake_head=pygame.image.load('snake_head.png')
    snake_body=pygame.image.load('snake_body.png')
    snake_tail=pygame.image.load('snake_tail.png')
   
    def __init__(self,screen):
        pygame.sprite.Sprite.__init__(self)
        #蛇序列
        self.snakeLine=[(400,250),(400-40,250),(400-40*2,250)]

        #画板
        self.screen=screen

        #碰撞检测
        self.rect=Rect(400,250,40,40) #蛇头的区域

    def show(self,newSnakeLine=None):
        #将新的蛇序列设为原蛇序列
        if newSnakeLine is not None:
            self.snakeLine=newSnakeLine
            self.rect=Rect(newSnakeLine[0],(40,40))

        self.screen.blit(Snake.snake_head,self.snakeLine[0])
        self.rect=Rect(self.snakeLine[0],(40,40))

        #蛇尾
        for cord in self.snakeLine[1:-1]:
            self.screen.blit(Snake.snake_body,cord)

        #蛇尾
        self.screen.blit(Snake.snake_tail,self.snakeLine[-1])
        
    def getDirection(self):
        offX=self.snakeLine[0][0]-self.snakeLine[1][0]
        offY=self.snakeLine[0][1]-self.snakeLine[1][1]
        if (offX==30 or offX==-870) and offY==0:
            return K_RIGHT
        
        elif (offX==-30 or offX==870) and offY==0:
            return K_LEFT
        
        elif offX==0 and (offY==30 or offY==-570):
            return K_DOWN
        
        elif offX==0 and (offY==-30 or offY==570):
            return K_UP

    def move(self,KEY=None):
   
        #创建一个冲突列表
        wrong_list=[{K_RIGHT,K_RIGHT},{K_RIGHT,K_LEFT},{K_LEFT,K_LEFT},{K_UP,K_UP},{K_UP,K_DOWN},{K_DOWN,K_DOWN}]
        if KEY is None or {self.getDirection(),KEY} in wrong_list:
            KEY=self.getDirection()#按错方向键后,不改变原方向
            
        if KEY==K_RIGHT:#右移就在右侧添加蛇头,蛇尾减少1块
            self.snakeLine=[((self.snakeLine[0][0]+40)%900,self.snakeLine[0][1])]+self.snakeLine[0:-1]
            
        elif KEY==K_UP:#上移就在上侧添加蛇头,蛇尾减少1块
            self.snakeLine=[(self.snakeLine[0][0],(600+self.snakeLine[0][1]-40)%600)]+self.snakeLine[0:-1]
            
        elif KEY==K_DOWN:#下移就在下侧添加蛇头,蛇尾减少1块
            self.snakeLine=[(self.snakeLine[0][0],(self.snakeLine[0][1]+40)%600)]+self.snakeLine[0:-1]
            
        elif KEY==K_LEFT:#左移就在左侧添加蛇头,蛇尾减少1块
            self.snakeLine=[((self.snakeLine[0][0]-40+900)%900,self.snakeLine[0][1])]+self.snakeLine[0:-1]
            
        self.show()

pygame.init()

screen=pygame.display.set_mode((900,600))
pygame.display.set_caption('snake')

snake=Snake(screen)

clock=pygame.time.Clock()


while True:
   
    clock.tick(10)

    KEY=None
   
    for event in pygame.event.get():#进行事件等待
        #如果用户单击关闭窗口按钮就退出
        if event.type==QUIT:
            pygame.quit()
            exit()
        if event.type==KEYDOWN:
            KEY=event.key

    screen.fill('black')

    snake.move(KEY)

    #循环显示
    pygame.display.update()

一张有内容的白纸
2023-09-02 11:28
一张白纸123
Rank: 2
等 级:论坛游民
帖 子:40
专家分:24
注 册:2023-8-31
收藏
得分:0 
但其中的素材你要自己找
也可以用矩形rect代替

一张有内容的白纸
2023-09-02 11:29
小白在此
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2023-8-7
收藏
得分:0 
程序代码:
import random,sys,pygame
from pygame.locals import*
FPS=5
width=640
heigh=480
cellsize=20
cellwidth=int(width/cellsize)
cellheigh=int(heigh/cellsize)
white=(255,255,255)
black=(0,0,0)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
darkgreen=(0,155,0)
darkgray=(40,40,40)
BGcolor=white
Up='up'
Down='down'
Left='left'
Right='right'
def main():
    global FPSlock,screen,BASICfont
    pygame.init()
    FPSlock=pygame.time.Clock()
    screen=pygame.display.set_mode([width,heigh])
    BASICfont=pygame.font.Font(r'C:\Windows\Fonts\simkai.ttf',20)
    pygame.display.set_caption('贪吃蛇')
    showstartscreen()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        rungame()
        showgameover()
def showstartscreen():
    width1=640
    heigh1=480
    titlefont=pygame.font.Font(r'C:\Windows\Fonts\simkai.ttf',100)
    titlesurf1=titlefont.render('贪吃蛇',True,black,darkgreen)
    titlesurf2=titlefont.render('贪吃蛇',True,green)
    degrees1=0
    degrees2=0
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                return
        screen.fill(BGcolor)
        surf1=pygame.transform.rotate(titlesurf1,degrees1)
        rect1=surf1.get_rect()
        rect1.center=(width1/2,heigh1/2)
        screen.blit(surf1,rect1)
        surf2=pygame.transform.rotate(titlesurf2,degrees2)
        rect2=surf2.get_rect()
        rect2.center=(width1/2,heigh1/2)
        screen.blit(surf2,rect2)
        drawpresskeymsg()
        pygame.display.update()
        FPSlock.tick(FPS)
        degrees1 += 3
        degrees2 += 7
def drawpresskeymsg():
    presskeysurf=BASICfont.render('按任意键进入游戏',True,black)
    presskeyrect=presskeysurf.get_rect()
    presskeyrect.topleft=(width-200,heigh-30)
    screen.blit(presskeysurf,presskeyrect)
def drawgrid():
    for x in range(0,width,cellsize):
        pygame.draw.line(screen,darkgreen,(x,0),(x,heigh))
    for y in range(0,heigh,cellsize):
        pygame.draw.line(screen,darkgreen,(0,y),(width,y))
def getrandomlocation():
    return {'x':random.randint(0,cellwidth),'y':random.randint(0,cellheigh-1)}
def drawscore(score):
    scoresurf=BASICfont.render('分数:%s'%(score),True,black)
    scorerect=scoresurf.get_rect()
    scorerect.topleft=(width-120,10)
    screen.blit(scoresurf,scorerect)
def rungame():
    startx=random.randint(5,cellwidth-6)
    starty=random.randint(5,cellheigh-6)
    wormcoords=[{'x':startx,'y':starty},{'x':startx-1,'y':starty},{'x':startx-2,'y':starty}]
    direction=Right
    apple=getrandomlocation()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == KEYDOWN:
                if (event.key==K_LEFT or event.key==K_a)and direction != Right:
                    direction=Left
                elif (event.key==K_RIGHT or event.key==K_d)and direction != Left:
                    direction=Right
                elif (event.key==K_UP or event.key==K_w)and direction != Down:
                    direction=Up
                elif (event.key==K_DOWN or event.key==K_s)and direction != Up:
                    direction=Down
                elif event.key == K_ESCAPE:
                    sys.exit()
        if wormcoords[0]['x'] == -1 or wormcoords[0]['x'] == cellwidth or wormcoords[0]['y'] == -1 or wormcoords[0]['y'] == cellheigh:
            return
        for wormbody in wormcoords[1:]:
            if wormbody['x'] == wormcoords[0]['x'] and wormbody['y'] == wormcoords[0]['y']:
                return
        if wormcoords[0]['x'] == apple['x'] and wormcoords[0]['y'] == apple['y']:
            apple= getrandomlocation()
        else:
            del wormcoords[-1]
        if direction == Up:
            newhead={'x':wormcoords[0]['x'],'y':wormcoords[0]['y']-1}
        elif direction == Down:
            newhead={'x':wormcoords[0]['x'],'y':wormcoords[0]['y']+1}
        elif direction == Left:
            newhead={'x':wormcoords[0]['x']-1,'y':wormcoords[0]['y']}
        elif direction == Right:
            newhead={'x':wormcoords[0]['x']+1,'y':wormcoords[0]['y']}
        wormcoords.insert(0,newhead)
        screen.fill(BGcolor)
        drawgrid()
        drawworm(wormcoords)
        drawapple(apple)
        drawscore(len(wormcoords)-3)
        pygame.display.update()
        FPSlock.tick(FPS)
def drawworm(wormcoords):
    for coord in wormcoords:
        x=coord['x']*cellsize
        y=coord['y']*cellsize
        wormsegmentrect=pygame.Rect(x,y,cellsize,cellsize)
        pygame.draw.rect(screen,darkgreen,wormsegmentrect)
        worminnersegmentrect=pygame.Rect(x+4,y+4,cellsize-8,cellsize-8)
        pygame.draw.rect(screen,darkgreen,worminnersegmentrect)
def drawapple(coord):
    x=coord['x']*cellsize
    y=coord['y']*cellsize
    applerect=pygame.Rect(x,y,cellsize,cellsize)
    pygame.draw.rect(screen,red,applerect)
def showgameover():
    gameoverfont=pygame.font.Font('C://Windows//Fonts//msyh.ttc',150)
    gamesurf=gameoverfont.render('游戏',True,black)
    oversurf=gameoverfont.render('失败',True,black)
    gamerect=gamesurf.get_rect()
    overrect=oversurf.get_rect()
    gamerect.midtop=(width/2,10)
    overrect.midtop=(width/2,gamerect.height+10+25)
    screen.blit(gamesurf,gamerect)
    screen.blit(oversurf,overrect)
    drawpresskeymsg()
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            return 
if __name__=='__main__':
    main()

亲测可用
2023-09-02 13:47
一张纸白
Rank: 2
等 级:论坛游民
帖 子:32
专家分:24
注 册:2023-8-31
收藏
得分:0 
谢谢
2023-09-02 15:44
一张纸白
Rank: 2
等 级:论坛游民
帖 子:32
专家分:24
注 册:2023-8-31
收藏
得分:0 
不过我这没有分
2023-09-02 15:45
一张白纸123
Rank: 2
等 级:论坛游民
帖 子:40
专家分:24
注 册:2023-8-31
收藏
得分:0 
厉害呀,大神

一张有内容的白纸
2023-09-02 15:48
小白在此
Rank: 1
等 级:新手上路
帖 子:6
专家分:0
注 册:2023-8-7
收藏
得分:0 
回复 7楼 一张纸白
不会啊,分数在右上角啊。
如果你觉得满意的话,能不能结个帖呢

[此贴子已经被作者于2023-9-9 11:21编辑过]

2023-09-02 17:20
快速回复:用python怎么做贪吃蛇
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018467 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved