import pygame
import sys
import random
SCREEN_X = 800
SCREEN_Y = 600
# 定义贪吃蛇类
class Snake:
# 初始化贪吃蛇
def __init__(self):
self.body = [(4, 3), (3, 3), (2, 3)] # 贪吃蛇身体坐标
self.direction = "right" # 贪吃蛇初始方向
self.score = 0 # 分数
# 判断贪吃蛇撞墙或自己的身体
def is_dead(self):
x, y = self.body[0]
if x < 0 or x > SCREEN_X / 10 - 1 or y < 0 or y > SCREEN_Y / 10 - 1:
return True
for i in self.body[1:]:
if i == (x, y):
return True
return False
# 判断贪吃蛇是否吃到食物
def is_eat_food(self, food):
if self.body[0] == food:
self.score += 10
self.body.insert(0, food)
return True
return False
# 绘制贪吃蛇
def draw(self, screen):
for x, y in self.body:
rect = pygame.Rect(x * 10, y * 10, 10, 10)
pygame.draw.rect(screen, (255, 255, 255), rect)
# 移动贪吃蛇
def move(self):
x, y = self.body[0]
if self.direction == "right":
x += 1
elif self.direction == "left":
x -= 1
elif self.direction == "up":
y -= 1
elif self.direction == "down":
y += 1
self.body.pop()
self.body.insert(0, (x, y))
# 控制贪吃蛇方向
def control_direction(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and self.direction != "right":
self.direction = "left"
elif event.key == pygame.K_RIGHT and self.direction != "left":
self.direction = "right"
elif event.key == pygame.K_UP and self.direction != "down":
self.direction = "up"
elif event.key == pygame.K_DOWN and self.direction != "up":
self.direction = "down"
# 定义食物类
class Food:
# 初始化食物
def __init__(self):
self.pos = (0, 0) # 食物位置
self.color = (0, 255, 0) # 食物颜色
# 随机生成食物
def generate(self, snake):
while True:
x = random.randint(0, SCREEN_X / 10 - 1)
y = random.randint(0, SCREEN_Y / 10 - 1)
if (x, y) not in snake.body:
self.pos = (x, y)
break
# 绘制食物
def draw(self, screen):
rect = pygame.Rect(self.pos[0] * 10, self.pos[1] * 10, 10, 10)
pygame.draw.rect(screen, self.color, rect)
# 游戏主函数
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
snake = Snake()
food = Food()
food.generate(snake)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
snake.control_direction(event)
# 移动贪吃蛇并判断是否死亡或吃到食物
snake.move()
if snake.is_dead():
pygame.quit()
sys.exit()
if snake.is_eat_food(food.pos):
food.generate(snake)
# 绘制游戏界面
screen.fill((0, 0, 0))
snake.draw(screen)
food.draw(screen)
pygame.display.update()
# 控制游戏速度
clock.tick(15)
if __name__ == "__main__":
main()
Pygame制作贪吃蛇
最新推荐文章于 2024-09-07 17:46:09 发布