猫史档案馆


python贪吃蛇游戏

用户:FreeWorldFreeWorld查看:0 回复:0 评论:0 创建时间:2024-07-19T17:54:55


python贪吃蛇游戏

使用的库:pygame , time , random 。

代码如下:

import pygame 
import random
import time

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


# 定义游戏窗口大小
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600

# 定义游戏对象
class Snake:
    def __init__(self):
        self.x = WINDOW_WIDTH / 2
        self.y = WINDOW_HEIGHT / 2
        self.body = [[self.x, self.y], [self.x - 10, self.y], [self.x - 20, self.y]]
        self.direction = "RIGHT"
        self.score = 0

    def move(self):
        # 移动蛇头
        if self.direction == "RIGHT":
            self.x += 10
        elif self.direction == "LEFT":
            self.x -= 10
        elif self.direction == "UP":
            self.y -= 10
        elif self.direction == "DOWN":
            self.y += 10

        # 移动蛇身
        for i in range(len(self.body) - 1, 0, -1):
            self.body[i][0] = self.body[i - 1][0]
            self.body[i][1] = self.body[i - 1][1]

        self.body[0][0] = self.x
        self.body[0][1] = self.y

    def change_direction(self, new_direction):
        if new_direction != self.opposite_direction():
            self.direction = new_direction

    def opposite_direction(self):
        if self.direction == "RIGHT":
            return "LEFT"
        elif self.direction == "LEFT":
            return "RIGHT"
        elif self.direction == "UP":
            return "DOWN"
        elif self.direction == "DOWN":
            return "UP"

    def eat_food(self, food):
        if self.body[0][0] == food.x and self.body[0][1] == food.y:
            self.score += 1
            return True
        else:
            return False

    def collide_with_self(self):
        for i in range(3, len(self.body)):
            if self.body[0][0] == self.body[i][0] and self.body[0][1] == self.body[i][1]:
                return True
        return False

    def collide_with_wall(self):
        if self.x < 0 or self.x > WINDOW_WIDTH - 10 or self.y < 0 or self.y > WINDOW_HEIGHT - 10:
            return True
        else:
            return False


class Food:
    def __init__(self):
        self.x = random.randint(0, WINDOW_WIDTH - 10)
        self.y = random.randint(0, WINDOW_HEIGHT - 10)

    def draw(self, window):
        pygame.draw.rect(window, RED, (self.x, self.y, 10, 10))


# 定义游戏窗口
pygame.init()
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")


# 实例化游戏对象
snake = Snake()
food = Food()

# 主循环
while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake.change_direction("UP")
            elif event.key == pygame.K_DOWN:
                snake.change_direction("DOWN")
            elif event.key == pygame.K_LEFT:
                snake.change_direction("LEFT")
            elif event.key == pygame.K_RIGHT:
                snake.change_direction("RIGHT")

    # 绘制背景
    window.fill(BLACK)

    # 绘制蛇
    for coord in snake.body:
        pygame.draw.rect(window, GREEN, (coord[0], coord[1], 10, 10))

    # 绘制食物
    food.draw(window)

    # 移动蛇
    snake.move()

    # 吃食物
    if snake.eat_food(food):
        food = Food()

    # 碰撞检测
    if snake.collide_with_self() or snake.collide_with_wall():
        game_over = True
        break



    # 显示分数
    font = pygame.font.Font(None, 36)
    text = font.render("Score: " + str(snake.score), True, WHITE)
    window.blit(text, (WINDOW_WIDTH - 100, 10))

    # 刷新窗口
    pygame.display.update()

    # 控制游戏速度
    time.sleep(0.1)

# 游戏结束画面
while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    # 绘制背景
    window.fill(BLACK)

    # 绘制游戏结束画面
    font = pygame.font.Font(None, 72)
    text = font.render("Game Over!", True, WHITE)
    window.blit(text, (WINDOW_WIDTH / 2 - text.get_width() / 2, WINDOW_HEIGHT / 2 - text.get_height() / 2))

    # 显示分数
    font = pygame.font.Font(None, 36)
    text = font.render("Score: " + str(snake.score), True, WHITE)
    window.blit(text, (WINDOW_WIDTH / 2 - text.get_width() / 2, WINDOW_HEIGHT / 2 + text.get_height() / 2))

    # 刷新窗口
    pygame.display.update()

    # 控制游戏速度
    time.sleep(2)


    # 退出游戏    
    pygame.quit()
    exit()


回复

上一页1 页 / 共 0下一页