给出贪食蛇游戏的python代码
时间: 2023-07-23 10:38:45 浏览: 113
好的,以下是一个简单的贪食蛇游戏的Python代码,供参考:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 设置屏幕大小
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Snake Game")
# 定义贪食蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [(random.randint(0, 39) * 10, random.randint(0, 29) * 10)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_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 = [(random.randint(0, 39) * 10, random.randint(0, 29) * 10)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_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()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
elif 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, 39) * 10, random.randint(0, 29) * 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:
screen.fill(WHITE)
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(20)
```
这个游戏实现了贪食蛇的基本功能,包括蛇的移动、吃食物、重新开始等。你可以根据需要对代码进行修改和优化。
阅读全文