给出贪食蛇的python代码
时间: 2023-07-23 08:38:39 浏览: 84
贪吃蛇python代码
以下是一个简单的贪食蛇Python代码示例,使用的是Pygame库实现图形界面:
```python
import pygame
import random
# 定义常量
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_SIZE = 10
SNAKE_COLOR = (0, 255, 0)
FOOD_COLOR = (255, 0, 0)
# 初始化Pygame
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪食蛇")
# 定义贪食蛇类
class Snake:
def __init__(self):
self.body = [(4, 3), (3, 3), (2, 3)]
self.direction = "right"
def move(self):
head = self.body[0]
if self.direction == "right":
new_head = (head[0] + 1, head[1])
elif self.direction == "left":
new_head = (head[0] - 1, head[1])
elif self.direction == "up":
new_head = (head[0], head[1] - 1)
elif self.direction == "down":
new_head = (head[0], head[1] + 1)
self.body.insert(0, new_head)
self.body.pop()
def turn(self, direction):
self.direction = direction
def eat_food(self):
tail = self.body[-1]
self.body.append(tail)
# 定义食物类
class Food:
def __init__(self):
self.pos = (0, 0)
self.spawn_food()
def spawn_food(self):
x = random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE
y = random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE
self.pos = (x, y)
# 定义游戏主循环
def main():
clock = pygame.time.Clock()
snake = Snake()
food = Food()
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_RIGHT and snake.direction != "left":
snake.turn("right")
elif event.key == pygame.K_LEFT and snake.direction != "right":
snake.turn("left")
elif event.key == pygame.K_UP and snake.direction != "down":
snake.turn("up")
elif event.key == pygame.K_DOWN and snake.direction != "up":
snake.turn("down")
# 移动贪食蛇
snake.move()
# 判断是否吃到食物
if snake.body[0] == food.pos:
snake.eat_food()
food.spawn_food()
# 绘制背景
screen.fill((0, 0, 0))
# 绘制贪食蛇
for segment in snake.body:
pygame.draw.rect(screen, SNAKE_COLOR, (segment[0] * GRID_SIZE, segment[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))
# 绘制食物
pygame.draw.rect(screen, FOOD_COLOR, (food.pos[0], food.pos[1], GRID_SIZE, GRID_SIZE))
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(10)
# 运行游戏
if __name__ == "__main__":
main()
```
在运行代码前,需要先安装Pygame库。可以使用以下命令进行安装:
```
pip install pygame
```
运行代码后,按方向键控制贪食蛇的移动,尽量吃到食物。注意,以上代码仅供参考,实际开发中可能需要进行更多的调整和优化。
阅读全文