// tetris.cpp - Tetris for Bananarchy (Sxmo/dwm, 240x296) // Standalone X11 application in C++. Self-contained: uses a built-in 5x7 // bitmap font so it has no font-file dependency. // // Controls (Nokia keypad + D-pad): // 4 / Left -> move left 6 / Right -> move right // 2 / Up -> rotate CW 8 / Down -> soft drop // 0 / 5 / Space -> hard drop # / * / P -> pause // 5 / OK -> resume / new game // Back / Esc -> quit // // Build: g++ -O2 tetris.cpp -lX11 -o tetris #include #include #include #include #ifndef _EVDEVK #define _EVDEVK(_v) (0x10081000 + (_v)) #endif #include #include #include #include #include #include #include #include #include #include #include static const int TOPBAR = 24; static const int PCOLS = 10; static const int PROWS = 20; static const int CELL = 14; // ---- 5x7 bitmap font ---- struct Glyph { char ch; unsigned char r[7]; }; static const Glyph GLYPHS[] = { {' ', {0,0,0,0,0,0,0}}, {'!', {0b00100,0b00100,0b00100,0b00100,0b00100,0,0b00100}}, {'.', {0,0,0,0,0,0b00100,0b00100}}, {'-', {0,0,0,0b11111,0,0,0}}, {':', {0,0b00100,0b00100,0,0b00100,0b00100,0}}, {'?', {0b01110,0b10001,0b00001,0b00110,0b00100,0,0b00100}}, {'A', {0b01110,0b10001,0b10001,0b11111,0b10001,0b10001,0b10001}}, {'B', {0b11110,0b10001,0b10001,0b11110,0b10001,0b10001,0b11110}}, {'C', {0b01110,0b10001,0b10000,0b10000,0b10000,0b10001,0b01110}}, {'D', {0b11110,0b10001,0b10001,0b10001,0b10001,0b10001,0b01110}}, {'E', {0b11111,0b10000,0b10000,0b11110,0b10000,0b10000,0b11111}}, {'F', {0b11111,0b10000,0b10000,0b11110,0b10000,0b10000,0b10000}}, {'G', {0b01110,0b10001,0b10000,0b10111,0b10001,0b10001,0b01111}}, {'H', {0b10001,0b10001,0b10001,0b11111,0b10001,0b10001,0b10001}}, {'I', {0b01110,0b00100,0b00100,0b00100,0b00100,0b00100,0b01110}}, {'J', {0b00010,0b00010,0b00010,0b00010,0b10010,0b10010,0b01100}}, {'K', {0b10001,0b10010,0b10100,0b11000,0b10100,0b10010,0b10001}}, {'L', {0b10000,0b10000,0b10000,0b10000,0b10000,0b10000,0b11111}}, {'M', {0b10001,0b11011,0b10101,0b10101,0b10001,0b10001,0b10001}}, {'N', {0b10001,0b10001,0b11001,0b10101,0b10011,0b10001,0b10001}}, {'O', {0b01110,0b10001,0b10001,0b10001,0b10001,0b10001,0b01110}}, {'P', {0b11110,0b10001,0b10001,0b11110,0b10000,0b10000,0b10000}}, {'Q', {0b01110,0b10001,0b10001,0b10001,0b10101,0b10010,0b01101}}, {'R', {0b11110,0b10001,0b10001,0b11110,0b10100,0b10010,0b10001}}, {'S', {0b01111,0b10000,0b10000,0b01110,0b00001,0b00001,0b11110}}, {'T', {0b11111,0b00100,0b00100,0b00100,0b00100,0b00100,0b00100}}, {'U', {0b10001,0b10001,0b10001,0b10001,0b10001,0b10001,0b01110}}, {'V', {0b10001,0b10001,0b10001,0b10001,0b10001,0b01010,0b00100}}, {'W', {0b10001,0b10001,0b10001,0b10101,0b10101,0b11011,0b10001}}, {'X', {0b10001,0b10001,0b01010,0b00100,0b01010,0b10001,0b10001}}, {'Y', {0b10001,0b10001,0b01010,0b00100,0b00100,0b00100,0b00100}}, {'Z', {0b11111,0b00010,0b00100,0b01000,0b10000,0b10000,0b11111}}, {'0', {0b01110,0b10011,0b10101,0b10101,0b11001,0b10001,0b01110}}, {'1', {0b00100,0b01100,0b00100,0b00100,0b00100,0b00100,0b01110}}, {'2', {0b01110,0b10001,0b00001,0b00110,0b01000,0b10000,0b11111}}, {'3', {0b11110,0b00001,0b00001,0b01110,0b00001,0b00001,0b11110}}, {'4', {0b00010,0b00110,0b01010,0b10010,0b11111,0b00010,0b00010}}, {'5', {0b11111,0b10000,0b11110,0b00001,0b00001,0b10001,0b01110}}, {'6', {0b00110,0b01000,0b10000,0b11110,0b10001,0b10001,0b01110}}, {'7', {0b11111,0b00001,0b00010,0b00100,0b01000,0b01000,0b01000}}, {'8', {0b01110,0b10001,0b10001,0b01110,0b10001,0b10001,0b01110}}, {'9', {0b01110,0b10001,0b10001,0b01111,0b00001,0b00010,0b01100}}, {'/', {0b00001,0b00010,0b00100,0b00100,0b01000,0b01000,0b10000}}, {'#', {0b01010,0b01010,0b11111,0b01010,0b11111,0b01010,0b01010}}, {'*', {0b00100,0b01010,0b11111,0b01010,0b00100,0b00000,0b00000}}, {'+', {0b00000,0b00100,0b00100,0b11111,0b00100,0b00100,0b00000}}, {'=', {0b00000,0b00000,0b11111,0b00000,0b11111,0b00000,0b00000}}, }; static const int NGLYPH = int(sizeof(GLYPHS) / sizeof(GLYPHS[0])); static unsigned char GLYPH_LUT[128][7]; static void init_glyph_lut() { memset(GLYPH_LUT, 0, sizeof(GLYPH_LUT)); for (int i = 0; i < NGLYPH; i++) { unsigned char idx = (unsigned char)GLYPHS[i].ch; if (idx < 128) memcpy(GLYPH_LUT[idx], GLYPHS[i].r, 7); } } static inline const unsigned char* glyph(char c) { unsigned char idx = (unsigned char)c; return (idx < 128) ? GLYPH_LUT[idx] : GLYPH_LUT[(unsigned char)' ']; } // ---- X11 state ---- static Display* dpy = nullptr; static Window win; static GC gc; static Pixmap back; static int screen; static int winW = 240, winH = 296; // overridden at runtime from the actual screen static Atom wmDeleteAtom = None; static unsigned long C_BG, C_FG, C_HEAD, C_FOOD, C_DIM; static unsigned long C_GB_DARK, C_GB_MED, C_GB_LIGHT, C_GB_PALE; // ---- tetromino definitions (state 0 within a 4x4 box) ---- // type 0..6 -> I,O,T,S,Z,J,L static const int SHAPES[7][4][4][2] = { { {{0,1},{1,1},{2,1},{3,1}}, {{2,0},{2,1},{2,2},{2,3}}, {{0,2},{1,2},{2,2},{3,2}}, {{1,0},{1,1},{1,2},{1,3}} }, // I { {{1,0},{2,0},{1,1},{2,1}}, {{1,0},{2,0},{1,1},{2,1}}, {{1,0},{2,0},{1,1},{2,1}}, {{1,0},{2,0},{1,1},{2,1}} }, // O { {{1,0},{0,1},{1,1},{2,1}}, {{1,0},{1,1},{2,1},{1,2}}, {{0,1},{1,1},{2,1},{1,2}}, {{1,0},{0,1},{1,1},{1,2}} }, // T { {{1,0},{2,0},{0,1},{1,1}}, {{1,0},{1,1},{2,1},{2,2}}, {{1,1},{2,1},{0,2},{1,2}}, {{0,0},{0,1},{1,1},{1,2}} }, // S { {{0,0},{1,0},{1,1},{2,1}}, {{2,0},{1,1},{2,1},{1,2}}, {{0,1},{1,1},{1,2},{2,2}}, {{1,0},{0,1},{1,1},{0,2}} }, // Z { {{0,0},{0,1},{1,1},{2,1}}, {{1,0},{2,0},{1,1},{1,2}}, {{0,1},{1,1},{2,1},{2,2}}, {{1,0},{1,1},{0,2},{1,2}} }, // J { {{2,0},{0,1},{1,1},{2,1}}, {{1,0},{1,1},{1,2},{2,2}}, {{0,1},{1,1},{2,1},{0,2}}, {{0,0},{1,0},{1,1},{1,2}} }, // L }; enum State { PLAYING, PAUSED, GAMEOVER }; static State state = PLAYING; static int board[PCOLS][PROWS]; // 0 empty, else type+1 static int curType = 0, curRot = 0, curX = 3, curY = 0; static int nextType = 0; static int score = 0, best = 0, lines = 0, level = 1; static int speed = 600; // ms per gravity step (derived from pps below) static int pps = 23; // base speed px/sec; +1 px/sec per 10 lines cleared static bool running = true; static bool dirty = true; static bool resyncTimer = false; static void piece_cells(int type, int rot, int out[4][2]) { int r = ((rot % 4) + 4) % 4; for (int i = 0; i < 4; i++) { out[i][0] = SHAPES[type][r][i][0]; out[i][1] = SHAPES[type][r][i][1]; } } static bool collide(int px, int py, int cells[4][2]) { for (int i = 0; i < 4; i++) { int cx = px + cells[i][0]; int cy = py + cells[i][1]; if (cx < 0 || cx >= PCOLS || cy >= PROWS) return true; if (cy >= 0 && board[cx][cy]) return true; } return false; } static int64_t now_ns() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (int64_t)ts.tv_sec * 1000000000LL + (int64_t)ts.tv_nsec; } static inline int64_t step_ns() { return (int64_t)speed * 1000000LL; } // Derive the gravity delay (ms) from the target pixels/second. A piece drops // one cell (CELL pixels) per gravity step, so step time = CELL / pps. static void update_speed() { pps = 23 + lines / 10; // +1 px/sec per 10 cleared lines (progressive difficulty) int ms = (CELL * 1000) / pps; if (ms < 40) ms = 40; // floor on gravity so it stays playable speed = ms; } static void spawn() { curType = nextType; nextType = rand() % 7; curRot = 0; curX = 3; curY = 0; int cells[4][2]; piece_cells(curType, curRot, cells); if (collide(curX, curY, cells)) { state = GAMEOVER; if (score > best) best = score; } resyncTimer = true; dirty = true; } static void lock_piece() { int cells[4][2]; piece_cells(curType, curRot, cells); for (int i = 0; i < 4; i++) { int cx = curX + cells[i][0]; int cy = curY + cells[i][1]; if (cy < 0) { state = GAMEOVER; if (score > best) best = score; dirty = true; return; } board[cx][cy] = curType + 1; } // clear full lines int cleared = 0; for (int y = PROWS - 1; y >= 0; y--) { bool full = true; for (int x = 0; x < PCOLS; x++) if (!board[x][y]) { full = false; break; } if (full) { cleared++; for (int yy = y; yy > 0; yy--) for (int x = 0; x < PCOLS; x++) board[x][yy] = board[x][yy - 1]; for (int x = 0; x < PCOLS; x++) board[x][0] = 0; y++; // recheck same row } } if (cleared > 0) { lines += cleared; level = 1 + lines / 10; int pts[5] = {0, 100, 300, 500, 800}; score += pts[cleared] * level; if (score > best) best = score; update_speed(); // +1 px/sec per 10 cleared lines } spawn(); } static void step() { int cells[4][2]; piece_cells(curType, curRot, cells); if (!collide(curX, curY + 1, cells)) { curY++; dirty = true; } else { lock_piece(); } } static void hard_drop() { int cells[4][2]; piece_cells(curType, curRot, cells); while (!collide(curX, curY + 1, cells)) curY++; score += 2; if (score > best) best = score; lock_piece(); } static void try_move(int dx) { int cells[4][2]; piece_cells(curType, curRot, cells); if (!collide(curX + dx, curY, cells)) { curX += dx; dirty = true; } } static void try_rotate() { int nr = (curRot + 1) % 4; int cells[4][2]; piece_cells(curType, nr, cells); // wall kicks: try in place, then small horizontal shifts int kicks[5] = {0, -1, 1, -2, 2}; for (int k = 0; k < 5; k++) { if (!collide(curX + kicks[k], curY, cells)) { curX += kicks[k]; curRot = nr; dirty = true; return; } } } static void reset_game() { for (int x = 0; x < PCOLS; x++) for (int y = 0; y < PROWS; y++) board[x][y] = 0; score = 0; lines = 0; level = 1; update_speed(); nextType = rand() % 7; state = PLAYING; spawn(); } // Append a string's coalesced glyph rectangles into a caller-supplied array. static int append_text_rects(int x, int y, int scale, const char* s, XRectangle* rects, int maxRects, int nrects) { int cx = x; for (const char* p = s; *p; p++) { const unsigned char* g = glyph(*p); for (int r = 0; r < 7; r++) { unsigned char row = g[r]; if (!row) continue; int b = 0; while (b < 5) { if (row & (1 << (4 - b))) { int start = b; while (b < 5 && (row & (1 << (4 - b)))) b++; if (nrects < maxRects) { rects[nrects].x = (short)(cx + start * scale); rects[nrects].y = (short)(y + r * scale); rects[nrects].width = (unsigned short)((b - start) * scale); rects[nrects].height = (unsigned short)scale; nrects++; } } else { b++; } } } cx += 6 * scale; } return nrects; } static void draw_text(int x, int y, int scale, unsigned long col, const char* s) { XRectangle rects[512]; int nrects = append_text_rects(x, y, scale, s, rects, 512, 0); if (nrects > 0) { XSetForeground(dpy, gc, col); XFillRectangles(dpy, back, gc, rects, nrects); } } static inline void append_bevel(int bx, int by, int size, XRectangle* bodies, int& nb, XRectangle* highlights, int& nh, XRectangle* shadows, int& ns) { bodies[nb].x = (short)(bx + 1); bodies[nb].y = (short)(by + 1); bodies[nb].width = (unsigned short)(size - 2); bodies[nb].height = (unsigned short)(size - 2); nb++; highlights[nh].x = (short)(bx + 1); highlights[nh].y = (short)by; highlights[nh].width = (unsigned short)(size - 2); highlights[nh].height = 1; nh++; highlights[nh].x = (short)bx; highlights[nh].y = (short)(by + 1); highlights[nh].width = 1; highlights[nh].height = (unsigned short)(size - 2); nh++; shadows[ns].x = (short)(bx + 1); shadows[ns].y = (short)(by + size - 1); shadows[ns].width = (unsigned short)(size - 2); shadows[ns].height = 1; ns++; shadows[ns].x = (short)(bx + size - 1); shadows[ns].y = (short)(by + 1); shadows[ns].width = 1; shadows[ns].height = (unsigned short)(size - 2); ns++; } static void render() { int px0 = 8, py0 = 8; XSetForeground(dpy, gc, C_BG); XFillRectangle(dpy, back, gc, 0, 0, winW, winH); // Outer border framing the whole game window XSetForeground(dpy, gc, C_DIM); XDrawRectangle(dpy, back, gc, 2, 2, winW - 4, winH - 4); if (state == PLAYING) { // 1px frame around the 10x20 well so its walls/floor are unmistakable XDrawRectangle(dpy, back, gc, px0 - 1, py0 - 1, PCOLS * CELL + 1, PROWS * CELL + 1); // Side panel preview frame int sx = px0 + PCOLS * CELL + 12; int boxY = py0 + 10; int boxH = 52; XDrawRectangle(dpy, back, gc, sx - 2, boxY + 1, winW - sx - 3, boxH); // Batched beveled blocks: settled board, active piece, and next-piece preview XRectangle settledBodies[PCOLS * PROWS]; XRectangle activeBodies[4]; XRectangle previewBodies[4]; XRectangle highlights[(PCOLS * PROWS + 8) * 2]; XRectangle shadows[(PCOLS * PROWS + 8) * 2]; int nsb = 0, nab = 0, npb = 0, nh = 0, ns = 0; for (int x = 0; x < PCOLS; x++) { for (int y = 0; y < PROWS; y++) { if (board[x][y]) { append_bevel(px0 + x * CELL, py0 + y * CELL, CELL, settledBodies, nsb, highlights, nh, shadows, ns); } } } int cells[4][2]; piece_cells(curType, curRot, cells); for (int i = 0; i < 4; i++) { int cx = curX + cells[i][0]; int cy = curY + cells[i][1]; if (cy >= 0) { append_bevel(px0 + cx * CELL, py0 + cy * CELL, CELL, activeBodies, nab, highlights, nh, shadows, ns); } } int nc[4][2]; piece_cells(nextType, 0, nc); int minx = 4, miny = 4, maxx = -1, maxy = -1; for (int i = 0; i < 4; i++) { if (nc[i][0] < minx) minx = nc[i][0]; if (nc[i][1] < miny) miny = nc[i][1]; if (nc[i][0] > maxx) maxx = nc[i][0]; if (nc[i][1] > maxy) maxy = nc[i][1]; } int pcell = 11; int pcols = maxx - minx + 1; int prows = maxy - miny + 1; int nx0 = sx + ((winW - sx - 4) - pcols * pcell) / 2; int ny0 = boxY + (boxH - prows * pcell) / 2 + 12; for (int i = 0; i < 4; i++) { int cx = nx0 + (nc[i][0] - minx) * pcell; int cy = ny0 + (nc[i][1] - miny) * pcell; append_bevel(cx, cy, pcell, previewBodies, npb, highlights, nh, shadows, ns); } if (nsb > 0) { XSetForeground(dpy, gc, C_GB_MED); XFillRectangles(dpy, back, gc, settledBodies, nsb); } if (nab > 0) { XSetForeground(dpy, gc, C_GB_LIGHT); XFillRectangles(dpy, back, gc, activeBodies, nab); } if (npb > 0) { XSetForeground(dpy, gc, C_HEAD); XFillRectangles(dpy, back, gc, previewBodies, npb); } if (nh > 0) { XSetForeground(dpy, gc, C_GB_PALE); XFillRectangles(dpy, back, gc, highlights, nh); } if (ns > 0) { XSetForeground(dpy, gc, C_GB_DARK); XFillRectangles(dpy, back, gc, shadows, ns); } // Vertical separator line between playfield and side panel int sepX = px0 + PCOLS * CELL + 6; XSetForeground(dpy, gc, C_FG); XDrawLine(dpy, back, gc, sepX, py0, sepX, py0 + PROWS * CELL); // Batch ALL side-panel text (NEXT, stats, and controls) into a single XFillRectangles call! XRectangle textRects[1024]; int ntr = 0; ntr = append_text_rects(sx, py0, 1, "NEXT", textRects, 1024, ntr); int ty = boxY + boxH + 6; char buf[32]; snprintf(buf, sizeof(buf), "SCORE %d", score); ntr = append_text_rects(sx, ty, 1, buf, textRects, 1024, ntr); snprintf(buf, sizeof(buf), "LINES %d", lines); ntr = append_text_rects(sx, ty + 9, 1, buf, textRects, 1024, ntr); snprintf(buf, sizeof(buf), "LEVEL %d", level); ntr = append_text_rects(sx, ty + 18, 1, buf, textRects, 1024, ntr); if (best > 0) { snprintf(buf, sizeof(buf), "BEST %d", best); ntr = append_text_rects(sx, ty + 27, 1, buf, textRects, 1024, ntr); } int ky = ty + 27 + 12; ntr = append_text_rects(sx, ky, 1, "KEYS", textRects, 1024, ntr); ntr = append_text_rects(sx, ky + 9, 1, "4/6 MOVE", textRects, 1024, ntr); ntr = append_text_rects(sx, ky + 18, 1, "2 ROTATE", textRects, 1024, ntr); ntr = append_text_rects(sx, ky + 27, 1, "8 SOFT", textRects, 1024, ntr); ntr = append_text_rects(sx, ky + 36, 1, "0 DROP", textRects, 1024, ntr); ntr = append_text_rects(sx, ky + 45, 1, "# PAUSE", textRects, 1024, ntr); ntr = append_text_rects(sx, ky + 54, 1, "5 OK", textRects, 1024, ntr); if (ntr > 0) { XSetForeground(dpy, gc, C_DIM); XFillRectangles(dpy, back, gc, textRects, ntr); } } else if (state == PAUSED) { draw_text(winW / 2 - 5 * 6, winH / 2 - 7, 2, C_FG, "PAUSE"); draw_text(winW / 2 - 4 * 6, winH / 2 + 10, 1, C_DIM, "5 RESUME"); } else if (state == GAMEOVER) { draw_text(winW / 2 - 9 * 6, winH / 2 - 14, 2, C_FG, "GAME OVER"); char buf[32]; snprintf(buf, sizeof(buf), "SCORE %d", score); draw_text(winW / 2 - (int)strlen(buf) * 3, winH / 2 + 4, 1, C_DIM, buf); draw_text(winW / 2 - 5 * 6, winH / 2 + 13, 1, C_DIM, "5 NEW GAME"); } XCopyArea(dpy, back, win, gc, 0, 0, winW, winH, 0, 0); XFlush(dpy); dirty = false; } static void setup_window() { dpy = XOpenDisplay(nullptr); if (!dpy) { fprintf(stderr, "tetris: cannot open display\n"); exit(1); } screen = DefaultScreen(dpy); int sw = DisplayWidth(dpy, screen); int scrH = DisplayHeight(dpy, screen); // dwm draws a `borderpx` border around every client (src/sxmo-dwm/config.h). // Size/position the window so that, once dwm adds its border back on each // side, the framed window exactly meets the screen edges and the native // border stays fully visible instead of being clipped off the right/bottom. int bw = 1; // must match dwm borderpx winW = sw - 3 * bw; winH = (scrH - TOPBAR) - 3 * bw; // room for the status bar + border if (winW < 96) winW = 96; if (winH < 96) winH = 96; win = XCreateWindow(dpy, RootWindow(dpy, screen), bw, TOPBAR + bw, winW, winH, 0, CopyFromParent, InputOutput, CopyFromParent, 0, nullptr); XStoreName(dpy, win, "Tetris"); XClassHint* ch = XAllocClassHint(); if (ch) { ch->res_name = (char*)"tetris"; ch->res_class = (char*)"tetris"; XSetClassHint(dpy, win, ch); XFree(ch); } Atom wtype = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False); Atom dialog = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); XChangeProperty(dpy, win, wtype, XA_ATOM, 32, PropModeReplace, (unsigned char*)&dialog, 1); XSizeHints sh; sh.flags = PMinSize | PMaxSize | PSize; sh.min_width = sh.max_width = winW; sh.min_height = sh.max_height = winH; XSetWMNormalHints(dpy, win, &sh); wmDeleteAtom = XInternAtom(dpy, "WM_DELETE_WINDOW", False); XSetWMProtocols(dpy, win, &wmDeleteAtom, 1); gc = XCreateGC(dpy, win, 0, nullptr); // CRITICAL: disable GraphicsExposures so XCopyArea does not emit a NoExpose // event on every frame (which previously woke select() in an infinite 100% // CPU redraw storm). XSetGraphicsExposures(dpy, gc, False); back = XCreatePixmap(dpy, win, winW, winH, DefaultDepth(dpy, screen)); C_BG = BlackPixel(dpy, screen); C_FG = 0x33ff33; C_HEAD = 0x99ff99; C_FOOD = 0x66ff66; C_DIM = 0x2f9f2f; // Gameboy-style four-shade green palette C_GB_DARK = 0x1f7f1f; // bottom/right shadow C_GB_MED = 0x3faf3f; // settled block body C_GB_LIGHT = 0x7fdf7f; // active piece body C_GB_PALE = 0xbfffbf; // top/left highlight XSelectInput(dpy, win, KeyPressMask | StructureNotifyMask | ExposureMask | FocusChangeMask); XMapWindow(dpy, win); } static void handle_key(KeySym ks) { switch (ks) { case XK_Left: case XK_a: case XK_KP_Left: case XK_4: case XK_KP_4: if (state == PLAYING) try_move(-1); break; case XK_Right: case XK_d: case XK_KP_Right: case XK_6: case XK_KP_6: if (state == PLAYING) try_move(1); break; case XK_Up: case XK_w: case XK_KP_Up: case XK_2: case XK_KP_2: if (state == PLAYING) try_rotate(); break; case XK_Down: case XK_s: case XK_KP_Down: case XK_8: case XK_KP_8: case XK_x: if (state == PLAYING) { int cells[4][2]; piece_cells(curType, curRot, cells); if (!collide(curX, curY + 1, cells)) { curY++; resyncTimer = true; dirty = true; } else { lock_piece(); } } break; case XK_space: case XK_0: case XK_KP_0: if (state == PLAYING) hard_drop(); else if (state == PAUSED) { state = PLAYING; resyncTimer = true; dirty = true; } else if (state == GAMEOVER) reset_game(); break; // Pause: P, 3, *, and the # key (which emits XK_KP_Divide on nokia-argon). case XK_p: case XK_3: case XK_KP_3: case XK_numbersign: case XK_slash: case XK_KP_Divide: case XK_asterisk: case XK_KP_Multiply: if (state == PLAYING) { state = PAUSED; dirty = true; } else if (state == PAUSED) { state = PLAYING; resyncTimer = true; dirty = true; } break; case XK_5: case XK_KP_5: case XK_Return: case XK_KP_Enter: if (state == PLAYING) { hard_drop(); } else if (state == PAUSED) { state = PLAYING; resyncTimer = true; dirty = true; } else if (state == GAMEOVER) { reset_game(); } break; case XK_Escape: case XK_BackSpace: case XK_Delete: case XK_End: case XK_Menu: case XF86XK_Back: case XF86XK_KbdLcdMenu2: running = false; break; default: break; } } static void handle_event(XEvent& e) { if (e.type == ClientMessage) { if ((Atom)e.xclient.data.l[0] == wmDeleteAtom) running = false; } else if (e.type == ConfigureNotify) { if (e.xconfigure.width != winW || e.xconfigure.height != winH) { winW = e.xconfigure.width; winH = e.xconfigure.height; if (back) XFreePixmap(dpy, back); back = XCreatePixmap(dpy, win, winW, winH, DefaultDepth(dpy, screen)); dirty = true; } } else if (e.type == Expose) { if (e.xexpose.count == 0) dirty = true; } else if (e.type == FocusOut) { if ((e.xfocus.mode == NotifyNormal || e.xfocus.mode == NotifyGrab || e.xfocus.mode == NotifyWhileGrabbed) && state == PLAYING) { state = PAUSED; dirty = true; } } else if (e.type == KeyPress) { char buf[8]; KeySym ks = 0; XLookupString(&e.xkey, buf, sizeof(buf), &ks, nullptr); if (ks == NoSymbol) ks = XLookupKeysym(&e.xkey, 0); if (ks == XK_q || ks == XK_Q) { running = false; return; } handle_key(ks); } } int main() { srand((unsigned)time(nullptr) ^ (unsigned)getpid()); init_glyph_lut(); setup_window(); reset_game(); render(); int xfd = ConnectionNumber(dpy); int tfd = -1; #if defined(__linux__) tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); #endif int64_t nextStep = now_ns() + step_ns(); State prevState = PLAYING; resyncTimer = false; auto arm_timer = [&](int64_t deadline_ns) { if (tfd < 0) return; struct itimerspec its; its.it_interval.tv_sec = 0; its.it_interval.tv_nsec = 0; its.it_value.tv_sec = (time_t)(deadline_ns / 1000000000LL); its.it_value.tv_nsec = (long)(deadline_ns % 1000000000LL); timerfd_settime(tfd, TFD_TIMER_ABSTIME, &its, nullptr); }; auto disarm_timer = [&]() { if (tfd < 0) return; struct itimerspec its; memset(&its, 0, sizeof(its)); timerfd_settime(tfd, 0, &its, nullptr); }; arm_timer(nextStep); while (running) { fd_set fds; FD_ZERO(&fds); FD_SET(xfd, &fds); int nfds = xfd + 1; struct timeval tvbuf, *tvp = nullptr; if (tfd >= 0) { if (state == PLAYING) { FD_SET(tfd, &fds); if (tfd + 1 > nfds) nfds = tfd + 1; } } else if (state == PLAYING) { int64_t remNs = nextStep - now_ns(); if (remNs < 0) remNs = 0; tvbuf.tv_sec = (time_t)(remNs / 1000000000LL); tvbuf.tv_usec = (suseconds_t)((remNs % 1000000000LL) / 1000LL); tvp = &tvbuf; } int r = select(nfds, &fds, nullptr, nullptr, tvp); if (r < 0) { if (errno == EINTR) continue; break; } // 1) Drain pending input first so key presses are never delayed. if (FD_ISSET(xfd, &fds) || XPending(dpy)) { while (XPending(dpy)) { XEvent e; XNextEvent(dpy, &e); handle_event(e); if (!running) break; } if (!running) break; } // 2) Resync timer on state transitions, soft drop, or piece spawn. if (state != prevState || resyncTimer) { if (state == PLAYING) { nextStep = now_ns() + step_ns(); arm_timer(nextStep); } else { disarm_timer(); } prevState = state; resyncTimer = false; } else if (state == PLAYING) { // 3) Advance simulation on scheduled gravity timer expiration. bool due = false; if (tfd >= 0) { if (FD_ISSET(tfd, &fds)) { uint64_t expirations = 0; ssize_t n = read(tfd, &expirations, sizeof(expirations)); (void)n; due = true; } } else { if (now_ns() >= nextStep) due = true; } if (due) { step(); if (state == PLAYING) { if (resyncTimer) { nextStep = now_ns() + step_ns(); resyncTimer = false; } else { nextStep += step_ns(); int64_t now = now_ns(); if (now - nextStep > step_ns()) nextStep = now + step_ns(); } arm_timer(nextStep); } else { disarm_timer(); prevState = state; resyncTimer = false; } } } // 4) Repaint only when visual state actually changed. if (dirty) render(); } if (tfd >= 0) close(tfd); XFreeGC(dpy, gc); XFreePixmap(dpy, back); XDestroyWindow(dpy, win); XCloseDisplay(dpy); return 0; }