使用pygame建立基本简单的贪吃蛇游戏

创建一个基本的贪吃蛇游戏涉及到几个关键的步骤:初始化游戏环境、创建蛇和食物、处理用户输入、更新游戏状态以及检测游戏结束条件。

import pygame
import sys
import random
import time

# 初始化pygame
pygame.init()

# 设置屏幕大小
width, height = 600, 400
screen = pygame.display.set_mode((width, height))

# 颜色定义
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 蛇初始设置
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
direction = "RIGHT"
change_to = direction

# 食物
food_pos = [random.randrange(1, (width//10)) * 10, random.randrange(1, (height//10)) * 10]
food_spawn = True

# 游戏循环标志
running = True

# 分数
score = 0

# 设置时钟
clock = pygame.time.Clock()

# 游戏速度
speed = 10

def game_over():
    my_font = pygame.font.SysFont('times new roman', 90)
    go_surface = my_font.render('Your Score is : ' + str(score), True, RED)
    go_rect = go_surface.get_rect()
    go_rect.midtop = (width/2, height/4)
    screen.blit(go_surface, go_rect)
    pygame.display.flip()
    time.sleep(3)
    pygame.quit()
    sys.exit()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key ==

你可能感兴趣的:(pygame,python)