一份贪吃蛇Python源码

import pygame
import random

# 初始化 Pygame 库
pygame.init()

# 游戏窗口尺寸
window_width = 640
window_height = 480

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

# 设置游戏窗口的尺寸
game_display = pygame.display.set_mode((window_width, window_height))

# 设置游戏标题
pygame.display.set_caption('Greedy Snake')

# 设置游戏的帧率
clock = pygame.time.Clock()

# 定义贪吃蛇的尺寸和速度
snake_block_size = 10
snake_speed = 15

# 设置字体和字号
font_style = pygame.font.SysFont(None, 30)

# 定义显示提示消息的函数
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    game_display.blit(mesg, [window_width/6, window_height/3])

# 定义主函数
def gameLoop():
    game_exit = False
    game_over = False
 
    # 贪吃蛇的初始位置
    x1 = window_width / 2
    y1 = window_height / 2
 
    # 贪吃蛇的初始移动方向
    x1_change = 0       
    y1_change = 0

    # 食物的初始位置
    foodx = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
    foody = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0

    while not game_exit:
        while game_over == True:
            game_display.fill(white)
            message("Game over, press Q-Quit or C-Play Again", red)
            pygame.display.update()
 
            # 判断玩家是否要继续游戏
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_exit = True
                        game_over = False
                    if event.key == pygame.K_c:
                        gameLoop()

        # 处理玩家的操作
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block_size
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block_size
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block_size
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block_size
                    x1_change = 0
 
        # 判断贪吃蛇是否碰到了边界
        if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
            game_over

 

© 版权声明
THE END
喜欢就支持一下吧
点赞27赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容