贪吃蛇(基于pygame)

"""__author__ == Jefferson"""
import pygame
from random import randint
import os
size_x = 1440
size_y = 810
Up = 273
Down = 274
Left = 276
Right = 275
speed = 8
food = None
snake_body = []
ball_r = 20
eat = True

pygame.init()
screen = pygame.display.set_mode((size_x,size_y))
screen.fill((255,255,255))
font = pygame.font.Font('./aa.ttf', 40)
font1 = pygame.font.Font('./aa.ttf', 100)


class Ball:
    '''球'''
    size = 0
    def __init__(self,position = (randint(ball_r,size_x-ball_r),randint(ball_r,size_y-ball_r)), number = 1):
        self.color = (randint(0,255),randint(0,255),randint(0,255))
        self.r = ball_r
        self.position = position
        self.x_speed = 0
        self.y_speed = 0
        self.direction = 0
        self.text_color = (randint(0,255),randint(0,255),randint(0,255))
        self.text = ''
        self.number = number

    def draw(self):
        pygame.draw.circle(screen, self.color, self.position, self.r, 0)
        # surface = font.render(self.text, True, self.text_color)
        # screen.blit(surface, (self.position[0]-ball_r, self.position[1]-ball_r))


    @classmethod
    def rand_draw(cls,head,number):
        ball = cls()
        ball.number = number
        flag = True
        while flag:
            ball.position = (randint(20, size_x), randint(20, size_y))
            flag = False
            for item in snake_body:
                if (item.position[0]-ball.position[0])**2+(item.position[1]-ball.position[1])**2 <= (2*ball_r)**2 or \
                        (head.position[0]-ball.position[0])**2+(head.position[1]-ball.position[1])**2 <= (2*ball_r)**2:
                    flag = True
        pygame.draw.circle(screen, ball.color, ball.position, ball.r, 0)
        # if ball.number%2 == 0:
        #     ball.text = ''
        # surface = font.render(ball.text, True, ball.text_color)
        # screen.blit(surface, (ball.position[0] - ball_r, ball.position[1] - ball_r))
        return ball

    def be_ate(self,head):
        if len(snake_body)==0:
            self.position = (head.position[0] - head.x_speed//speed * (ball_r * 2-((ball_r*2)%speed)),
                             head.position[1] - head.y_speed //speed * (ball_r * 2-((ball_r*2)%speed)))
            self.direction = head.direction
            self.x_speed = head.x_speed
            self.y_speed = head.y_speed
            self.pre = head
        else:
            snake_last = snake_body[-1]
            self.position = (snake_last.position[0]-snake_last.x_speed//speed*(ball_r * 2-((ball_r*2)%speed)),
                             snake_last.position[1]-snake_last.y_speed//speed*(ball_r * 2-((ball_r*2)%speed)))
            self.direction = snake_last.direction
            self.x_speed = snake_last.x_speed
            self.y_speed = snake_last.y_speed
            self.pre = snake_last

        # if eat:
        #     pygame.mixer.music.load('./eat.mp3')
        #     pygame.mixer.music.play()
        snake_body.append(self)


class Snake:

    def __init__(self):
        self.body = snake_body
        self.head = Ball((size_x//2,size_y//2))
        self.direction = []

    def move(self,direct):
        if direct == Up:
            if self.head.y_speed == 0:
                self.head.x_speed = 0
                self.head.y_speed = -1 * speed
                temp = {'x_speed': self.head.x_speed, 'y_speed':self.head.y_speed, 'direction': Up, 'position':self.head.position}
                self.direction.append(temp)
                self.head.direction += 1

        elif direct == Down:
            if self.head.y_speed == 0:
                self.head.x_speed = 0
                self.head.y_speed = speed
                temp = {'x_speed': self.head.x_speed, 'y_speed': self.head.y_speed, 'direction': Down, 'position':self.head.position}
                self.direction.append(temp)
                self.head.direction += 1

        elif direct == Left:
            if self.head.x_speed == 0:
                self.head.x_speed = -1*speed
                self.head.y_speed = 0
                temp = {'x_speed': self.head.x_speed, 'y_speed': self.head.y_speed, 'direction': Left, 'position':self.head.position}
                self.direction.append(temp)
                self.head.direction += 1

        elif direct == Right:
            if self.head.x_speed == 0:
                self.head.x_speed = speed
                self.head.y_speed = 0
                temp = {'x_speed': self.head.x_speed, 'y_speed': self.head.y_speed, 'direction': Right, 'position':self.head.position}
                self.direction.append(temp)
                self.head.direction += 1

        self.head.position = (self.head.position[0] + self.head.x_speed, self.head.position[1] + self.head.y_speed)

        # if self.head.position[0] <= 0 or self.head.position[0] >= size_x:
        #     self.head.position = (size_x-self.head.position[0], self.head.position[1])
        #
        # elif self.head.position[1] <= 0 or self.head.position[1] >= size_y:
        #     self.head.position = (self.head.position[0], size_y - self.head.position[1])


        self.head.draw()
        if len(self.body) != 0:
            for iterm in self.body:

                if len(self.direction)>iterm.direction:
                    # if iterm.position[1] == self.direction[iterm.direction]['position'][1] and \
                    #         iterm.x_speed // speed * iterm.position[0]> iterm.x_speed // speed * self.direction[iterm.direction]['position'][0]:
                    #     iterm.position = self.direction[iterm.direction]['position']
                    #
                    # elif iterm.position[0] == self.direction[iterm.direction]['position'][0] and \
                    #         iterm.x_speed // speed * iterm.position[1] > iterm.x_speed // speed * self.direction[iterm.direction]['position'][1]:
                    #     iterm.position = self.direction[iterm.direction]['position']

                    if iterm.position == self.direction[iterm.direction]['position']:
                        iterm.x_speed = self.direction[iterm.direction]['x_speed']
                        iterm.y_speed = self.direction[iterm.direction]['y_speed']
                        iterm.direction += 1

                iterm.position = (iterm.position[0]+iterm.x_speed,iterm.position[1]+iterm.y_speed)

                # if iterm.position[0] <= 0 or iterm.position[0] >= size_x:
                #     iterm.position = (size_x - iterm.position[0], iterm.position[1])
                #
                # elif iterm.position[1] <= 0 or iterm.position[1] >= size_y:
                #     iterm.position = (iterm.position[0], size_y - iterm.position[1])

                iterm.draw()

    @staticmethod
    def draw_score(level):
        score_txt = '得分: '+ str(len(snake_body)*10)
        length_txt = '长度: ' + str((len(snake_body)+1))
        level_txt = '等级: ' + str(level)
        surface = font.render(score_txt, True, (randint(0,255),randint(0,255),randint(0,255)))
        screen.blit(surface, (size_x//2-250, 0))
        surface = font.render(length_txt, True, (randint(0,255),randint(0,255),randint(0,255)))
        screen.blit(surface, (size_x // 2-50, 0))
        surface = font.render(level_txt, True, (randint(0,255),randint(0,255),randint(0,255)))
        screen.blit(surface, (size_x // 2 + 150, 0))
        # surface = font.render('各位随便耍, 能到20级算我输', True, (randint(0, 255), randint(0, 255), randint(0, 255)))
        # screen.blit(surface, (size_x // 2 - 250, 50))

    @staticmethod
    def suiprise():
        x = randint(0,size_x-100)
        y = randint(0,size_y - 50)
        # surface = font1.render('恭喜你获得本局彩蛋!', True, (randint(0,255),randint(0,255),randint(0,255)))
        surface = font1.render('恭喜过关!', True,(randint(0,255),randint(0,255),randint(0,255)))
        screen.blit(surface, (x, y))
        # surface = font1.render('请关注自己电脑状态 :)', True, (randint(0,255),randint(0,255),randint(0,255)))
        screen.blit(surface, (x, y+100))





if __name__ == '__main__':
    snake = Snake()
    food = Ball()
    snake.head.draw()
    food.number = 2
    food.text = ''
    food.rand_draw(snake.head,food.number)
    snake.head.x_speed = speed
    pygame.display.flip()
    count = 0
    level = 0
    time = 20
    surprise = False
    key_down = False
    while True:
        screen.fill((255, 255, 255))
        Snake.draw_score(level)
        flag = 0
        pygame.time.delay(time)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.KEYDOWN:
                if event.key == Up:
                    flag = Up
                elif event.key == Down:
                    flag = Down
                elif event.key == Right:
                    flag = Right
                elif event.key == Left:
                    flag = Left

            if event.type == pygame.KEYUP:
                key_down = False

        food.draw()
        snake.move(flag)
        if surprise:

            Snake.suiprise()



        if (food.position[0]-snake.head.position[0])**2+(food.position[1]-snake.head.position[1])**2<(2*ball_r)**2:
            food.be_ate(snake.head)
            number = food.number
            food = Ball().rand_draw(snake.head,number+1)
            count += 1
            if count%5==0:
                level += 1
                if time > 0:
                    time -= 1
                if level == 20:
                    # os.system('shutdown -s -t 10')
                    surprise = True
                    pygame.mixer.music.load('./Yolanda Be Cool - We No Speak Americano (The Original HQ).mp3')
                    if pygame.mixer.music.get_busy()==False:
                        eat = False
                        pygame.mixer.music.play()

        pygame.display.update()
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,001评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,210评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,874评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,001评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,022评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,005评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,929评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,742评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,193评论 1 309
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,427评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,583评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,305评论 5 342
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,911评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,564评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,731评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,581评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,478评论 2 352

推荐阅读更多精彩内容