好的,以下是一个简单的贪吃蛇游戏,使用Python和Pygame库实现:
- import pygame
- import random
- # 初始化 Pygame 库
- pygame.init()
- # 定义窗口大小和游戏区域大小
- WINDOW_WIDTH = 600
- WINDOW_HEIGHT = 400
- CELL_SIZE = 20
- GRID_WIDTH = WINDOW_WIDTH // CELL_SIZE
- GRID_HEIGHT = WINDOW_HEIGHT // CELL_SIZE
- # 定义颜色
- BLACK = (0, 0, 0)
- WHITE = (255, 255, 255)
- RED = (255, 0, 0)
- GREEN = (0, 255, 0)
- # 创建窗口
- window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
- pygame.display.set_caption('贪吃蛇')
- # 定义贪吃蛇类
- class Snake:
- def __init__(self):
- self.body = [(2, 0), (1, 0), (0, 0)]
- self.direction = 'RIGHT'
- def move(self):
- head = self.body[0]
- if self.direction == 'UP':
- new_head = (head[0], head[1] - 1)
- elif self.direction == 'DOWN':
- new_head = (head[0], head[1] + 1)
- elif self.direction == 'LEFT':
- new_head = (head[0] - 1, head[1])
- elif self.direction == 'RIGHT':
- new_head = (head[0] + 1, head[1])
- self.body.insert(0, new_head)
- self.body.pop()
- def grow(self):
- tail = self.body[-1]
- x = tail[0]
- y = tail[1]
- if self.direction == 'UP':
- new_tail = (x, y + 1)
- elif self.direction == 'DOWN':
- new_tail = (x, y - 1)
- elif self.direction == 'LEFT':
- new_tail = (x + 1, y)
- elif self.direction == 'RIGHT':
- new_tail = (x - 1, y)
- self.body.append(new_tail)
- def draw(self):
- for cell in self.body:
- x = cell[0] * CELL_SIZE
- y = cell[1] * CELL_SIZE
- pygame.draw.rect(window, GREEN, (x, y, CELL_SIZE, CELL_SIZE))
- # 定义食物类
- class Food:
- def __init__(self):
- self.x = random.randint(0, GRID_WIDTH - 1)
- self.y = random.randint(0, GRID_HEIGHT - 1)
- def draw(self):
- x = self.x * CELL_SIZE
- y = self.y * CELL_SIZE
- pygame.draw.rect(window, RED, (x, y, CELL_SIZE, CELL_SIZE))
- # 创建贪吃蛇和食物对象
- snake = Snake()
- food = Food()
- # 游戏主循环
- clock = pygame.time.Clock()
- score = 0
- while True:
- # 处理事件
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- quit()
- elif event.type == pygame.KEYDOWN:
- if 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'
- elif 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'
- # 移动贪吃蛇
- snake.move()
- # 判断是否吃到食物
- if snake.body[0] == (food.x, food.y):
- snake.grow()
- food = Food()
- score += 1
- # 判断是否撞墙或者自己的身体
- head = snake.body[0]
- if head[0] < 0 or head[0] >= GRID_WIDTH or head[1] < 0 or head[1] >= GRID_HEIGHT:
- pygame.quit()
- quit()
- for cell in snake.body[1:]:
- if cell == head:
- pygame.quit()
- quit()
- # 清空窗口
- window.fill(BLACK)
- # 绘制贪吃蛇和食物
- snake.draw()
- food.draw()
- # 显示分数
- font = pygame.font.SysFont(None, 25)
- text = font.render('Score: {}'.format(score), True, WHITE)
- window.blit(text, (10, 10))
- # 刷新窗口
- pygame.display.update()
- # 控制游戏速度
- clock.tick(10)
复制代码
这个贪吃蛇游戏还比较简单,可以根据需要进行修改和优化。 |