写一个贪吃蛇小游戏代码
时间: 2024-01-06 17:07:07 浏览: 79
以下是Python语言的贪吃蛇小游戏代码:
```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("贪吃蛇小游戏")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 定义方向
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# 定义蛇类
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
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)), (cur[1] + (y*10)))
if 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])
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), random.randint(0, screen_height - 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()
# 设置游戏时钟
clock = pygame.time.Clock()
# 游戏循环
while True:
# 处理键盘事件
snake.handle_keys()
# 移动蛇和检测碰撞
snake.move()
if snake.get_head_position() == food.position:
snake.length += 1
food.randomize_position()
snake.draw(screen)
food.draw(screen)
# 刷新屏幕
pygame.display.update()
# 设置帧率
clock.tick(15)
# 退出pygame
pygame.quit()
```
这是一个基本的贪吃蛇游戏,包括蛇类、食物类、处理键盘事件、移动蛇、检测碰撞等各种功能。你可以根据自己的需要添加更多的特性,比如:增加游戏难度、计分、排行榜等等。
阅读全文