开发者社区 > 通义灵码 > AI编码助手 > 正文

如何用python写一个贪吃蛇

如何用python写一个贪吃蛇

展开
收起
左国才 2023-11-01 13:52:36 71 0
5 条回答
写回答
取消 提交回答
  • 要用Python编写一个贪吃蛇游戏,你可以使用pygame库。以下是一个简单的贪吃蛇游戏实现:

    1. 首先,确保你已经安装了pygame库。如果没有安装,可以使用以下命令安装:
    pip install pygame
    
    1. 创建一个名为snake_game.py的文件,并将以下代码复制到文件中:
    import pygame
    import sys
    import random
    
    # 初始化pygame
    pygame.init()
    
    # 设置屏幕大小
    screen_width = 640
    screen_height = 480
    screen = pygame.display.set_mode((screen_width, screen_height))
    
    # 设置游戏速度
    clock = pygame.time.Clock()
    speed = 10
    
    # 定义蛇和食物的大小
    block_size = 20
    
    # 定义颜色
    WHITE = (255, 255, 255)
    GREEN = (0, 255, 0)
    RED = (255, 0, 0)
    
    # 蛇的初始位置
    snake_pos = [[100, 100], [80, 100], [60, 100]]
    
    # 食物的初始位置
    food_pos = [300, 300]
    
    def draw_snake(snake):
        for pos in snake:
            pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], block_size, block_size))
    
    def draw_food(food):
        pygame.draw.rect(screen, RED, pygame.Rect(food[0], food[1], block_size, block_size))
    
    def move_snake(snake, direction):
        x, y = snake[0]
        if direction == "up":
            y -= block_size
        elif direction == "down":
            y += block_size
        elif direction == "left":
            x -= block_size
        elif direction == "right":
            x += block_size
        snake.insert(0, [x, y])
        snake.pop()
    
    def check_collision(snake, food):
        if snake[0] == food:
            return True
        return False
    
    def generate_food(snake):
        while True:
            x = random.randrange(0, screen_width, block_size)
            y = random.randrange(0, screen_height, block_size)
            if [x, y] not in snake:
                return [x, y]
    
    def main():
        direction = "right"
        game_over = False
    
        while not game_over:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_over = True
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP and direction != "down":
                        direction = "up"
                    elif event.key == pygame.K_DOWN and direction != "up":
                        direction = "down"
                    elif event.key == pygame.K_LEFT and direction != "right":
                        direction = "left"
                    elif event.key == pygame.K_RIGHT and direction != "left":
                        direction = "right"
    
            move_snake(snake_pos, direction)
    
            if check_collision(snake_pos, food_pos):
                food_pos = generate_food(snake_pos)
            else:
                snake_pos.pop()
    
            screen.fill(WHITE)
            draw_snake(snake_pos)
            draw_food(food_pos)
            pygame.display.flip()
            clock.tick(speed)
    
        pygame.quit()
        sys.exit()
    
    if __name__ == "__main__":
        main()
    
    1. 运行snake_game.py文件,开始游戏:
    python snake_game.py
    

    这个简单的贪吃蛇游戏实现了基本的功能,如蛇的移动、碰撞检测和食物生成。你可以根据需要对其进行扩展和优化。

    2023-11-02 15:30:58
    赞同 展开评论 打赏
  • 通义灵码支持两种通过自然语言描述生成代码的方式:

    • 在编辑器中,直接通过注释的方式描述你需要的功能,直接在编辑器中生成代码建议,单击 Tab 可直接采纳 ;

    • 在智能问答中,直接描述你需要的功能,智能问答助手将为你生成代码建议,并支持一键插入或复制代码。比如:用python写一个贪吃蛇程序。

    image.png

    ——参考来源于阿里云官方文档。

    2023-11-02 01:04:59
    赞同 展开评论 打赏
  • 在灵码的问答面板里输入“帮我用Python写一个贪吃蛇游戏”就可以啦,如果生成的结果不满意,可以在继续提出修改要求,灵码会根据需求修改代码哦

    2023-11-01 18:31:04
    赞同 展开评论 打赏
  • 面对过去,不要迷离;面对未来,不必彷徨;活在今天,你只要把自己完全展示给别人看。

    下面是一个简单的贪吃蛇游戏的Python脚本示例,可以作为一个基本参考。这是一个简单的游戏,仅用于演示如何制作一款基础的游戏。游戏中玩家可以控制一条蛇移动并在地图上收集食物。

    1. 初始化游戏屏幕和蛇:
    import pygame
    
    pygame.init()
    
    # 设置屏幕大小
    screen_size = (800, 600)
    screen = pygame.display.set_mode(screen_size)
    
    # 设置标题
    pygame.display.set_caption("Snake")
    
    # 加载图像
    snake_img = pygame.image.load('snake.png')
    food_img = pygame.image.load('food.png')
    
    # 设置初始状态
    snake_pos = [200, 200]
    snake_speed = [1, 0]
    
    game_over = False
    
    while not game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
    
        # 按键处理
        keys_pressed = pygame.key.get_pressed()
        snake_speed[0], snake_speed[1] = 0, 0
        if keys_pressed[pygame.K_LEFT]:
            snake_speed[0] = -1
        elif keys_pressed[pygame.K_RIGHT]:
            snake_speed[0] = 1
        elif keys_pressed[pygame.K_UP]:
            snake_speed[1] = -1
        elif keys_pressed[pygame.K_DOWN]:
            snake_speed[1] = 1
    
        # 移动蛇的位置
        new_snake_pos = list(snake_pos)
        new_snake_pos[0] += snake_speed[0]
        new_snake_pos[1] += snake_speed[1]
    
        # 判断游戏结束
        if new_snake_pos[0] < 0 or new_snake_pos[0] >= screen_size[0] or new_snake_pos[1] < 0 or new_snake_pos[1] >= screen_size[1]:
            game_over = True
    
        # 更新屏幕
        screen.fill((0, 0, 0))
        screen.blit(food_img, food_pos)
        screen.blit(snake_img, new_snake_pos)
        pygame.display.update()
    
    pygame.quit()
    

    这个脚本只是一个基本的示例,实际游戏中还需要添加许多额外的功能,如食物生成、得分统计、碰撞检测等。

    2023-11-01 15:02:37
    赞同 展开评论 打赏
  • """ 贪吃蛇小游戏 """
    import random
    import sys
    import time
    import pygame
    from pygame.locals import *
    from collections import deque
    
    SCREEN_WIDTH = 600
    SCREEN_HEIGHT = 480
    SIZE = 20
    
    
    def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
        imgText = font.render(text, True, fcolor)
        screen.blit(imgText, (x, y))
    
    
    def main():
        pygame.init()
        screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption('贪吃蛇')
    
        light = (100, 100, 100)  # 蛇的颜色
        dark = (200, 200, 200)  # 食物颜色
    
        font1 = pygame.font.SysFont('SimHei', 24)  # 得分的字体
        font2 = pygame.font.Font(None, 72)  # GAME OVER 的字体
        red = (200, 30, 30)  # GAME OVER 的字体颜色
        fwidth, fheight = font2.size('GAME OVER')
        line_width = 1  # 网格线宽度
        black = (0, 0, 0)  # 网格线颜色
        bgcolor = (40, 40, 60)  # 背景色
    
        # 方向,起始向右
        pos_x = 1
        pos_y = 0
        # 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER
        # b 变量就是用于防止这种情况的发生
        b = True
        # 范围
        scope_x = (0, SCREEN_WIDTH // SIZE - 1)
        scope_y = (2, SCREEN_HEIGHT // SIZE - 1)
        # 蛇
        snake = deque()
        # 食物
        food_x = 0
        food_y = 0
    
        # 初始化蛇
        def _init_snake():
            nonlocal snake
            snake.clear()
            snake.append((2, scope_y[0]))
            snake.append((1, scope_y[0]))
            snake.append((0, scope_y[0]))
    
        # 食物
        def _create_food():
            nonlocal food_x, food_y
            food_x = random.randint(scope_x[0], scope_x[1])
            food_y = random.randint(scope_y[0], scope_y[1])
            while (food_x, food_y) in snake:
                # 为了防止食物出到蛇身上
                food_x = random.randint(scope_x[0], scope_x[1])
                food_y = random.randint(scope_y[0], scope_y[1])
    
        _init_snake()
        _create_food()
    
        game_over = True
        start = False  # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
        score = 0  # 得分
        orispeed = 0.5  # 原始速度
        speed = orispeed
        last_move_time = None
        pause = False  # 暂停
    
        while True:
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit()
                elif event.type == KEYDOWN:
                    if event.key == K_RETURN:
                        if game_over:
                            start = True
                            game_over = False
                            b = True
                            _init_snake()
                            _create_food()
                            pos_x = 1
                            pos_y = 0
                            # 得分
                            score = 0
                            last_move_time = time.time()
                    elif event.key == K_SPACE:
                        if not game_over:
                            pause = not pause
                    elif event.key in (K_w, K_UP):
                        # 这个判断是为了防止蛇向上移时按了向下键,导致直接 GAME OVER
                        if b and not pos_y:
                            pos_x = 0
                            pos_y = -1
                            b = False
                    elif event.key in (K_s, K_DOWN):
                        if b and not pos_y:
                            pos_x = 0
                            pos_y = 1
                            b = False
                    elif event.key in (K_a, K_LEFT):
                        if b and not pos_x:
                            pos_x = -1
                            pos_y = 0
                            b = False
                    elif event.key in (K_d, K_RIGHT):
                        if b and not pos_x:
                            pos_x = 1
                            pos_y = 0
                            b = False
    
            # 填充背景色
            screen.fill(bgcolor)
            # 画网格线 竖线
            for x in range(SIZE, SCREEN_WIDTH, SIZE):
                pygame.draw.line(screen, black, (x, scope_y[0] * SIZE), (x, SCREEN_HEIGHT), line_width)
            # 画网格线 横线
            for y in range(scope_y[0] * SIZE, SCREEN_HEIGHT, SIZE):
                pygame.draw.line(screen, black, (0, y), (SCREEN_WIDTH, y), line_width)
    
            if game_over:
                if start:
                    print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER',
                               red)
            else:
                curTime = time.time()
                if curTime - last_move_time > speed:
                    if not pause:
                        b = True
                        last_move_time = curTime
                        next_s = (snake[0][0] + pos_x, snake[0][1] + pos_y)
                        if next_s[0] == food_x and next_s[1] == food_y:
                            # 吃到了食物
                            _create_food()
                            snake.appendleft(next_s)
                            score += 10
                            speed = orispeed - 0.03 * (score // 100)
                        else:
                            if scope_x[0] <= next_s[0] <= scope_x[1] and scope_y[0] <= next_s[1] <= scope_y[1] \
                                    and next_s not in snake:
                                snake.appendleft(next_s)
                                snake.pop()
                            else:
                                game_over = True
    
            # 画食物
            if not game_over:
                # 避免 GAME OVER 的时候把 GAME OVER 的字给遮住了
                pygame.draw.rect(screen, light, (food_x * SIZE, food_y * SIZE, SIZE, SIZE), 0)
    
            # 画蛇
            for s in snake:
                pygame.draw.rect(screen, dark, (s[0] * SIZE + line_width, s[1] * SIZE + line_width,
                                                SIZE - line_width * 2, SIZE - line_width * 2), 0)
    
            print_text(screen, font1, 30, 7, f'速度: { 
         score // 100}')
            print_text(screen, font1, 450, 7, f'得分: { 
         score}')
    
            pygame.display.update()
    
    
    if __name__ == '__main__':
        main()
    
    2023-11-01 14:11:03
    赞同 1 展开评论 打赏
问答分类:
问答标签:

基于通义大模型的 AI 编码辅助工具,支持代码智能生成、单元测试生成、问题排查、研发智能问答等功能,为开发者带来高效、流畅的编码体验。

热门讨论

热门文章

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载