Search code examples
javascripthtml-tablemaze

Stop character at maze wall Javascript


I am making a maze game, and I'm using a table for the maze layout. The character moves flawlessly, but it goes through the walls For the walls, I am using something like <td style="border-right:10px solid #000000;">. It works, but the character is pretty much a ghost. Is there a way to make the character stop when it reaches a border? My maze is at http://thomaswd.com/maze.


Solution

  • Since you're using jQuery, and the walls are shown by the class on the cell, you could check if the cell you're trying to move into has a wall using jQuery's hasClass method.

    function up() {
        //check if the cell has a border on the bottom
        if ($("#td" + (algernon - 8)).hasClass('b')) return;
        $("td").css("background","transparent");
        algernon -= 8;
        setTimeout("refresh()", 0);
    }
    
    function down() {
        //check if the cell has a border on the top
        if ($("#td" + (algernon + 8)).hasClass('t')) return;
        $("td").css("background","transparent");
        algernon += 8;
        setTimeout("refresh()", 0);
    }
    
    function leftclick() {
        //check if the cell has a border on the right
        if ($("#td" + (algernon - 1)).hasClass('r')) return;
        $("td").css("background","transparent");
        algernon -= 1;
        setTimeout("refresh()", 0);
    }
    
    function rightclick() {
        //check if the cell has a border on the left
        if ($("#td" + (algernon + 1)).hasClass('l')) return;
        $("td").css("background","transparent");
        algernon += 1;
        setTimeout("refresh()", 0);
    }
    

    I hope this helps