Skip to content

Instantly share code, notes, and snippets.

@plastic041
Created February 15, 2023 13:22
Show Gist options
  • Save plastic041/d0f0fcea3588e01eb481bc35b18dc52c to your computer and use it in GitHub Desktop.
Save plastic041/d0f0fcea3588e01eb481bc35b18dc52c to your computer and use it in GitHub Desktop.
minecraft
const COLS = 8; // x
const ROWS = 8; // y
/**
* Finds 8 neighbors(4 cardinal directions + 4 diagonal directions)
*/
function getNeighbors(x: number, y: number) {
const neighbors = [];
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (i === 0 && j === 0) {
continue;
} else {
const newX = x + i;
const newY = y + j;
if (newX >= 0 && newX < COLS && newY >= 0 && newY < ROWS) {
neighbors.push([newX, newY]);
}
}
}
}
return neighbors;
}
/// make map
function makeMap(mineCount: number): string[][] {
const map: string[][] = new Array(ROWS);
for (let i = 0; i < ROWS; i++) {
map[i] = new Array(COLS).fill("-");
}
for (let i = 0; i < mineCount; i++) {
const x = Math.floor(Math.random() * COLS);
const y = Math.floor(Math.random() * ROWS);
if (map[y][x] === "*") {
i--;
} else {
map[y][x] = "*";
}
}
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
if (map[y][x] === "*") {
continue;
}
let count = 0;
for (const [newX, newY] of getNeighbors(x, y)) {
if (map[newY][newX] === "*") {
count++;
}
}
if (count > 0) {
map[y][x] = count.toString();
}
}
}
return map;
}
const map = makeMap(10);
for (const row of map) {
console.log(row.join(""));
}
const map = Deno.readTextFileSync("./map.txt")
.split("\n")
.map((line) => line.split(""));
const ROWS = map.length; // y
const COLS = map[0].length; // x
/**
* Finds 8 neighbors(4 cardinal directions + 4 diagonal directions)
*/
function getNeighbors(x: number, y: number) {
const neighbors = [];
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
if (i === 0 && j === 0) {
continue;
} else {
const newX = x + i;
const newY = y + j;
if (newX >= 0 && newX < COLS && newY >= 0 && newY < ROWS) {
neighbors.push([newX, newY]);
}
}
}
}
return neighbors;
}
function bfs(x: number, y: number) {
const queue: [number, number][] = [[x, y]];
const visited = new Set<string>();
let count = 0;
while (queue.length) {
const [x, y] = queue.shift()!;
if (!visited.has(`${x},${y}`)) {
visited.add(`${x},${y}`);
count++;
if (map[y][x] === "-") {
for (const [newX, newY] of getNeighbors(x, y)) {
queue.push([newX, newY]);
}
}
}
}
console.log(count);
}
bfs(0, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment