贪吃蛇编程源码是什么样的

fiy 其他 7

回复

共3条回复 我来回复
  • 不及物动词的头像
    不及物动词
    这个人很懒,什么都没有留下~
    评论

    贪吃蛇是一款经典的游戏,可以用编程语言来实现。下面是一个简单的贪吃蛇编程源码示例:

    #include <iostream>
    #include <conio.h>
    #include <windows.h>
    
    using namespace std;
    
    bool gameover;
    const int width = 20;
    const int height = 20;
    int x, y, fruitX, fruitY, score;
    int tailX[100], tailY[100];
    int nTail;
    enum eDirecton { STOP = 0, LEFT, RIGHT, UP, DOWN};
    eDirecton dir;
    
    void Setup()
    {
        gameover = false;
        dir = STOP;
        x = width / 2;
        y = height / 2;
        fruitX = rand() % width;
        fruitY = rand() % height;
        score = 0;
    }
    
    void Draw()
    {
        system("cls");
        for (int i = 0; i < width+2; i++)
            cout << "#";
        cout << endl;
    
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                if (j == 0)
                    cout << "#";
                if (i == y && j == x)
                    cout << "O";
                else if (i == fruitY && j == fruitX)
                    cout << "F";
                else
                {
                    bool printTail = false;
                    for (int k = 0; k < nTail; k++)
                    {
                        if (tailX[k] == j && tailY[k] == i)
                        {
                            cout << "o";
                            printTail = true;
                        }
                    }
                    if (!printTail)
                        cout << " ";
                }
    
                if (j == width - 1)
                    cout << "#";
            }
            cout << endl;
        }
    
        for (int i = 0; i < width+2; i++)
            cout << "#";
        cout << endl;
        cout << "Score:" << score << endl;
    }
    
    void Input()
    {
        if (_kbhit())
        {
            switch (_getch())
            {
                case 'a':
                    dir = LEFT;
                    break;
                case 'd':
                    dir = RIGHT;
                    break;
                case 'w':
                    dir = UP;
                    break;
                case 's':
                    dir = DOWN;
                    break;
                case 'x':
                    gameover = true;
                    break;
            }
        }
    }
    
    void Logic()
    {
        int prevX = tailX[0];
        int prevY = tailY[0];
        int prev2X, prev2Y;
        tailX[0] = x;
        tailY[0] = y;
        for (int i = 1; i < nTail; i++)
        {
            prev2X = tailX[i];
            prev2Y = tailY[i];
            tailX[i] = prevX;
            tailY[i] = prevY;
            prevX = prev2X;
            prevY = prev2Y;
        }
        switch (dir)
        {
            case LEFT:
                x--;
                break;
            case RIGHT:
                x++;
                break;
            case UP:
                y--;
                break;
            case DOWN:
                y++;
                break;
        }
    
        if (x >= width)
            x = 0;
        else if (x < 0)
            x = width - 1;
    
        if (y >= height)
            y = 0;
        else if (y < 0)
            y = height - 1;
    
        for (int i = 0; i < nTail; i++)
        {
            if (tailX[i] == x && tailY[i] == y)
                gameover = true;
        }
    
        if (x == fruitX && y == fruitY)
        {
            score += 10;
            fruitX = rand() % width;
            fruitY = rand() % height;
            nTail++;
        }
    }
    
    int main()
    {
        Setup();
        while (!gameover)
        {
            Draw();
            Input();
            Logic();
            Sleep(10);
        }
        return 0;
    }
    

    这段代码使用C++编写,并调用了Windows API来实现一些功能,比如清屏和延时。游戏的主要逻辑包括初始化游戏设置,绘制游戏界面,获取玩家输入,更新游戏状态等。通过不断刷新界面和监听玩家输入,实现了贪吃蛇游戏的基本功能。你可以根据自己的需求对源码进行修改和扩展。

    1年前 0条评论
  • fiy的头像
    fiy
    Worktile&PingCode市场小伙伴
    评论

    贪吃蛇是一款经典的游戏,在编程中也经常被用作练手的项目。下面是一个简单的贪吃蛇游戏的编程源码示例:

    import pygame
    import random
    
    # 初始化游戏
    pygame.init()
    
    # 设置游戏窗口的尺寸
    width = 640
    height = 480
    window = pygame.display.set_mode((width, height))
    
    # 设置游戏窗口的标题
    pygame.display.set_caption("贪吃蛇游戏")
    
    # 定义颜色
    white = (255, 255, 255)
    black = (0, 0, 0)
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)
    
    # 设置游戏时钟
    clock = pygame.time.Clock()
    
    # 设置贪吃蛇的初始位置和移动速度
    snake_size = 10
    snake_speed = 15
    
    # 定义贪吃蛇的移动方向
    direction = "right"
    
    # 定义贪吃蛇的初始位置和长度
    snake_x = 50
    snake_y = 50
    snake_body = []
    snake_length = 1
    
    # 定义食物的初始位置
    food_x = random.randint(0, width - 10)
    food_y = random.randint(0, height - 10)
    
    # 定义分数
    score = 0
    
    # 定义游戏结束的标志
    game_over = False
    
    # 定义函数,用于绘制贪吃蛇
    def draw_snake(snake_body):
        for x, y in snake_body:
            pygame.draw.rect(window, green, [x, y, snake_size, snake_size])
    
    # 定义函数,用于显示分数
    def show_score(score):
        font = pygame.font.SysFont(None, 25)
        text = font.render("Score: " + str(score), True, black)
        window.blit(text, (10, 10))
    
    # 游戏循环
    while not game_over:
        # 监听事件
        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:
                    direction = "left"
                elif event.key == pygame.K_RIGHT:
                    direction = "right"
                elif event.key == pygame.K_UP:
                    direction = "up"
                elif event.key == pygame.K_DOWN:
                    direction = "down"
    
        # 移动贪吃蛇
        if direction == "left":
            snake_x -= snake_speed
        elif direction == "right":
            snake_x += snake_speed
        elif direction == "up":
            snake_y -= snake_speed
        elif direction == "down":
            snake_y += snake_speed
    
        # 判断是否吃到了食物
        if abs(snake_x - food_x) < 10 and abs(snake_y - food_y) < 10:
            score += 1
            snake_length += 1
            food_x = random.randint(0, width - 10)
            food_y = random.randint(0, height - 10)
    
        # 更新贪吃蛇的位置
        snake_head = []
        snake_head.append(snake_x)
        snake_head.append(snake_y)
        snake_body.append(snake_head)
    
        if len(snake_body) > snake_length:
            del snake_body[0]
    
        # 判断是否撞到了自己的身体
        for segment in snake_body[:-1]:
            if segment == snake_head:
                game_over = True
    
        # 判断是否撞到了墙壁
        if snake_x < 0 or snake_x >= width or snake_y < 0 or snake_y >= height:
            game_over = True
    
        # 绘制游戏窗口
        window.fill(black)
        pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size])
        draw_snake(snake_body)
        show_score(score)
        pygame.display.update()
    
        # 设置游戏的帧率
        clock.tick(30)
    
    # 退出游戏
    pygame.quit()
    

    上述代码使用了Python的Pygame库来实现贪吃蛇游戏。游戏窗口的大小为640×480,贪吃蛇的大小为10×10。游戏通过监听键盘事件来控制贪吃蛇的移动方向,当贪吃蛇吃到食物时,得分加1并随机生成新的食物。游戏结束的条件包括撞到自己的身体或撞到墙壁。游戏界面会显示当前的得分。

    1年前 0条评论
  • worktile的头像
    worktile
    Worktile官方账号
    评论

    贪吃蛇是一个经典的游戏,很多人都喜欢编程实现这个游戏。下面是一个示例的贪吃蛇编程源码,包括了方法和操作流程的讲解。

    import pygame
    import time
    import random
    
    # 初始化pygame
    pygame.init()
    
    # 定义颜色
    white = (255, 255, 255)
    black = (0, 0, 0)
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)
    
    # 设置游戏窗口的尺寸和标题
    screen_width = 800
    screen_height = 600
    game_display = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('贪吃蛇')
    
    # 设置游戏时钟
    clock = pygame.time.Clock()
    
    # 定义贪吃蛇的尺寸和速度
    snake_block_size = 20
    snake_speed = 15
    
    # 设置字体
    font_style = pygame.font.SysFont(None, 50)
    score_font = pygame.font.SysFont(None, 35)
    
    
    # 定义计分函数
    def score(score):
        value = score_font.render("Score: " + str(score), True, black)
        game_display.blit(value, [0, 0])
    
    
    # 定义贪吃蛇函数
    def snake(snake_block_size, snake_list):
        for x in snake_list:
            pygame.draw.rect(game_display, green, [x[0], x[1], snake_block_size, snake_block_size])
    
    
    # 定义游戏循环
    def game_loop():
        game_over = False
        game_close = False
    
        # 初始化贪吃蛇的位置和长度
        x1 = screen_width / 2
        y1 = screen_height / 2
        x1_change = 0
        y1_change = 0
        snake_list = []
        length_of_snake = 1
    
        # 初始化食物的位置
        foodx = round(random.randrange(0, screen_width - snake_block_size) / 20.0) * 20.0
        foody = round(random.randrange(0, screen_height - snake_block_size) / 20.0) * 20.0
    
        # 游戏循环
        while not game_over:
    
            # 游戏结束后的操作
            while game_close:
                game_display.fill(white)
                message("游戏结束!按Q退出,按C重新开始", red)
                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:
                            game_loop()
    
            # 处理键盘事件
            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_size
                        y1_change = 0
                    elif event.key == pygame.K_RIGHT:
                        x1_change = snake_block_size
                        y1_change = 0
                    elif event.key == pygame.K_UP:
                        y1_change = -snake_block_size
                        x1_change = 0
                    elif event.key == pygame.K_DOWN:
                        y1_change = snake_block_size
                        x1_change = 0
    
            # 判断贪吃蛇是否超出边界
            if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
                game_close = True
    
            # 更新贪吃蛇的位置
            x1 += x1_change
            y1 += y1_change
            game_display.fill(white)
            pygame.draw.rect(game_display, red, [foodx, foody, snake_block_size, snake_block_size])
            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
    
            # 更新贪吃蛇和食物的显示
            snake(snake_block_size, snake_list)
            score(length_of_snake - 1)
            pygame.display.update()
    
            # 判断贪吃蛇是否吃到食物
            if x1 == foodx and y1 == foody:
                foodx = round(random.randrange(0, screen_width - snake_block_size) / 20.0) * 20.0
                foody = round(random.randrange(0, screen_height - snake_block_size) / 20.0) * 20.0
                length_of_snake += 1
    
            # 控制游戏速度
            clock.tick(snake_speed)
    
        # 退出pygame
        pygame.quit()
    
    
    # 定义显示消息的函数
    def message(msg, color):
        mesg = font_style.render(msg, True, color)
        game_display.blit(mesg, [screen_width / 6, screen_height / 3])
    
    
    # 开始游戏循环
    game_loop()
    

    以上是一个用Python实现的贪吃蛇游戏的示例源码。这段代码使用了pygame库来实现游戏窗口的显示和贪吃蛇的移动、食物的生成等功能。在游戏循环中,通过监听键盘事件来控制贪吃蛇的移动方向,同时判断贪吃蛇是否吃到食物或者撞到边界,以及是否游戏结束。游戏结束后,可以选择退出游戏或者重新开始游戏。

    希望对你有帮助!

    1年前 0条评论
注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部