import pygame import random pygame.init() WIDTH, HEIGHT = 600, 400 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("贪吃蛇") WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 class Snake: def __init__(self): self.body = [(200, 200), (210, 200), (220, 200)] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) self.score = 0 def move(self): head = self.body[0] x, y = head if self.direction == UP: y -= 10 elif self.direction == DOWN: y += 10 elif self.direction == LEFT: x -= 10 elif self.direction == RIGHT: x += 10 self.body.insert(0, (x, y)) self.body.pop() def grow(self): tail = self.body[-1] x, y = tail if self.direction == UP: y += 10 elif self.direction == DOWN: y -= 10 elif self.direction == LEFT: x += 10 elif self.direction == RIGHT: x -= 10 self.body.append((x, y)) self.score += 1 def draw(self, surface): for segment in self.body: pygame.draw.rect(surface, GREEN, (segment[0], segment[1], 10, 10)) class Food: def __init__(self): self.position = (random.randint(0, (WIDTH - 10) // 10) * 10, random.randint(0, (HEIGHT - 10) // 10) * 10) def draw(self, surface): pygame.draw.rect(surface, RED, (self.position[0], self.position[1], 10, 10)) def main(): snake = Snake() food = Food() clock = pygame.time.Clock() running = True while running: WIN.fill(WHITE) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and snake.direction != DOWN: snake.direction = UP elif event.key == pygame.K_DOWN and snake.direction != UP: snake.direction = DOWN elif event.key == pygame.K_LEFT and snake.direction != RIGHT: snake.direction = LEFT elif event.key == pygame.K_RIGHT and snake.direction != LEFT: snake.direction = RIGHT head = snake.body[0] if head[0] < 0 or head[0] >= WIDTH or head[1] < 0 or head[1] >= HEIGHT: print("Game Over!") running = False snake.move() if snake.body[0] == food.position: snake.grow() food = Food() snake.draw(WIN) food.draw(WIN) pygame.display.update() clock.tick(10) pygame.quit() if __name__ == "__main__": main()
运用python编写简易贪吃蛇小游戏
最新推荐文章于 2024-08-10 10:46:00 发布