basic tui rendering

This commit is contained in:
David Husicka 2021-11-15 11:00:37 +01:00
parent 0db9339346
commit 6a3085af4e
3 changed files with 61 additions and 9 deletions

19
2048.c
View File

@ -1,4 +1,19 @@
#include "2048.h"
#include <stdlib.h>
#include <time.h>
void game_add_block(Game game) {
start:
size_t x, y;
int value;
x = rand() % game.field_size;
y = rand() % game.field_size;
value = (rand() % 2) + 1;
if(game.field[x][y] != 0)
game.field[x][y] = value * 2;
else
goto start;
}
Game game_init(size_t field_size) {
Game game;
@ -8,6 +23,10 @@ Game game_init(size_t field_size) {
for (size_t i = 0; i < field_size; i++) {
game.field[i] = calloc(field_size, sizeof(uint16_t) * field_size);
}
time_t t;
srand((unsigned) time(&t));
game_add_block(game);
return game;
}

9
2048.h
View File

@ -5,10 +5,11 @@
#define HEADER_2048
typedef enum Direction {
up,
down,
right,
left
NoDirection,
Up,
Down,
Right,
Left
} Direction;
typedef struct Game

42
tui.c
View File

@ -2,6 +2,9 @@
#include <stdio.h>
#include <curses.h>
const space_between_cells_x = 6;
const space_between_cells_y = 2;
// entering and leaving screen using ANSI escape sequence
void tui_init() {
initscr();
@ -16,10 +19,39 @@ void tui_destroy() {}
void tui_loop(Game *game) {
while(true){
char input = getch();
// up - 3, 107, 56
// down - 2, 106, 50
// left - 4, 104, 52
// right - 5, 108, 54
// fprintf(stderr, "%d", input);
Direction dir = NoDirection;
// these are not magic numbers
// these are just codes for arrows,
// numpad and Vim bindings
switch (input) {
case 3:
case 107:
case 56:
dir = Up;
break;
case 2:
case 106:
case 50:
dir = Down;
break;
case 4:
case 104:
case 52:
dir = Left;
break;
case 5:
case 108:
case 54:
dir = Right;
break;
}
game_move(game, dir);
// printing the game state is fun
for (size_t i = 0; i < game->field_size; i++) {
for (size_t j = 0; j < game->field_size; j++) {
mvprintw(i * space_between_cells_y, j * space_between_cells_x, "%d", game->field[i][j]);
}
}
}
}