Implement puzzle generation
This commit is contained in:
parent
540a47c37b
commit
0561639aa6
25
main.c
Normal file
25
main.c
Normal file
@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Copyright (c) Camden Dixie O'Brien
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
#include "puzz.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
struct timeval tv;
|
||||
if (gettimeofday(&tv, NULL) != 0) {
|
||||
perror("Failed to get time");
|
||||
exit(1);
|
||||
}
|
||||
srand(tv.tv_usec);
|
||||
|
||||
gen();
|
||||
print();
|
||||
|
||||
return 0;
|
||||
}
|
50
puzz.c
Normal file
50
puzz.c
Normal file
@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright (c) Camden Dixie O'Brien
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
#include "puzz.h"
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static puzz_t soln;
|
||||
|
||||
void gen(void)
|
||||
{
|
||||
memset(soln, 0, sizeof(soln));
|
||||
|
||||
for (int i = 0; i < NMINES; ++i) {
|
||||
int x, y;
|
||||
do {
|
||||
x = rand() % WIDTH;
|
||||
y = rand() % HEIGHT;
|
||||
} while (soln[x][y] == MINE);
|
||||
soln[x][y] = MINE;
|
||||
}
|
||||
|
||||
for (int y = 0; y < HEIGHT; ++y) {
|
||||
for (int x = 0; x < WIDTH; ++x) {
|
||||
if (soln[x][y] == MINE)
|
||||
continue;
|
||||
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)
|
||||
continue;
|
||||
soln[x][y] += soln[xp][yp] == MINE ? 1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void print(void)
|
||||
{
|
||||
for (int y = 0; y < HEIGHT; ++y) {
|
||||
for (int x = 0; x < WIDTH; ++x)
|
||||
putchar(soln[x][y] == MINE ? 'x' : '0' + soln[x][y]);
|
||||
putchar('\n');
|
||||
}
|
||||
}
|
22
puzz.h
Normal file
22
puzz.h
Normal file
@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright (c) Camden Dixie O'Brien
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
#ifndef PUZZ_H
|
||||
#define PUZZ_H
|
||||
|
||||
#define WIDTH 10
|
||||
#define HEIGHT 10
|
||||
#define NMINES 10
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
enum { MINE = 0xff };
|
||||
|
||||
typedef uint8_t puzz_t[WIDTH][HEIGHT];
|
||||
|
||||
void gen(void);
|
||||
void print(void);
|
||||
|
||||
#endif
|
Loading…
x
Reference in New Issue
Block a user