python3 pygame贪吃蛇

python3 用pygame模块写的贪吃蛇小游戏
直接上代码

# -*- coding:utf-8 -*-
# python3 贪吃snake
import pygame
import sys
import random
from pygame.locals import *

GAME_WINDOW_WIDTH = 800    # 游戏界面窗口宽度
GAME_WINDOW_HEIGHT = 600   #  游戏界面窗口高度
GAME_WINDOW_SIZE = (GAME_WINDOW_WIDTH, GAME_WINDOW_HEIGHT)
FOOD_SIZE = 25  # 食物大小
MOVE_SPEED = FOOD_SIZE  # 移动速度
SNAKE_LENGTH = 4  # 蛇身初始化长度

# 颜色定义
WHITE = 255, 255, 255
BLUE = 0, 0, 255
RED = 255, 0, 0
BLACK = 0, 0, 0
GREEN = 0, 255, 0

# 移动方向定义
LEFT = (-MOVE_SPEED, 0)
RIGHT = (MOVE_SPEED, 0)
UP = (0, -MOVE_SPEED)
DOWN = (0, MOVE_SPEED)
STOP = (0, 0)


class Snake(object):
    def __init__(self):
        self.snake_pos_x = 300  # snake初始化x坐标
        self.snake_pos_y = 300  # snake初始化y坐标
        self.direction = RIGHT  # 初始化方向
        self.snake_body_list = []

        # snake body初始化长度
        for i in range(SNAKE_LENGTH)[::-1]:
            self.snake_body_list.append(pygame.Rect(i * FOOD_SIZE + self.snake_pos_x,
                                                    self.snake_pos_y, FOOD_SIZE, FOOD_SIZE))

    # 显示snake
    def display_snake(self):
        for snake_rect in self.snake_body_list:
            pygame.draw.rect(screen, GREEN, snake_rect, 0)

    # 增加snake body
    def add_snake_body(self, direction=RIGHT):
        self.snake_body_list.insert(0, self.snake_body_list[0].move(direction))

    # 删除snake尾
    def del_snake_tail(self):
        self.snake_body_list.pop()

    # 检查snake头是否碰墙是否碰自身
    def checkIsHit(self):
        snake_head_rect = self.snake_body_list[0]
        for rect in self.snake_body_list[1:]:
            if rect.colliderect(snake_head_rect):
                return True
        if snake_head_rect.left < 0 or snake_head_rect.right > GAME_WINDOW_WIDTH or snake_head_rect.top < 0 \
                or snake_head_rect.bottom > GAME_WINDOW_HEIGHT:
            return True

    # snake吃食物
    def eatFood(self, food):
        if self.snake_body_list[0].colliderect(food):
            return True

    # 控制snake速度
    def controlspeed(self, fps):
        fpsClock = pygame.time.Clock()
        fpsClock.tick(fps)

    # 执行游戏
    def RunGame(self):
        direction = self.direction
        food_left, food_top = getRandomfoodPosition()
        score = 0
        iscontinue = 1
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit()
                elif event.type == KEYDOWN:
                    if event.key == K_LEFT and direction != RIGHT:
                        direction = LEFT
                    elif event.key == K_RIGHT and direction != 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_SPACE:
                        iscontinue = -iscontinue
            screen.fill(WHITE)
            if iscontinue > 0:
                self.add_snake_body(direction)
            if self.eatFood(getfoodRect(food_left, food_top)):
                food_left, food_top = getRandomfoodPosition()
                score += 1
            elif iscontinue > 0:
                self.del_snake_tail()
            if self.checkIsHit():
                if displayGameOver():
                    snake = Snake()
                    snake.RunGame()
            else:
                self.display_snake()
                displayfood(getfoodRect(food_left, food_top))
                display_score(score)
            pygame.display.update()
            self.controlspeed(score / 2 + 2)


def getRandomfoodPosition():
    return random.randrange(0, GAME_WINDOW_WIDTH - FOOD_SIZE, FOOD_SIZE), random.randrange(0,
                                                                                           GAME_WINDOW_HEIGHT - FOOD_SIZE,
                                                                                           FOOD_SIZE)


def getfoodRect(food_left, food_top):
    return pygame.Rect(food_left, food_top, FOOD_SIZE, FOOD_SIZE)


def displayfood(foodrect):
    pygame.draw.rect(screen, RED, foodrect, 0)


def displayGameOver():
    g1ameOverfont = pygame.font.SysFont(None, 100)
    g1ameOverImage = g1ameOverfont.render('Game Over', True, BLUE)
    screen.blit(g1ameOverImage, (
    (GAME_WINDOW_WIDTH - g1ameOverImage.get_width()) / 2, (GAME_WINDOW_HEIGHT - g1ameOverImage.get_height()) / 2))
    displayPressMsg()
    pygame.display.update()
    pygame.time.wait(500)
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYUP:
                if event.key == None:
                    pass
                else:
                    return event.key


def displayPressMsg():
    PressMsgfont = pygame.font.SysFont(None, 30)
    PressMsgImage = PressMsgfont.render('Please press any key to play', True, BLACK)
    screen.blit(PressMsgImage,
                (GAME_WINDOW_WIDTH - PressMsgImage.get_width(), GAME_WINDOW_HEIGHT - PressMsgImage.get_height()))


def display_score(score):
    Scorefont = pygame.font.SysFont(None, 30)
    ScoreImage = Scorefont.render('Score:%d' % score, True, BLUE)
    screen.blit(ScoreImage, (GAME_WINDOW_WIDTH - 100, 20))


# 开始运行游戏
if __name__ == '__main__':
    pygame.init()
    pygame.display.set_caption('贪吃snake')
    screen = pygame.display.set_mode(GAME_WINDOW_SIZE, 0, 32)
    snake = Snake()
    snake.RunGame()

贪吃蛇基本功能都已实现,欢迎评论!

你可能感兴趣的:(Python3)