Last active
August 2, 2016 02:48
-
-
Save anotheredward/93b18e489fd08dd8a68ecf2fad5f380a to your computer and use it in GitHub Desktop.
CHCH.js Roguelike with basic Line of Sight
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<pre id="maze"></pre> | |
<script> | |
'use strict' | |
const maze = [ | |
'#########', | |
'#@..#####', | |
'###.#####', | |
'#...#####', | |
'#.#######', | |
'#.#...###', | |
'#......T#', | |
'#########' | |
] | |
let map = maze.map(line => line.split('')) | |
let player = {x: 1, y: 1} | |
function render (map) { | |
let filteredMap = filterMapByLoS(map) | |
document.getElementById('maze').innerHTML = | |
filteredMap.map(characters => characters.join('')).join('<br>') | |
} | |
function getLine(x0, y0, x1, y1){ | |
var dx = Math.abs(x1-x0); | |
var dy = Math.abs(y1-y0); | |
var sx = (x0 < x1) ? 1 : -1; | |
var sy = (y0 < y1) ? 1 : -1; | |
var err = dx-dy; | |
let points = [] | |
while(true){ | |
//points.push(x0, y0) | |
points.push({x: x0, y: y0}) | |
if ((x0==x1) && (y0==y1)) break; | |
var e2 = 2*err; | |
if (e2 >-dy){ err -= dy; x0 += sx; } | |
if (e2 < dx){ err += dx; y0 += sy; } | |
} | |
return points | |
} | |
function filterMapByLoS (m) { | |
return m.map((line, y)=> | |
line.map((character, x) => { | |
let obstructed = false | |
for (let p of getLine(player.x, player.y, x, y)) { | |
if (obstructed) { | |
return ' ' | |
break; | |
} | |
if (map[p.y][p.x] === '#') obstructed = true | |
} | |
return character | |
}) | |
) | |
} | |
render(map) | |
const keyToDirection = { | |
37: {x: -1, y: 0}, | |
38: {x: 0, y: -1}, | |
39: {x: 1, y: 0}, | |
40: {x: 0, y: 1} | |
} | |
document.onkeydown = function (e) { | |
const direction = keyToDirection[e.keyCode] | |
if (direction) { | |
e.preventDefault() | |
move(direction) | |
} | |
} | |
const addPoints = (point1, point2) => | |
({x: point1.x + point2.x, y: point1.y + point2.y}) | |
function move(direction) { | |
const newPosition = addPoints(player, direction) | |
const newCharacter = map[newPosition.y][newPosition.x] | |
if (newCharacter === '.') | |
teleportPlayer(newPosition) | |
else if (newCharacter === 'T') | |
alert("Congrats! You are a winner!") | |
} | |
function teleportPlayer ({x,y}) { | |
map[player.y][player.x] = '.' | |
map[y][x] = '@' | |
player = {x, y} | |
render(map) | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment