Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C 語言實作 Windows 控制台字符版俄羅斯方塊

不用圖形庫、不用第三方依賴,單一個 C 檔就能在 Windows 控制台下跑起來的俄羅斯方塊。方塊以位元圖案表描述,畫面靠 gotoxy 定位重繪,最高分則以 XOR 混淆加 BKDR 雜湊校驗後寫入檔案。

操作方式

W 旋轉、S 下落、A 左移、D 右移、P 暫停。開始遊戲前請先按 Ctrl + 空格關閉輸入法,否則按鍵會被攔截而無法操作。

資料結構設計

方塊形狀被抽象成 pattern(寬、高與 4×4 的 0/1 矩陣),同一種方塊的所有旋轉態收在 tetris 的陣列裡,再以兩個 id 組成的 itetris 定位,最後由 ntetris 描述「當前正在下落的」與「下一個」的座標與姿態。

完整程式碼

// 一個可以工作在 Windows 控制台字符界面下的俄羅斯方塊
// 工作在非圖形模式,無需其他庫依賴,單個 C 文件代碼即可運行
// 支持最高紀錄,並且對於紀錄進行了加密
// By wrule 2015年12月14日20:53:57
// 控制方式 WSAD 鍵對應旋轉,下,左,右
// 需要注意的是在進行游戲之前需要按下 Ctrl + 空格 取消輸入法

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <windows.h>

#define SQUARE_BLANK 0
#define SQUARE_TETRIS 1
#define SQUARE_WALL 2

typedef struct pattern pattern;
struct pattern {
    const int w;
    const int h;
    const int data[4][4];
};

typedef struct tetris tetris;
struct tetris {
    const int len;
    const pattern * pattern_list;
};

typedef struct itetris itetris;
struct itetris {
    int id1;
    int id2;
};

typedef struct ntetris ntetris;
struct ntetris {
    int x1, y1;
    itetris its1;
    int x2, y2;
    itetris its2;
};

const tetris tetris_list[];
const size_t TETRIS_LIST_LEN;

char hs_name[9] = "暫無";
int hs_score = 0;
int now_score = 0;
int map[20][10];
unsigned int rhythm = 1000;

void gotoxy(int x, int y) {
    COORD coord = { x, y };
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void error() {
    gotoxy(0, 0);
    printf("error");
    _getch();
    exit(EXIT_FAILURE);
}

void draw_square(int x, int y, int v) {
    gotoxy(x * 2, y);
    switch (v) {
    case SQUARE_BLANK:  { printf("  "); } break;
    case SQUARE_TETRIS: { printf("□"); } break;
    case SQUARE_WALL:   { printf("■"); } break;
    default: { error(); } break;
    }
}

void draw_frame() {
    int x, y;
    for (y = 0; y < 22; ++y)
        for (x = 0; x < 12; ++x)
            if (y == 0 || y == 21 || x == 0 || x == 11)
                draw_square(x, y, SQUARE_WALL);
    for (y = 0; y < 6; ++y)
        for (x = 13; x < 19; ++x)
            if (y == 0 || y == 5 || x == 13 || x == 18)
                draw_square(x, y, SQUARE_WALL);
    gotoxy(28, 8);  printf("最高紀錄");
    gotoxy(28, 14); printf("當前得分");
    gotoxy(28, 21); printf("by wrule");
}

void draw_tetris(const itetris * pits, int x, int y, int v) {
    int px, py, ox, oy;
    const pattern * ptrn = &(tetris_list[pits->id1].pattern_list[pits->id2]);
    int w = ptrn->w, h = ptrn->h;
    for (py = 0; py < h; ++py) {
        for (px = 0; px < w; ++px) {
            if (ptrn->data[py][px]) {
                ox = x + px; oy = y + py;
                if ((ox > -1 && ox < 10 && oy > -1 && oy < 20) ||
                    (ox > 12 && ox < 17 && oy > -1 && oy < 4))
                    draw_square(ox + 1, oy + 1, v);
            }
        }
    }
}

void draw_next_tetris(const itetris * pits) {
    const pattern * ptrn = &(tetris_list[pits->id1].pattern_list[pits->id2]);
    int w = ptrn->w, h = ptrn->h, bx, by;
    int px = (4 - w) / 2, py = (4 - h) / 2;
    if (h % 2) ++py;
    for (by = 1; by < 5; ++by)
        for (bx = 14; bx < 18; ++bx)
            draw_square(bx, by, SQUARE_BLANK);
    draw_tetris(pits, 13 + px, py, SQUARE_TETRIS);
}

void get_rnd_tetris(itetris * pits) {
    pits->id1 = rand() % TETRIS_LIST_LEN;
    pits->id2 = rand() % tetris_list[pits->id1].len;
}

void use_op(ntetris * pnts) {
    draw_tetris(&(pnts->its1), pnts->x1, pnts->y1, SQUARE_BLANK);
    pnts->x1 = pnts->x2; pnts->y1 = pnts->y2; pnts->its1 = pnts->its2;
    draw_tetris(&(pnts->its1), pnts->x1, pnts->y1, SQUARE_TETRIS);
}

void general_fall(ntetris * pnts) {
    pnts->x2 = pnts->x1; pnts->y2 = pnts->y1 + 1; pnts->its2 = pnts->its1;
}

void hand_left(ntetris * pnts) {
    pnts->x2 = pnts->x1 - 1; pnts->y2 = pnts->y1; pnts->its2 = pnts->its1;
}

void hand_right(ntetris * pnts) {
    pnts->x2 = pnts->x1 + 1; pnts->y2 = pnts->y1; pnts->its2 = pnts->its1;
}

#define TURN_LEFT -1
#define TURN_RIGHT 1

void hand_turn(ntetris * pnts, int dir) {
    int px, py, w1, h1, w2, h2;
    const pattern * ptrn1, * ptrn2;
    int len = tetris_list[pnts->its1.id1].len;
    pnts->its2 = pnts->its1;
    pnts->its2.id2 += dir;
    if (pnts->its2.id2 >= len) pnts->its2.id2 = 0;
    else if (pnts->its2.id2 <= -1) pnts->its2.id2 = len - 1;
    ptrn1 = &(tetris_list[pnts->its1.id1].pattern_list[pnts->its1.id2]);
    ptrn2 = &(tetris_list[pnts->its2.id1].pattern_list[pnts->its2.id2]);
    w1 = ptrn1->w; h1 = ptrn1->h; w2 = ptrn2->w; h2 = ptrn2->h;
    px = (w1 - w2) / 2; py = (h1 - h2) / 2;
    pnts->x2 = pnts->x1 + px;
    pnts->y2 = pnts->y1 + py;
}

void put_tetris(ntetris * pnts, itetris * pits) {
    const pattern * ptrn = &(tetris_list[pits->id1].pattern_list[pits->id2]);
    int w = ptrn->w, h = ptrn->h;
    pnts->x2 = (10 - w) / 2; pnts->y2 = -h; pnts->its2 = *pits;
    pnts->x1 = pnts->x2; pnts->y1 = pnts->y2; pnts->its1 = pnts->its2;
    use_op(pnts);
}

void init_map() {
    int x, y;
    for (y = 0; y < 20; ++y)
        for (x = 0; x < 10; ++x)
            map[y][x] = 0;
}

int op_isilegal(ntetris * pnts) {
    int x = pnts->x2, y = pnts->y2, px, py, ox, oy, ret = 0;
    const pattern * ptrn = &(tetris_list[pnts->its2.id1].pattern_list[pnts->its2.id2]);
    int w = ptrn->w, h = ptrn->h;
    for (py = 0; py < h; ++py) {
        for (px = 0; px < w; ++px) {
            if (ptrn->data[py][px]) {
                ox = x + px; oy = y + py;
                if (ox < 0 || ox > 9 || oy > 19) { ret = 1; goto pret; }
                else if (oy > -1 && map[oy][ox]) { ret = 1; goto pret; }
            }
        }
    }
pret:
    return ret;
}

void write_tetris(ntetris * pnts) {
    int x = pnts->x1, y = pnts->y1, px, py, ox, oy;
    const pattern * ptrn = &(tetris_list[pnts->its1.id1].pattern_list[pnts->its1.id2]);
    int w = ptrn->w, h = ptrn->h;
    for (py = 0; py < h; ++py)
        for (px = 0; px < w; ++px)
            if (ptrn->data[py][px]) {
                ox = x + px; oy = y + py;
                map[oy][ox] = 1;
            }
}

void draw_map() {
    int x, y;
    for (y = 0; y < 20; ++y)
        for (x = 0; x < 10; ++x)
            draw_square(x + 1, y + 1, map[y][x] ? SQUARE_TETRIS : SQUARE_BLANK);
}

int try_clear() {
    int score = 0, i, x, y, flag, clear = 0;
    int list[20], tmap[20][10];
    for (y = 0; y < 20; ++y) {
        flag = 1;
        for (x = 0; x < 10; ++x)
            if (0 == map[y][x]) { flag = 0; break; }
        list[y] = flag;
    }
    for (i = 0; i < 20; ++i)
        if (1 == list[i]) { score++; clear = 1; }
    if (clear) {
        for (i = 0; i < 3; ++i) {
            for (x = 0; x < 10; ++x)
                for (y = 0; y < 20; ++y)
                    if (list[y])
                        draw_square(x + 1, y + 1, (i % 2) ? SQUARE_TETRIS : SQUARE_BLANK);
            Sleep(250);
        }
        for (y = 0; y < 20; ++y)
            for (x = 0; x < 10; ++x)
                tmap[y][x] = 0;
        i = 19;
        for (y = 19; y > -1; --y)
            if (0 == list[y]) {
                for (x = 0; x < 10; ++x) tmap[i][x] = map[y][x];
                --i;
            }
        for (y = 0; y < 20; ++y)
            for (x = 0; x < 10; ++x)
                map[y][x] = tmap[y][x];
        draw_map();
    }
    rhythm -= score;
    if (rhythm < 50) rhythm = 50;
    return score;
}

void update_now_score() {
    gotoxy(30, 16); printf("     ");
    gotoxy(30, 16); printf("%d", now_score);
}

void update_hs_data() {
    int i;
    gotoxy(28, 10); printf("     ");
    gotoxy(28, 10);
    for (i = 0; i < 8 && hs_name[i]; ++i) putchar(hs_name[i]);
    gotoxy(30, 12); printf("     ");
    gotoxy(30, 12); printf("%d", hs_score);
}

#define NEXT_STEP 0
#define WRITE_WIN 1
#define GAME_OVER 2

int after_fall(ntetris * pnts) {
    int pscore;
    if (op_isilegal(pnts) == 0) { use_op(pnts); return NEXT_STEP; }
    else {
        if (pnts->y1 < 0) return GAME_OVER;
        else {
            write_tetris(pnts);
            pscore = try_clear();
            if (pscore) { now_score += pscore; update_now_score(); }
            return WRITE_WIN;
        }
    }
}

unsigned int bkdr_hash(const char * str) {
    unsigned int seed = 131, hash = 0;
    while (*str) hash = hash * seed + (*str++);
    return hash % 65536;
}

void read_hs_data() {
    size_t i, len;
    unsigned char buf[100];
    unsigned int hash_num;
    char str[50], * pstr = NULL;
    FILE * fp = fopen("tetris.txt", "rb");
    if (NULL != fp) {
        len = fread(buf, 1, 100, fp);
        for (i = 0; i < len; ++i) buf[i] ^= 0xC6;
        buf[i] = '\0';
        hash_num = buf[0] + buf[1] * 256;
        if (bkdr_hash(&buf[2]) == hash_num) {
            sscanf(&buf[2], "%s", str);
            sscanf(str, "%d", &hs_score);
            pstr = &buf[strlen(str) + 3];
            for (i = 0; i < 8 && pstr[i]; ++i) hs_name[i] = pstr[i];
            hs_name[i] = '\0';
        } else { strcpy(hs_name, "暫無"); hs_score = 0; }
        fclose(fp);
    } else { strcpy(hs_name, "暫無"); hs_score = 0; }
}

void write_hs_data(char name[], int score) {
    size_t len, i;
    unsigned char buf[100];
    unsigned int hash_num;
    FILE * fp = fopen("tetris.txt", "wb");
    if (NULL != fp) {
        sprintf(&buf[2], "%d\n", score);
        len = strlen(&buf[2]);
        for (i = 0; i < 8 && name[i]; ++i) (&buf[2])[len + i] = name[i];
        (&buf[2])[len + i] = '\0';
        len = strlen(&buf[2]);
        hash_num = bkdr_hash(&buf[2]);
        buf[0] = hash_num % 256;
        buf[1] = hash_num / 256;
        for (i = 0; i < len + 2; ++i) fputc(buf[i] ^ 0xC6, fp);
        fclose(fp);
    } else error();
}

void game_over() {
    char name[100];
    system("cls");
    gotoxy(9, 2); printf("你的得分為: %d", now_score);
    if (now_score > hs_score) {
        gotoxy(9, 4); printf("恭喜你刷新了記錄");
        gotoxy(9, 6); printf("請輸入你的大名: ");
        scanf("%s", name);
        write_hs_data(name, now_score);
        gotoxy(9, 8); printf("記錄成功刷新");
    } else {
        gotoxy(9, 4); printf("很遺憾你沒有刷新記錄");
    }
    _getch();
}

int game_main() {
    itetris next_its;
    ntetris nts;
    unsigned int otime, ntime;
    int c, pause = 0, aflag;
    system("cls");
    now_score = 0;
    init_map();
    get_rnd_tetris(&next_its);
    draw_frame();
    read_hs_data();
    update_hs_data();
    update_now_score();
    gotoxy(28, 19); printf("P鍵暫停");
    while (1) {
bk2:
        put_tetris(&nts, &next_its);
        get_rnd_tetris(&next_its);
        draw_next_tetris(&next_its);
        otime = GetTickCount();
        while (1) {
            if (0 == pause) {
                if ((ntime = GetTickCount()) - otime > rhythm) {
                    otime = ntime;
                    general_fall(&nts);
                    aflag = after_fall(&nts);
                    if (WRITE_WIN == aflag) break;
                    else if (GAME_OVER == aflag) { game_over(); return 0; }
                }
            }
            if (_kbhit()) {
                c = _getch();
                if (0 == pause) {
                    switch (c) {
                    case 'w': {
                        hand_turn(&nts, TURN_RIGHT);
                        if (op_isilegal(&nts) == 0) use_op(&nts);
                    } break;
                    case 's': {
                        general_fall(&nts);
                        aflag = after_fall(&nts);
                        if (WRITE_WIN == aflag) goto bk2;
                        else if (GAME_OVER == aflag) { game_over(); return 0; }
                    } break;
                    case 'a': {
                        hand_left(&nts);
                        if (op_isilegal(&nts) == 0) use_op(&nts);
                    } break;
                    case 'd': {
                        hand_right(&nts);
                        if (op_isilegal(&nts) == 0) use_op(&nts);
                    } break;
                    }
                }
                if ('p' == c) {
                    if (pause) { pause = 0; gotoxy(28, 19); printf("P鍵暫停"); }
                    else { pause = 1; gotoxy(28, 19); printf("P鍵繼續"); }
                }
            }
        }
    }
    return 0;
}

int main() {
    system("cls");
    system("title tetris");
    system("mode con cols=38 lines=22");
    srand((unsigned int)time(NULL));
    while (1) game_main();
    return 0;
}

方塊圖案資料表(七種方塊各自的旋轉態)以 const pattern 陣列常量化存放,與主程式邏輯分離;tetris_list 再用 sizeof 計算每種方塊的旋轉數,新增方塊時只改資料表即可,不必動到遊戲邏輯。這份「資料與程式分離」的結構,是它能壓在單一檔案裡還保持可讀的關鍵。

另外提醒:程式中 scanf("%s", name) 未限制長度,正式使用前應改為指定寬度(例如 %99s)以避免緩衝區溢位風險。

Copyright © Linux教程網 All Rights Reserved