just some cleanup

This commit is contained in:
2024-12-19 23:37:28 +03:00
parent cbd218eaad
commit f4012e2c84
5 changed files with 52 additions and 15 deletions

2
.gitignore vendored
View File

@@ -1 +1,3 @@
*~
bin/*
# ignore files without extension with [^\.]*

View File

@@ -1,2 +1,2 @@
make all:
gcc mine.c -o mine -lraylib -lGL -lm -lpthread -ldl -lrt -lX11
gcc ../util.c mine.c -o ../bin/mine -lraylib -lGL -lm -lpthread -ldl -lrt -lX11

View File

@@ -1,18 +1,23 @@
#include "raylib.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "../util.h"
typedef char cell;
#define MINE 0b10000000
#define MARKED 0b01000000
#define EXPOSED 0b00100000
#define NUMBERED 0b00000111
/*
0000 0000
^^ ^^^
|| number
|1 if marked
1 if mine
cell is a char (8 bits)
0000 0000
^^^ ^^^
||| number of mine neigbours
|||> 1 if exposed (revealed)
||> 1 if marked
|> 1 if mine
*/
typedef struct minefield_t {
@@ -21,6 +26,14 @@ typedef struct minefield_t {
cell* cells;
} Minefield;
static inline cell get_cell(Minefield* mf, int r, int c){
return mf->cells[r * mf->col + c];
}
static inline cell set_cell(Minefield* mf, int r, int c, cell cell){
return mf->cells[r * mf->col + c] = cell;
}
Minefield make_minefield(int row, int col, int mine_count){
Minefield mf = {.row = row, .col = col};
int size = mf.row * mf.col;
@@ -47,20 +60,16 @@ Minefield make_minefield(int row, int col, int mine_count){
// Place numbers
for (int i = 0; i < mf.row; i++){
for (int j = 0; j < mf.col; j++){
if (!(mf.cells[i * mf.col + j] & MINE)){
if (!(get_cell(&mf, i, j) & MINE)){
cell c = 0;
for (int ii = i - 1; ii <= i + 1; ii++){
for (int jj = j - 1; jj <= j + 1; jj++){
if (ii < 0 || ii >= mf.row
|| jj < 0 || jj >= mf.col){
continue;
}
if (mf.cells[ii * mf.col + jj] & MINE){
for (int ii = imax(i - 1, 0); ii < imin(i + 2, mf.row); ii++){
for (int jj = imax(j - 1, 0); jj < imin(j + 2, mf.col); jj++){
if (get_cell(&mf, ii, jj) & MINE){
c++;
}
}
}
mf.cells[i * mf.col + j] = c;
set_cell(&mf, i, j, c);
}
}
}
@@ -115,6 +124,7 @@ void draw_minefield(Minefield* mf){
}
int main(){
srand(time(NULL));
Minefield mf = make_minefield(10, 20, 30);
print_minefield(&mf, stdout);

4
util.c Normal file
View File

@@ -0,0 +1,4 @@
#include "util.h"
int imax(int a, int b);
int imin(int a, int b);

21
util.h Normal file
View File

@@ -0,0 +1,21 @@
/*
Utility definitions shared by games
*/
#ifndef GAMES_UTIL_H
#define GAMES_UTIL_H
/* https://stackoverflow.com/questions/3437404/min-and-max-in-c
https://www.reddit.com/r/C_Programming/comments/1aoan41/apparently_inline_is_being_a_dumbo_in_c99_and/
I am so confused...
*/
inline int imax(int a, int b){
return a > b ? a : b;
}
inline int imin(int a, int b){
return a < b ? a : b;
}
#endif