猫史档案馆


【Python作品分享】贪吃蛇【作品秀】

用户:是洛桃哒是洛桃哒查看:0 回复:0 评论:0 创建时间:2022-08-09T19:23:27


【作品展示】

center_image

 

【作品介绍】

用了pygame的运行库

不知道可不可以运行,不可以的话在评论区回复一声,谢谢

 

【作品源代码】

# 导入程序所需要的模块

import random
import sys

import pygame
from pygame.locals import *

# 定义颜色的变量

# 目标方块的颜色 红色

redColour = pygame.Color(255, 0, 0)

# 背景颜色 黑色

blackColour = pygame.Color(0, 0, 0)

# 贪吃蛇的颜色 白色

whiteColour = pygame.Color(255, 255, 255)

# 游戏界面大小

windows_width = 800

windows_height = 600


# 定义游戏结束的函数

def gameOver():
    pygame.quit()

    sys.exit()


# 主函数

def main():
    # 初始化Pygame这个游戏库

    pygame.init()

    # 定义一个变量控制游戏的速度

    fpsClock = pygame.time.Clock()

    # 创建一个窗口 图形界面

    playSurface = pygame.display.set_mode((windows_width, windows_height))

    pygame.display.set_caption("贪吃蛇")  # 游戏名称写在窗口标题

    # 初始化最高分(不可修改)

    high_score = 0

    show_start_info(playSurface)  # 打印欢迎信息

    while True:

        # 初始化变量

        # 贪吃蛇起始坐标位置(100,100)

        snakePosition = [100, 100]

        snakeBody = [[100, 100], [80, 100], [60, 100]]

        # 目标方块的起始位置

        targetPosition = [300, 300]

        # 目标方块的标记 目的:用来判断是否吃掉了这个目标方块

        targetflag = 1

        # 初始化方向--> 往右

        direction = 'right'

        # 定义一个方向变量

        changeDirection = direction

        while True:

            for event in pygame.event.get():

                if event.type == QUIT:

                    pygame.quit()

                    sys.exit()

                elif event.type == KEYDOWN:

                    if event.key == K_RIGHT:
                        changeDirection = 'right'

                    if event.key == K_LEFT:
                        changeDirection = 'left'

                    if event.key == K_UP:
                        changeDirection = 'up'

                    if event.key == K_DOWN:
                        changeDirection = 'down'

                        # 对应该键盘上的Esc键

                    if event.key == K_ESCAPE:
                        pygame.event.post(pygame.event.Event(QUIT))

            # 确定方向

            if changeDirection == 'left' and not direction == 'right':
                direction = changeDirection

            if changeDirection == 'right' and not direction == 'left':
                direction = changeDirection

            if changeDirection == 'up' and not direction == 'down':
                direction = changeDirection

            if changeDirection == 'down' and not direction == 'up':
                direction = changeDirection

            # 根据方向移动蛇头坐标

            if direction == 'right':
                snakePosition[0] += 20

            if direction == 'left':
                snakePosition[0] -= 20

            if direction == 'up':
                snakePosition[1] -= 20

            if direction == 'down':
                snakePosition[1] += 20

            # 增加蛇的长度

            snakeBody.insert(0, list(snakePosition))

            # 如果我们贪吃蛇的位置和目标方块的位置重合了 目标方块的标记为0

            if snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]:

                targetflag = 0

            else:

                snakeBody.pop()

            if targetflag == 0:
                # 随机生成目标方块

                x = random.randrange(1, 32)

                y = random.randrange(1, 24)

                targetPosition = [int(x * 20), int(y * 20)]

                targetflag = 1

            playSurface.fill(blackColour)  # 填充背景为黑色

            for position in snakeBody:
                # 在屏幕上创建一条蛇

                pygame.draw.rect(playSurface, whiteColour, Rect(position[0], position[1], 20, 20))

                # 在屏幕上创建目标方块

                pygame.draw.rect(playSurface, redColour, Rect(targetPosition[0], targetPosition[1], 20, 20))

            pygame.display.flip()

            # 显示得分信息

            score = len(snakeBody) * 50 - 150

            draw_score(playSurface, score)

            draw_high_score(playSurface, high_score)

            # 出现更高分数把分数更新

            if score > high_score:
                high_score = score

            pygame.display.update()

            # 游戏结束

            if snakePosition[0] > 800 or snakePosition[0] < 0:

                break

            elif snakePosition[1] > 600 or snakePosition[1] < 0:

                break

            # 控制游戏速度

            fpsClock.tick(8)

        # 显示再玩一次按钮

        show_gameover_info(playSurface)


def show_start_info(playSurface):
    # 设置按钮的尺寸和其他属性

    width, height = 200, 50

    button_color = pygame.Color(0, 255, 0)

    text_color = pygame.Color(255, 255, 255)

    font = pygame.font.SysFont(None, 48)

    # 创建按钮的rect对象,并使其居中

    rect = pygame.Rect(0, 0, width, height)

    playSurface_rect = playSurface.get_rect()

    rect.center = playSurface_rect.center

    '''将msg渲染为图像,并使其在按钮上居中'''

    msg = "Play"

    msg_image = font.render(msg, True, text_color, button_color)

    msg_image_rect = msg_image.get_rect()

    msg_image_rect.center = rect.center

    # 绘制一个用颜色填充的按钮,再绘制文本

    playSurface.fill(button_color, rect)

    playSurface.blit(msg_image, msg_image_rect)

    pygame.display.update()

    while True:  # 鼠标监听事件

        for event in pygame.event.get():  # event handling loop

            if event.type == pygame.QUIT:

                gameOver()  # 终止程序

            elif event.type == pygame.MOUSEBUTTONDOWN:

                mouse_x, mouse_y = pygame.mouse.get_pos()

                return  # 结束此函数, 开始游戏


def show_gameover_info(playSurface):
    # 设置按钮的尺寸和其他属性

    width, height = 200, 50

    button_color = pygame.Color(0, 255, 0)

    text_color = pygame.Color(255, 255, 255)

    font = pygame.font.SysFont(None, 48)

    # 创建按钮的rect对象,并使其居中

    rect = pygame.Rect(0, 0, width, height)

    playSurface_rect = playSurface.get_rect()

    rect.center = playSurface_rect.center

    '''将msg渲染为图像,并使其在按钮上居中'''

    msg = "Play Again"

    msg_image = font.render(msg, True, text_color, button_color)

    msg_image_rect = msg_image.get_rect()

    msg_image_rect.center = rect.center

    # 绘制一个用颜色填充的按钮,再绘制文本

    playSurface.fill(button_color, rect)

    playSurface.blit(msg_image, msg_image_rect)

    pygame.display.update()

    while True:  # 键盘监听事件

        for event in pygame.event.get():  # event handling loop

            if event.type == pygame.QUIT:

                gameOver()  # 终止程序

            elif event.type == pygame.MOUSEBUTTONDOWN:

                mouse_x, mouse_y = pygame.mouse.get_pos()

                return  # 结束此函数, 开始游戏


def draw_score(playSurface, score):
    # 显示得分信息时使用的字体设置

    text_color = pygame.Color(255, 255, 255)

    font = pygame.font.SysFont(None, 48)

    '''将得分转换为一幅渲染的图像'''

    rounded_score = int(round(score, -1))

    score_str = "{:,}".format(rounded_score)

    score_image = font.render(score_str, True, text_color, (0, 0, 0))

    # 将得分放在屏幕右上角

    score_rect = score_image.get_rect()

    playSurface_rect = playSurface.get_rect()

    score_rect.right = playSurface_rect.right - 20

    score_rect.top = 20

    playSurface.blit(score_image, score_rect)


def draw_high_score(playSurface, high_score):
    # 显示得分信息时使用的字体设置

    text_color = pygame.Color(255, 255, 255)

    font = pygame.font.SysFont(None, 48)

    '''将得分转换为一幅渲染的图像'''

    rounded_high_score = int(round(high_score, -1))

    high_score_str = "{:,}".format(rounded_high_score)

    high_score_image = font.render(high_score_str, True, text_color, (0, 0, 0))

    # 将得分放在屏幕顶端

    high_score_rect = high_score_image.get_rect()

    playSurface_rect = playSurface.get_rect()

    high_score_rect.right = playSurface_rect.centerx

    high_score_rect.top = high_score_rect.top

    playSurface.blit(high_score_image, high_score_rect)


#  启动程序

if __name__ == '__main__':
    main()

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 0下一页