Skip to content

Instantly share code, notes, and snippets.

@marttp
Created August 31, 2023 11:45
Show Gist options
  • Save marttp/c10cc227f0c5ec7adb5346bcffb51cf1 to your computer and use it in GitHub Desktop.
Save marttp/c10cc227f0c5ec7adb5346bcffb51cf1 to your computer and use it in GitHub Desktop.
Random target & obstacle for Group 5
const TARGET = 3;
const OBSTACLE = 2;
/**
*
* @param {Number} height : ความสูงของตาราง;
* @param {Number} width : ความกว้างของตาราง;
* @param {Number} ob : สิ่งกีดขวาง;
*/
function generateMap(height, width, ob) {
// -1 Target ที่เราจะเอาไปวาง
const possibleOb = height * width - 1;
if (possibleOb < ob) {
throw Error("อย่าห้าวใส่เยอะเกิน")
}
// Want table
const table = [];
// 1. Generate structure of table
for (let h = 0; h < height; h++) {
const row = [];
for (let w = 0; w < width; w++) {
row.push(0);
}
table.push(row);
}
// 2. Place target
let randomX = Math.floor(Math.random() * height);
let randomY = Math.floor(Math.random() * width);
table[randomX][randomY] = TARGET;
// 3.วางสิ่งกีดขวาง
let obstacleAmount = ob;
while (obstacleAmount > 0) {
let x = Math.floor(Math.random() * height);
let y = Math.floor(Math.random() * width);
// ถ้าชนกับ Target ให้ข้ามไปรอบใหม่ได้เลย
if (table[x][y] === TARGET) {
continue;
}
// วางได้เมื่อไหร่ค่อยลบออก
table[x][y] = OBSTACLE;
obstacleAmount--;
}
console.log(table);
}
// เรียกใช้ไอ Function ด้านบน
generateMap(5, 5, 10);
// generateMap(5, 5, 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment