贪吃蛇(基于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()

你可能感兴趣的:(贪吃蛇(基于pygame))