Make macro for looping through adjacent tiles

This commit is contained in:
Camden Dixie O'Brien 2025-03-22 13:33:38 +00:00
parent 7156efc99c
commit 5b20a3e97b
3 changed files with 22 additions and 34 deletions

26
main.c
View File

@ -29,28 +29,18 @@ typedef struct {
static void setadj(puzz_t field, int x, int y, uint8_t from, uint8_t to)
{
for (int yp = y - 1; yp < y + 2; ++yp) {
for (int xp = x - 1; xp < x + 2; ++xp) {
if (xp < 0 || xp >= WIDTH || yp < 0 || yp >= HEIGHT
|| (xp == x && yp == y))
continue;
field[xp][yp] = field[xp][yp] == from ? to : field[xp][yp];
}
}
FORADJ(x, y, xi, yi)
field[xi][yi] = field[xi][yi] == from ? to : field[xi][yi];
}
static void getadj(puzz_t field, int *x, int *y, uint8_t val)
{
for (int yp = *y - 1; yp < *y + 2; ++yp) {
for (int xp = *x - 1; xp < *x + 2; ++xp) {
if (xp < 0 || xp >= WIDTH || yp < 0 || yp >= HEIGHT
|| (xp == *x && yp == *y))
continue;
if (field[xp][yp] == val) {
*x = xp;
*y = yp;
return;
}
FORADJ(*x, *y, xi, yi)
{
if (field[xi][yi] == val) {
*x = xi;
*y = yi;
return;
}
}
assert(false);

22
puzz.c
View File

@ -78,13 +78,11 @@ static void scan_copy(int x, int y, puzz_t out)
if (soln[x][y] != 0)
return;
for (int yp = y - 1; yp < y + 2; ++yp) {
for (int xp = x - 1; xp < x + 2; ++xp) {
if (xp < 0 || xp >= WIDTH || yp < 0 || yp >= HEIGHT
|| scanned[xp][yp] == YES)
continue;
scan_copy(xp, yp, out);
}
FORADJ(x, y, xi, yi)
{
if (scanned[xi][yi] == YES)
continue;
scan_copy(xi, yi, out);
}
}
@ -126,13 +124,7 @@ status_t check(puzz_t puzz)
int countadj(puzz_t field, int x, int y, uint8_t val)
{
int n = 0;
for (int yp = y - 1; yp < y + 2; ++yp) {
for (int xp = x - 1; xp < x + 2; ++xp) {
if (xp < 0 || xp >= WIDTH || yp < 0 || yp >= HEIGHT
|| (xp == x && yp == y))
continue;
n += field[xp][yp] == val ? 1 : 0;
}
}
FORADJ(x, y, xi, yi)
n += field[xi][yi] == val ? 1 : 0;
return n;
}

8
puzz.h
View File

@ -6,11 +6,17 @@
#ifndef PUZZ_H
#define PUZZ_H
#include <stdint.h>
#define WIDTH 9
#define HEIGHT 9
#define NMINES 10
#include <stdint.h>
#define FORADJ(X, Y, XI, YI) \
for (int YI = Y - 1; YI < Y + 2; ++YI) \
for (int XI = X - 1; XI < X + 2; ++XI) \
if (XI >= 0 && XI < WIDTH && YI >= 0 && YI < HEIGHT \
&& (XI != X || YI != Y))
enum { MINE = 0xff, UNKNOWN = 0xfe, SAFE = 0xfd };