Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

请给我写一段完整的贪吃蛇游戏代码

  1. User

    请给我写一段完整的贪吃蛇游戏代码

  2. Assistant

    以下是一段用Python语言编写的简单贪吃蛇游戏代码:

    import pygame
    import time
    import random
    
    # 初始化
    pygame.init()
    
    # 定义颜色
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    
    # 设置游戏窗口尺寸
    window_width = 800
    window_height = 600
    dis = pygame.display.set_mode((window_width, window_height))
    pygame.display.set_caption('贪吃蛇')
    
    # 设置游戏速度
    clock = pygame.time.Clock()
    snake_block = 20
    snake_speed = 20
    
    # 字体设置
    font_style = pygame.font.SysFont(None, 50)
    score_font = pygame.font.SysFont(None, 35)
    
    # 显示分数
    def Your_score(score):
        value = score_font.render("Your Score: " + str(score), True, BLACK)
        dis.blit(value, [0, 0])
    
    # 绘制蛇
    def our_snake(snake_block, snake_list):
        for x in snake_list:
            pygame.draw.rect(dis, GREEN, [x[0], x[1], snake_block, snake_block])
    
    # 显示消息
    def message(msg, color):
        mesg = font_style.render(msg, True, color)
        dis.blit(mesg, [window_width / 6, window_height / 3])
    
    # 游戏主循环
    def gameLoop():
        game_over = False
        game_close = False
    
        # 设置蛇的初始位置和长度
        x1 = window_width / 2 - snake_block
        y1 = window_height / 2 - snake_block
        x1_change = 0
        y1_change = 0
        snake_List = []
        Length_of_snake = 1
    
        # 设置食物的初始位置
        foodx = round(random.randrange(0, window_width - snake_block) / 20.0) * 20.0
        foody = round(random.randrange(0, window_height - snake_block) / 20.0) * 20.0
    
        while not game_over:
    
            while game_close == True:
                dis.fill(WHITE)
                message("You Lost! Press Q-Quit or C-Play Again", RED)
                Your_score(Length_of_snake - 1)
                pygame.display.update()
    
                # 游戏重新开始或退出
                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_q:
                            game_over = True
                            game_close = False
                        if event.key == pygame.K_c:
                            gameLoop()
    
            # 控制蛇的移动
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_over = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        x1_change = -snake_block
                        y1_change = 0
                    elif event.key == pygame.K_RIGHT:
                        x1_change = snake_block
                        y1_change = 0
                    elif event.key == pygame.K_UP:
                        y1_change = -snake_block
                        x1_change = 0
                    elif event.key == pygame.K_DOWN:
                        y1_change = snake_block
                        x1_change = 0
    
            # 控制蛇不能超出边界
            if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
                game_close = True
    
            x1 += x1_change
            y1 += y1_change
            dis.fill(WHITE)
            pygame.draw.rect(dis, BLUE, [foodx, foody, snake_block, snake_block])
            snake_Head = []
            snake_Head.append(x1)
            snake_Head.append(y1)
            snake_List.append(snake_Head)
            if len(snake_List) > Length_of_snake:
                del snake_List[0]
    
            # 控制蛇撞到自己时游戏结束
            for x in snake_List[:-1]:
                if x == snake_Head:
                    game_close = True
    
            our_snake(snake_block, snake_List)
            Your_score(Length_of_snake - 1)
    
            pygame.display.update()
    
            # 控制蛇吃到了食物后的处理
            if x1 == foodx and y1 == foody:
                foodx = round(random.randrange(0, window_width - snake_block) / 20.0) * 20.0
                foody = round(random.randrange(0, window_height - snake_block) / 20.0) * 20.0
                Length_of_snake += 1
    
            # 控制游戏速度
            clock.tick(snake_speed)
    
        pygame.quit()
    
    # 运行游戏
    gameLoop()
    

    运行以上代码后,便可以在Pygame窗口中体验到贪吃蛇游戏了。

  3. User

    运行以上代码

  4. Assistant

    很抱歉,由于使用文本交互,无法直接运行上述代码。建议将代码复制到Python编辑器中,保存为.py文件,然后运行该文件。确保你已经安装了Pygame库。如果没有安装,可以使用以下命令进行安装:

    pip install pygame
    

    安装完成后,即可运行代码并开始游戏。希望你能享受到贪吃蛇游戏带来的乐趣!

  5. User

    安装pip install pygame

  6. Assistant

    如果你已经安装了Python并且已经在环境变量中配置了Python路径,那么可以按照以下步骤安装Pygame库:

    1. 打开命令行窗口(Windows用户可以按下Win键,然后输入cmd并按回车键打开命令提示符)。

    2. 在命令行中输入以下命令:

      pip install pygame
      

      如果你使用的是Python 3,应该使用pip3而不是pip来安装库。命令应该是pip3 install pygame。

    3. 按下回车键执行命令后,pip会自动下载并安装Pygame库及其依赖项。等待安装完成。

    安装完成后,你可以尝试运行之前的代码。如果一切顺利,你应该能够享受到贪吃蛇游戏的乐趣了。祝你玩得愉快!