Python学习实践一
[编程语言教程]

贪吃蛇小游戏

pycharm——pygame

game.py

import pygame  # 导包
from game_items import *  # 导类和变量

class Game(object):  # 这里的object类,意为顶级/基础类。
    def __init__(self):
        self.main_window = pygame.display.set_mode((640, 480))
        self.main_name = pygame.display.set_caption(‘贪吃蛇‘)

        self.score_label = Label()  # 得分标签

        self.tip_label = Label(24, False)  # 暂停&游戏结束的标签

        self.is_game_over = True  # 游戏是否结束
        self.is_pause = False  # 游戏是否暂停

        self.food = Food()

        self.snake = Snake()

    def start(self):
        clock = pygame.time.Clock()  # 游戏时钟

        while True:
            self.main_window.fill(BACKGROUND_COLOR)

            # 事件监听
            for event in pygame.event.get():
                if event.type == pygame.QUIT:  # 退出
                    return
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        return

                    elif event.key == pygame.K_SPACE:
                        if self.is_game_over:
                            self.reset_game()
                        else:
                            self.is_pause = not self.is_pause
                if not self.is_pause and not self.is_game_over:
                    if event.type == FOOD_UPDATE_EVENT:
                        self.food.random_rect()
                    elif event.type == SNAKE_UPDATE_EVENT:
                        self.is_game_over = not self.snake.update()
                    elif event.type == pygame.KEYDOWN:
                        if event.key in (pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT, pygame.K_UP):
                            self.snake.change_dir(event.key)

            # 绘制得分标签
            self.score_label.draw(‘分数: %d‘ % self.snake.score, self.main_window)
            # 绘制暂停&游戏结束标签
            if self.is_game_over:
                self.tip_label.draw(‘游戏结束,按空格从新开始游戏。‘, self.main_window)
            elif self.is_pause:
                self.tip_label.draw(‘游戏暂停,按空格键继续。‘, self.main_window)
            #  更新显示内容(不能缺少)
            else:
                if self.snake.has_eat(self.food):
                    self.food.random_rect()

            self.food.draw(self.main_window)

            self.snake.draw(self.main_window)

            pygame.display.update()
            clock.tick(60)  # 刷新频率(帧数)

    def reset_game(self):
        """重置游戏分数"""

        self.is_pause = False
        self.is_game_over = False

        self.snake.reset_snake()
        self.food.random_rect()

if __name__ == ‘__main__‘:

    pygame.init()  # 初始化pygame模块

    #游戏代码
    Game().start()

    pygame.quit()  # 释放pygame模块
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » Python学习实践一