2048游戏,详解+代码

初始化游戏板


C++复制↓↓↓

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <conio.h> // 用于_getch()

const int SIZE = 4;
std::vector<std::vector<int>> board(SIZE, std::vector<int>(SIZE, 0));

void initializeBoard() {
    srand(time(0));
    // 初始放置两个随机数字
    addRandomTile();
    addRandomTile();
}

添加随机数字


cpp复制插入

void addRandomTile() {
    int row, col;
    do {
        row = rand() % SIZE;
        col = rand() % SIZE;
    } while (board[row][col] != 0);

    board[row][col] = (rand() % 10 < 9) ? 2 : 4;
}

移动逻辑


cpp复制插入

void moveLeft() {
    for (int i = 0; i < SIZE; ++i) {
        // 合并相同数字
        for (int j = 0; j < SIZE - 1; ++j) {
            if (board[i][j] == board[i][j + 1] && board[i][j] != 0) {
                board[i][j] *= 2;
                board[i][j + 1] = 0;
            }
        }
        // 移动非零元素
        for (int j = 0; j < SIZE - 1; ++j) {
            if (board[i][j] == 0) {
                for (int k = j + 1; k < SIZE; ++k) {
                    if (board[i][k] != 0) {
                        board[i][j] = board[i][k];
                        board[i][k] = 0;
                        break;
                    }
                }
            }
        }
    }
}

旋转和移动其他方向


void rotateBoard() {
    std::vector<std::vector<int>> temp(SIZE, std::vector<int>(SIZE));
    for (int i = 0; i < SIZE; ++i) {
        for (int j = 0; j < SIZE; ++j) {
            temp[j][SIZE - 1 - i] = board[i][j];
        }
    }
    board = temp;
}

void move(int direction) {
    for (int i = 0; i < direction; ++i) {
        rotateBoard();
    }
    moveLeft();
    for (int i = 0; i < (4 - direction) % 4; ++i) {
        rotateBoard();
    }
}

显示游戏板


cpp复制插入

void displayBoard() {
    system("cls");
    for (int i = 0; i < SIZE; ++i) {
        for (int j = 0; j < SIZE; ++j) {
            std::cout << board[i][j] << "\t";
        }
        std::cout << std::endl << std::endl;
    }
}

主游戏循环


cpp复制插入

int main() {
    initializeBoard();
    displayBoard();

    while (true) {
        char input = _getch();
        switch (input) {
            case 'a': move(0); break; // 左
            case 'w': move(1); break; // 上
            case 'd': move(2); break; // 右
            case 's': move(3); break; // 下
            case 'q': return 0;       // 退出
            default: continue;
        }
        addRandomTile();
        displayBoard();
    }

    return 0;
}

这个实现包含了2048游戏的基本功能:

  • 4x4游戏板初始化
  • 随机数字生成(2或4)
  • 方向移动和合并逻辑
  • 简单的控制台界面

可以自己组装一下,试一下成果!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值