帮我用Python 写一个贪吃蛇大作战游戏
时间: 2023-05-22 21:02:19 浏览: 99
当然可以,以下是一个简单的贪吃蛇大作战游戏的 Python 代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇大作战")
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)]
self.direction = "right"
def move(self):
if self.direction == "right":
new_head = (self.body[0][0] + 10, self.body[0][1])
elif self.direction == "left":
new_head = (self.body[0][0] - 10, self.body[0][1])
elif self.direction == "up":
new_head = (self.body[0][0], self.body[0][1] - 10)
elif self.direction == "down":
new_head = (self.body[0][0], self.body[0][1] + 10)
self.body.insert(0, new_head)
self.body.pop()
def draw(self):
for i, segment in enumerate(self.body):
if i == 0:
pygame.draw.rect(window, GREEN, (segment[0], segment[1], 10, 10))
else:
pygame.draw.rect(window, BLUE, (segment[0], segment[1], 10, 10))
# 定义食物类
class Food:
def __init__(self):
self.position = (random.randint(0, WINDOW_WIDTH // 10 - 1) * 10, random.randint(0, WINDOW_HEIGHT // 10 - 1) * 10)
def draw(self):
pygame.draw.rect(window, RED, (self.position[0], self.position[1], 10, 10))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT and snake.direction != "left":
snake.direction = "right"
elif event.key == pygame.K_LEFT and snake.direction != "right":
snake.direction = "left"
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"
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == food.position:
snake.body.append(snake.body[-1])
food = Food()
# 绘制游戏界面
window.fill(BLACK)
snake.draw()
food.draw()
pygame.display.update()
```
希望这个代码能够帮到你!
阅读全文