import pygame
import random
# 初始化 pygame
pygame.init()
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 创建游戏窗口
game_display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('贪吃蛇游戏')
# 贪吃蛇类
class Snake:
def __init__(self):
self.length = 1
self.positions = [((WINDOW_WIDTH / 2), (WINDOW_HEIGHT / 2))]
self.direction = "RIGHT"
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def turn(self, direction):
if direction == "RIGHT" and not self.direction == "LEFT":
self.direction = direction
if direction == "LEFT" and not self.direction == "RIGHT":
self.direction = direction
if direction == "UP" and not self.direction == "DOWN":
self.direction = direction
if direction == "DOWN" and not self.direction == "UP":
self.direction = direction
def move(self):
cur = self.get_head_position()
x, y = cur
if self.direction == "RIGHT":
x += 20
if self.direction == "LEFT":
x -= 20
if self.direction == "UP":
y -= 20
if self.direction == "DOWN":
y += 20
self.positions.insert(0, (x, y))
if len(self.positions) > self.length:
self.positions.pop()
def eat(self):
self.length += 1
def draw(self, surface):
for p in self.positions:
pygame.draw.rect(surface, self.color, pygame.Rect(p[0], p[1], 20, 20))
# 食物类
class Food:
def __init__(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, (WINDOW_WIDTH - 20) // 20) * 20, random.randint(0, (WINDOW_HEIGHT - 20) // 20) * 20)
def draw(self, surface):
pygame.draw.rect(surface, self.color, pygame.Rect(self.position[0], self.position[1], 20, 20))
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:
snake.turn("RIGHT")
if event.key == pygame.K_LEFT:
snake.turn("LEFT")
if event.key == pygame.K_UP:
snake.turn("UP")
if event.key == pygame.K_DOWN:
snake.turn("DOWN")
snake.move()
head = snake.get_head_position()
if head[0] < 0 or head[0] >= WINDOW_WIDTH or head[1] < 0 or head[1] >= WINDOW_HEIGHT:
pygame.quit()
quit()
if head == food.position:
snake.eat()
food.randomize_position()
game_display.fill(BLACK)
snake.draw(game_display)
food.draw(game_display)
pygame.display.flip()
clock.tick(10)
if __name__ == "__main__":
main()