科学教育
标题:
帮我生成一个贪吃蛇代码
[打印本页]
作者:
jiang.
时间:
2025-11-4 09:49
标题:
帮我生成一个贪吃蛇代码
帮我生成一个贪吃蛇代码
作者:
kaia
时间:
2025-11-4 09:49
当我们在编写贪吃蛇游戏时,首先需要考虑游戏的基本元素,包括蛇的移动、食物的生成、游戏结束的判断等。接下来我会给你一个简单的贪吃蛇代码:
import pygame
import random
pygame.init()
# 设置屏幕大小
screen_width = 600
screen_height = 400
# 设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# 初始化屏幕
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇游戏')
# 蛇的初始位置和长度
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
# 设置速度
snake_speed = 15
clock = pygame.time.Clock()
# 定义游戏结束函数
def game_over():
font_style = pygame.font.SysFont(None, 50)
message = font_style.render('Game Over!', True, red)
screen.blit(message, [screen_width/2-100, screen_height/2-50])
pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# 检测键盘输入
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
if event.key == pygame.K_UP:
change_to = 'UP'
if event.key == pygame.K_DOWN:
change_to = 'DOWN'
# 碰撞检测
if snake_pos[0] >= screen_width or snake_pos[0] < 0 or snake_pos[1] >= screen_height or snake_pos[1] < 0:
game_over()
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
# 更新蛇的位置
if change_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
if change_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
if direction == 'RIGHT':
snake_pos[0] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
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
screen.fill(black)
for pos in snake_body:
pygame.draw.rect(screen, white, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, red, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
pygame.display.update()
clock.tick(snake_speed)
复制代码
这是一个简单的贪吃蛇小游戏的Python代码,通过上面的代码,你可以在Python的环境中执行并运行这个贪吃蛇游戏。希望对你有所帮助!
欢迎光临 科学教育 (http://www.sci-edu.net/)
Powered by Discuz! X3.2