aiaiask.com©

开花即结果 提问即答案

贪吃蛇游戏代码
原始问题:

贪吃蛇游戏代码

贪吃蛇游戏代码如下:

import pygame
import sys
import random

pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)

# 设置蛇的初始位置
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]

# 设置食物的初始位置
food_pos = [random.randrange(1, screen_width // 10) * 10, random.randrange(1, screen_height // 10) * 10]
food_spawn = True

# 设置方向
direction = "RIGHT"
change_to = direction

# 设置速度
speed = 15
clock = pygame.time.Clock()

# 设置字体
font = pygame.font.SysFont("arial", 25)

def game_over():
    msg = font.render("Game Over!", True, red)
    screen.blit(msg, [screen_width // 2 - 50, screen_height // 2 - 25])
    pygame.display.flip()
    pygame.time.wait(2000)
    pygame.quit()
    sys.exit()

while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                change_to = "UP"
            if event.key == pygame.K_DOWN:
                change_to = "DOWN"
            if event.key == pygame.K_LEFT:
                change_to = "LEFT"
            if event.key == pygame.K_RIGHT:
                change_to = "RIGHT"

    if change_to == "UP" and direction != "DOWN":
        direction = "UP"
    if change_to == "DOWN" and direction != "UP":
        direction = "DOWN"
    if change_to == "LEFT" and direction != "RIGHT":
        direction = "LEFT"
    if change_to == "RIGHT" and direction != "LEFT":
        direction = "RIGHT"

    if direction == "UP":
        snake_pos[1] -= speed
    if direction == "DOWN":
        snake_pos[1] += speed
    if direction == "LEFT":
        snake_pos[0] -= speed
    if direction == "RIGHT":
        snake_pos[0] += speed

    snake_body.insert(0, list(snake_pos))
    if snake_pos == food_pos:
        food_spawn = False
    else:
        snake_body.pop()

    if not food_spawn:
        food_pos = [random.randrange(1, screen_width // 10) * 10, random.randrange(1, screen_height // 10) * 10]
        food_spawn = True
        snake_body.append(list(snake_pos))

    screen.fill(black)
    for pos in snake_body:
        pygame.draw.rect(screen, green, pygame.Rect(pos[0], pos[1], 10, 10))

    pygame.draw.rect(screen, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

    if snake_pos[0] >= screen_width or snake_pos[0] < 0 or snake_pos[1] >= screen_height or snake_pos[1] < 0:
        game_over()
贪吃蛇游戏代码
https://www.aiaiask.com/ask/46816.html
AI / 模型iFLYTEK
时间 / DATESeptember 10, 2023, 6:09 PM
语言zh-CN
IP / 区域重庆市重庆市