使用python 写一个贪吃蛇完整项目,蛇的长度3.苹果为1
时间: 2024-02-12 17:06:28 浏览: 26
好的,以下是一个贪吃蛇的完整项目,蛇的长度为3,每次吃到苹果会增加1,游戏结束条件为撞墙或者撞到自己。代码如下:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小和标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Snake Game")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置字体
font = pygame.font.SysFont(None, 25)
# 定义蛇的初始位置和方向
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 3
snake_x = screen_width // 2
snake_y = screen_height // 2
snake_direction = "right"
# 定义苹果的初始位置
apple_block_size = 10
apple_x = random.randrange(0, screen_width - apple_block_size, apple_block_size)
apple_y = random.randrange(0, screen_height - apple_block_size, apple_block_size)
# 定义游戏结束函数
def game_over():
game_over_text = font.render("Game Over!", True, white)
screen.blit(game_over_text, [screen_width // 2 - 50, screen_height // 2])
pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()
quit()
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != "right":
snake_direction = "left"
elif event.key == pygame.K_RIGHT and snake_direction != "left":
snake_direction = "right"
elif event.key == pygame.K_UP and snake_direction != "down":
snake_direction = "up"
elif event.key == pygame.K_DOWN and snake_direction != "up":
snake_direction = "down"
# 移动蛇
if snake_direction == "right":
snake_x += snake_block_size
elif snake_direction == "left":
snake_x -= snake_block_size
elif snake_direction == "up":
snake_y -= snake_block_size
elif snake_direction == "down":
snake_y += snake_block_size
# 判断是否吃到苹果
if snake_x == apple_x and snake_y == apple_y:
apple_x = random.randrange(0, screen_width - apple_block_size, apple_block_size)
apple_y = random.randrange(0, screen_height - apple_block_size, apple_block_size)
snake_length += 1
# 判断是否撞墙
if snake_x >= screen_width or snake_x < 0 or snake_y >= screen_height or snake_y < 0:
game_over()
# 判断是否撞到自己
head = []
head.append(snake_x)
head.append(snake_y)
snake_list.append(head)
if len(snake_list) > snake_length:
del snake_list[0]
for block in snake_list[:-1]:
if block == head:
game_over()
# 绘制游戏画面
screen.fill(black)
pygame.draw.rect(screen, red, [apple_x, apple_y, apple_block_size, apple_block_size])
for block in snake_list:
pygame.draw.rect(screen, white, [block[0], block[1], snake_block_size, snake_block_size])
pygame.display.flip()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
```
在这个项目中,先定义了一些常量和变量,包括蛇和苹果的位置和大小、游戏窗口大小、颜色等。然后在游戏循环中,处理用户输入和更新游戏状态,包括移动蛇、判断是否吃到苹果、是否撞墙或撞到自己等,最后绘制游戏画面。游戏结束后会显示 "Game Over!" 文字,并等待2秒后退出游戏。
希望这个项目能够帮助你学习 Python 和 Pygame。