自运行贪吃蛇AI
'''
@File : 0.py
@Author: BC
@Date : 2023-04-20 17:20
贪吃蛇AI
'''
import pygame
import random
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
class Snake:
def __init__(self):
self.x = screen_width / 2
self.y = screen_height / 2
self.width = 20
self.height = 20
self.color = white
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.body = [(self.x, self.y)]
self.score = 0
def move(self):
if self.direction == UP:
self.y -= self.height
elif self.direction == DOWN:
self.y += self.height
elif self.direction == LEFT:
self.x -= self.width
elif self.direction == RIGHT:
self.x += self.width
if self.body[0] == food.position:
food.reset()
self.score += 1
self.body.insert(0, (self.x, self.y))
else:
self.body.insert(0, (self.x, self.y))
self.body.pop()
if self.x < 0 or self.x > screen_width - self.width or \
self.y < 0 or self.y > screen_height - self.height or \
self.body[0] in self.body[1:]:
pygame.quit()
quit()
def decision(self):
head_x, head_y = self.body[0]
food_x, food_y = food.position
if food_x < head_x:
self.direction = LEFT
elif food_x > head_x:
self.direction = RIGHT
elif food_y < head_y:
self.direction = UP
elif food_y > head_y:
self.direction = DOWN
def draw(self):
for pos in self.body:
pygame.draw.rect(screen, self.color, (pos[0], pos[1], self.width, self.height))
class Food:
def __init__(self):
self.width = 20
self.height = 20
self.color = red
self.reset()
def reset(self):
self.position = (random.randint(0, (screen_width - self.width) / self.width) * self.width,
random.randint(0, (screen_height - self.height) / self.height) * self.height)
def draw(self):
pygame.draw.rect(screen, self.color, (self.position[0], self.position[1], self.width, self.height))
snake = Snake()
food = Food()
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
snake.decision()
snake.move()
screen.fill(black)
snake.draw()
food.draw()
pygame.display.update()
clock.tick(10)