t贪吃蛇小游戏代码python
时间: 2023-09-05 13:06:48 浏览: 100
以下是一个简单的贪吃蛇小游戏的 Python 代码示例:
```python
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义方向常量
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 初始化 pygame
pygame.init()
# 设置窗口大小和标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇小游戏")
# 设置时钟
clock = pygame.time.Clock()
# 加载字体
font = pygame.font.SysFont(None, 25)
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [((screen_width / 2), (screen_height / 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
self.score = 0
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = (((cur[0] + (x * 10)) % screen_width), (cur[1] + (y * 10)) % screen_height)
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [((screen_width / 2), (screen_height / 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.score = 0
def draw(self, surface):
for p in self.positions:
r = pygame.Rect((p[0], p[1]), (10, 10))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
def handle_keys(self):
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:
self.turn((0, -1))
elif event.key == pygame.K_DOWN:
self.turn((0, 1))
elif event.key == pygame.K_LEFT:
self.turn((-1, 0))
elif event.key == pygame.K_RIGHT:
self.turn((1, 0))
# 定义食物类
class Food:
def __init__(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, screen_width // 10 - 1) * 10, random.randint(0, screen_height // 10 - 1) * 10)
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (10, 10))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理事件
snake.handle_keys()
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.get_head_position() == food.position:
snake.length += 1
snake.score += 1
food.randomize_position()
# 绘制游戏界面
screen.fill(WHITE)
snake.draw(screen)
food.draw(screen)
text = font.render("Score: " + str(snake.score), True, BLACK)
screen.blit(text, (5, 10))
pygame.display.update()
# 控制帧率
clock.tick(10)
```
这个示例代码使用 Pygame 模块进行游戏开发,实现了基本的贪吃蛇小游戏功能。你可以根据需要进行修改和扩展。
阅读全文