No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

No te salgas del mapa

11/24
Recursos

Aportes 47

Preguntas 4

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad?

o inicia sesi贸n.

cuando lo cambiaba de pantalla de un monitor a otro se romp铆a y se sal铆a, as铆 que esta fue mi soluci贸n:

function moveUp(){
    if(Math.floor(playerPosicion.y) > elementSize){
        

        playerPosicion.y = (playerPosicion.y - elementSize) 
        
        movePlayer()
    }
    
}
function moveLeft(){
    if(Math.floor(playerPosicion.x) > elementSize){
        

        playerPosicion.x = (playerPosicion.x - elementSize) 
        
        movePlayer()
    }
}
function moveRight(){
    if(Math.ceil(playerPosicion.x)< 10*elementSize){
        

        playerPosicion.x = (playerPosicion.x + elementSize) 
        
        movePlayer()
    }
}
function moveDown(){
    if(Math.ceil(playerPosicion.y) < 10*elementSize){
        

        playerPosicion.y = (playerPosicion.y + elementSize) 
        
        movePlayer()
    }
}

Yo lo hice directamente en la funci贸n movePlayer; De cualquier forma ella es la encargada de renderizar la calavera

Estoy pensando en darle otro enfoque.
En vez de verificar coordenadas de Canvas, quiz谩 mejor sea ver los limites en el array bidimensional que seria el verdadero mapa del juego.

Por alguna extranha razon no me funcionaba como se resolvio en este video de ejemplo entonces opte por hacer lo siguiente鈥

Yo ps solo le puse con ternarias, y en lugar del mensaje, le puse que esa posici贸n sea igual al tama帽o del elemento, porque me estaba dando unos decimales diferentes.

function moveUp() {
    console.log(canvasElement, map.playerPosition.x)
    map.playerPosition.x - canvasElement<canvasElement
        ? map.playerPosition.x = canvasElement
        : map.playerPosition.x -= canvasElement

    startGame()
}
function moveLeft() {
    map.playerPosition.y - canvasElement<canvasElement
        ? map.playerPosition.y = canvasElement
        : map.playerPosition.y -= canvasElement
    startGame()
}
function moveRight() {
    map.playerPosition.y + canvasElement>canvasSize
        ? map.playerPosition.y = canvasSize
        : map.playerPosition.y += canvasElement
    startGame()
}
function moveDown() {
    map.playerPosition.x + canvasElement>canvasSize
        ? map.playerPosition.x = canvasSize
        : map.playerPosition.x += canvasElement
    startGame()
}

Hola , les comparto una manera que yo pienso es un poco mas corta , pero funciona.

function moveUp() {
    console.log("moveUp");
    playerPosition.y -= elementSize;
    if (playerPosition.y < 0) {
        playerPosition.y += elementSize;
    }
    startGame();
}
function moveDown(){
    console.log("moveDown");
    playerPosition.y += elementSize;
    if (playerPosition.y > elementSize * 10) {
        playerPosition.y -= elementSize;
    }
    startGame();

}
function moveRight(){
    console.log("moveRight");
    playerPosition.x += elementSize;
    if (playerPosition.x > elementSize * 11) {
        playerPosition.x -= elementSize;
    }
    startGame();
}
function moveLeft() {
    console.log("moveLeft");
    playerPosition.x -= elementSize;
    if (playerPosition.x <= elementSize) {
        playerPosition.x += elementSize;
    }
    startGame();
}

Para que sea responsive cambi茅 la posicion del jugador de absoluta como lo hizo en clase a posicion de la matriz

if (col === "O" && playerPos.x === undefined && playerPos.y === undefined) {
  playerPos.x = colIdx;
  playerPos.y = rowIdx+1; 
//hay un +1 por la forma de mi matriz
}	

entonces la funcion mover arriba, abajo etc ser铆a en unidades

function moveUp() {
  if (playerPos.y > 1) {
    playerPos.y -= 1;
    drawMap();
  }
}
function moveDown() {
  if (playerPos.y  < 10) {
    playerPos.y += 1;
    drawMap();
  }
}

No s茅 si mi soluci贸n quiz谩s sea demasiado rebuscada, pero al menos a m铆 me gusta, je je, e igualmente funciona~ La dejar茅 por aqu铆:

let mapLimits = {
	up: null,
	left: null,
	right: null,
	down: null
};
// Este es un objeto global que indica los l铆mites del mapa~

startGame() {
...
mapLimits.up = elementSize * 1;
mapLimits.left = elementSize * 1;
mapLimits.right = elementSize * 10;
mapLimits.down = elementSize * 10;
...
}
// Dentro de la funci贸n "startGame" se indican cu谩les son esos l铆mites una vez ya sabemos el tama帽o del Canvas (acorde al tama帽o de la pantalla del usuario).
function moveByKeys(keyEvent) {
	switch (keyEvent.code){
		case "ArrowUp":
			movePlayer("up");
			// console.log("arriba");
			break;
		case "ArrowLeft":
			movePlayer("left");
			// console.log("izquierda");
			break;
		case "ArrowRight":
			movePlayer("right");
			// console.log("derecha");
			break;
		case "ArrowDown":
			movePlayer("down");
			// console.log("abajo");
			break;
	}
}
// En vez de tener una 4 funciones diferentes (moveUp, moveLeft, moveRight, moveDown), tengo una sola funci贸n "movePlayer" que recibe como par谩metro la direcci贸n a la cual se quiere mover el jugador.
function movePlayer(direction) {	
	switch(direction) {
		case "up":
			if ( (playerPos.y - gridSize) >= mapLimits.up ) {
				playerPos.y -= gridSize;
				renderPlayer();
			}
			break;
			
		case "left":
			if ( (playerPos.x - gridSize) >= mapLimits.left) {
				playerPos.x -= gridSize;
				renderPlayer();
			}
			break;
			
		case "right":
			if ( (playerPos.x + gridSize) <= mapLimits.right) {
				playerPos.x += gridSize;
				renderPlayer();
			}
			break;
			
		case "down":
			if ( (playerPos.y + gridSize) <= mapLimits.down) {
				playerPos.y += gridSize;
				renderPlayer();
			}
			break;
	}

	function renderPlayer() {
		startGame();
		game.fillText(emojis["PLAYER"], playerPos.x, playerPos.y);
	}	
}

// Y dentro de esta funci贸n se verifica si la direcci贸n a la cual se quiere mover el jugador se encuentra dentro de los l铆mites del mapa. Si es as铆, se mueve sin problemas, pero si no, entonces no se mueve.

As铆 lo solucion茅

function mapLimit() {
    const canvasLimit = elementSize* 10
    if (playerPosition.x >= canvasLimit) {
        playerPosition.x -= elementSize
    }
    if (playerPosition.x < 0) {
        playerPosition.x += elementSize
    }
    if (playerPosition.y >= canvasLimit) {
        playerPosition.y -= elementSize
    }
    if (playerPosition.y < 0) {
        playerPosition.y += elementSize
    }
}

La llamar铆a despu茅s de detectar el movimiento

function movePlayer(direction) {
    moves++
    switch (direction) {
        case 'moveUp':
            playerPosition.y -= elementSize
            break;
        case 'moveLeft':
            playerPosition.x -= elementSize
            break;
        case 'moveRight':
            playerPosition.x += elementSize
            break;
        case 'moveDown':
            playerPosition.y += elementSize
            break;
        default:
            break;
    }
    mapLimit()
    printMap()
    game.fillText(emojis['PLAYER'], playerPosition.x, playerPosition.y)
}

Una alternativa

function startGame() {
  game.font = `${elementsSize}px Verdana`;
  game.textAlign = "end";

  const map = maps[0];
  const mapRows = map.trim().split("\n");
  const mapRowCols = mapRows.map((row) => row.trim().split(""));

  game.clearRect(0, 0, canvasSize, canvasSize);

  mapRowCols.forEach((row, rowIndex) => {
    row.forEach((col, colIndex) => {
      if (col == "O") {
        if (playerPosition.x === undefined) {
          playerPosition.x = colIndex;
          playerPosition.y = rowIndex;
        }
      }

      game.fillText(
        emojis[col],
        elementsSize * (colIndex + 1),
        elementsSize * (rowIndex + 1)
      );
    });
  });

  movePlayer();
}

function movePlayer() {
  game.fillText(
    emojis["PLAYER"],
    elementsSize * (playerPosition.x + 1),
    elementsSize * (playerPosition.y + 1)
  );
}

window.addEventListener("keydown", move);
btnUp.addEventListener("click", moveUp);
btnLeft.addEventListener("click", moveLeft);
btnRight.addEventListener("click", moveRight);
btnDown.addEventListener("click", moveDown);

function move(event) {
  switch (event.key) {
    // UP
    case "ArrowUp":
      moveUp();
      break;
    case "w":
      moveUp();
      break;

    // LEFT
    case "ArrowLeft":
      moveLeft();
      break;
    case "a":
      moveLeft();
      break;

    // RIGHT
    case "ArrowRight":
      moveRight();
      break;
    case "d":
      moveRight();
      break;

    // DOWN
    case "ArrowDown":
      moveDown();
      break;
    case "s":
      moveDown();
      break;
  }
}

function moveUp() {
  if (playerPosition.y === 0) {
    return;
  }

  playerPosition.y--;
  startGame();
}

function moveLeft() {
  if (playerPosition.x === 0) {
    return;
  }

  playerPosition.x--;
  startGame();
}

function moveRight() {
  if (playerPosition.x === 9) {
    return;
  }

  playerPosition.x++;
  startGame();
}

function moveDown() {
  if (playerPosition.y === 9) {
    return;
  }

  playerPosition.y++;
  startGame();
}

Esta fue mi soluci贸n

<function moveUp() {
  if (playerPosition.y < elementsSize) return console.log("Llegamos al limite");
  playerPosition.y -= elementsSize;
  console.log("Me quiero mover hacia arriba");
  startGame();
}

function moveLeft() {
  if (playerPosition.x == elementsSize)
    return console.log("Llegamos al limite");
  playerPosition.x -= elementsSize;
  console.log("Me quiero mover hacia izquierda");
  startGame();
}

function moveRight() {
  if (playerPosition.x > canvasSize) return console.log("Llegamos al limite");
  playerPosition.x += elementsSize;
  console.log("Me quiero mover hacia derecha");
  startGame();
}

function moveDown() {
  if (playerPosition.y == canvasSize) return console.log("Llegamos al limite");
  playerPosition.y += elementsSize;
  console.log("Me quiero mover hacia abajo");
  startGame();
}> 

yo solucion茅 de esta forma:

Por temas de legibilidad y complejidad el if que se tiene para cada metodo que mueve el jugador se puede optimizar, ya que, que si no queremos que imprima 鈥樷極UT鈥欌 por ejemplo quedaria vaci贸, por lo que se puede optimizar de la siguiente manera.

if (!(playerPosition.x - elementsSize) < elementsSize) {
	playerPosition.x -= elementsSize;
	startGame();
}

Mi triste solucion 馃槮

if(emoji == 'O'){
                if(playerPosition.x > canvasSize){
                    playerPosition.x = canvasSize - 10
                    alert('NO TE SALGAS DEL MAPAAAAA!')
                }else if(playerPosition.y > canvasSize){
                    playerPosition.y = canvasSize - 10
                    alert('NO TE SALGAS DEL MAPAAAAA!')
                }else if( playerPosition.y <= 0){
                    playerPosition.y = playerPosition.y + elementsSize
                    alert('NO TE SALGAS DEL MAPAAAAA!')
                }else if(playerPosition.x <=0){
                    playerPosition.x = playerPosition.x + elementsSize
                    alert('NO TE SALGAS DEL MAPAAAAA!')
                }else{
                    if(!playerPosition.x && !playerPosition.y){
                        playerPosition.x = posX
                        playerPosition.y = posY
                    }
                } 

Una alternativa que se me ocurri贸, no s茅 que tan bien este:

function startGame() {

    game.font = elementsSize + 'px Verdana';
    game.textAlign = 'end';

    const map = maps[0];
    const mapRows = map.trim().split('\n');
    const mapRowsCols = mapRows.map( row => row.trim().split(''));

    game.clearRect(0,0,canvasSize, canvasSize)

    mapRowsCols.forEach((row, rowI) => {
        row.forEach((col, colI) => {
            const emoji = emojis[col];
            const posX = elementsSize * (colI + 1);
            const posY =elementsSize * (rowI + 1);

            if (col == 'O') {
                if(!playerPosition.x && !playerPosition.y) {
                    playerPosition.x = posX;
                    playerPosition.y = posY;
                    console.log({playerPosition});
                }
              }
              
              game.fillText(emoji, posX, posY);
            });
        });
        
        if(playerPosition.x > canvasSize) playerPosition.x -= elementsSize; 
        if(playerPosition.x < (elementsSize)-1) playerPosition.x += elementsSize; 
        if(playerPosition.y > canvasSize) playerPosition.y -= elementsSize
        if(playerPosition.y < (elementsSize)-1)  playerPosition.y += elementsSize

    movePlayer();

}

Mi soluci贸n aprovechando la variable canvasSize que ya tenemos:


function moveUp(){
    if(playerPosition.y > elementsSize) {
        playerPosition.y -= elementsSize;
        startGame();
    }
    
}
function moveLeft(){
    if(playerPosition.x > elementsSize){
        playerPosition.x -= elementsSize;
        startGame();
    }
}
function moveRight(){
    if(playerPosition.x < canvasSize){
        playerPosition.x += elementsSize;
        startGame();
    }
}
function moveDown(){
    if(playerPosition.y < canvasSize) {
        playerPosition.y += elementsSize;
        startGame();
    }
} 

Yo tengo el game.textAlign = 鈥渟tart鈥

entonces, tuve que modificar el codigo

function moveUp() {
  if(playerPosition.y > elementsSize ){
    playerPosition.y -= elementsSize
    startGame()
  }
}
function moveLeft() {
  if(!playerPosition.x == 0 ){
  playerPosition.x -= elementsSize
  startGame()}
}
function moveRight() {
  if(playerPosition.x < (canvasSize -elementsSize) ){
  playerPosition.x += elementsSize
  startGame()}
}
function moveDown() {
  if(playerPosition.y < (canvasSize -elementsSize) ){
  playerPosition.y += elementsSize
  startGame()}
}

Asi lo hice:

function moveUp(){
  console.log('arriba')
  if(elemtSize<playerPos.y){
    playerPos.y -= elemtSize;
    startGame();
  }
}

function moveLeft(){
  console.log('izquierda')
  if(elemtSize<playerPos.x-elemtSize){
    playerPos.x -= elemtSize;
    startGame();
  }
}

function moveRight(){
  console.log('derecha')
  if(canvasSize>playerPos.x){
    playerPos.x += elemtSize;
    startGame();
  }
}

function moveDown(){
  console.log('abajo')
  if(canvasSize>playerPos.y+elemtSize){
    playerPos.y += elemtSize;
    startGame();
  }
}

Mi soluci贸n para el reto:

function playerMovUp(){
    console.log("Arriba")
    if (posPlayer.y > ( 2 * elementSize ) ) posPlayer.y -= elementSize
    movPlayer()
}
function playerMovLeft(){
    console.log("Izquierda")
    if ( posPlayer.x > elementSize ) posPlayer.x -= elementSize
    movPlayer()
}
function playerMovRigth(){
    console.log("Derecha")
    if (posPlayer.x < maxWidth) posPlayer.x += elementSize
    movPlayer()
}
function playerMovDown(){
    console.log("Abajo")
    if ( posPlayer.y < maxHeight ) posPlayer.y += elementSize
    movPlayer()
}

Mi soluci贸n es similar:

const canvas = document.querySelector("#game");
const context = canvas.getContext("2d");
const btnLeft = document.querySelector("#left");
const btnUp = document.querySelector("#up");
const btnRight = document.querySelector("#right");
const btnDown = document.querySelector("#down");

window.addEventListener("load", setCanvasSize);
window.addEventListener("resize", setCanvasSize);

let canvasSize;
let elementsSize;

const playerPosition = {
	x: undefined,
	y: undefined,
};

function startGame() {
	delMap();
	context.textAlign = "end";
	context.font = elementsSize + "px Verdana";

	const map = maps[0];
	const cleanMap = map.trim().split("\n");
	const matrixMap = cleanMap.map((row) => row.trim().split(""));
	matrixMap.forEach((row, rowP) => {
		row.forEach((col, colP) => {
			let posX = elementsSize * (colP + 1);
			let posY = elementsSize * (rowP + 1);

			if (
				col == "O" &&
				playerPosition.x == undefined &&
				playerPosition.y == undefined
			) {
				playerPosition.x = posX;
				playerPosition.y = posY;
			}
			context.fillText(emojis[col], posX, posY);
		});
	});
	console.log(playerPosition.x, playerPosition.y);
	movePlayer();
}
function movePlayer() {
	context.fillText(emojis["PLAYER"], playerPosition.x, playerPosition.y);
}
function delMap() {
	context.clearRect(0, 0, canvasSize, canvasSize);
}
// context.fillRect(100, 100, 1, 1);
// context.clearRect(50, 0, 100, 50);
// context.font = "30px Cabin";
// context.fillStyle = "green";
// context.textAlign = "center";
// context.fillText("Fabio", 100, 100);

function setCanvasSize() {
	canvasSize;
	if (window.innerWidth >= window.innerHeight) {
		canvasSize = innerHeight * 0.8;
	} else {
		canvasSize = innerWidth * 0.8;
	}

	canvas.setAttribute("width", canvasSize);
	canvas.setAttribute("height", canvasSize);
	elementsSize = canvasSize * 0.1;

	startGame();
}

window.addEventListener("keydown", moveByKeys);
btnLeft.addEventListener("click", moveLeft);
btnUp.addEventListener("click", moveUp);
btnRight.addEventListener("click", moveRight);
btnDown.addEventListener("click", moveDown);

function moveByKeys(event) {
	const tecla = event.key;
	switch (tecla) {
		case "ArrowLeft":
			moveLeft();
			break;
		case "ArrowUp":
			moveUp();
			break;
		case "ArrowRight":
			moveRight();
			break;
		case "ArrowDown":
			moveDown();
			break;
		default:
			break;
	}
}

function moveLeft() {
	if (playerPosition.x > elementsSize) {
		playerPosition.x -= elementsSize;
	}
	startGame();
}
function moveUp() {
	if (playerPosition.y > elementsSize) {
		playerPosition.y -= elementsSize;
	}
	startGame();
}
function moveRight() {
	if (playerPosition.x < canvasSize) {
		playerPosition.x += elementsSize;
	}
	startGame();
}
function moveDown() {
	if (playerPosition.y < canvasSize) {
		playerPosition.y += elementsSize;
	}
	startGame();
}

function moveUp(){
    if(playerPosition.y < elementSize +2){
        playerPosition.y
    }else{
        playerPosition.y -= elementSize;
        console.log(playerPosition);
        starGame();

    }
}   
function moveDown(){
    if(playerPosition.y >= canvasSize){
        playerPosition.y
    }else{
        playerPosition.y += elementSize;
        starGame();

    }
}   
function moveR(){
    if(playerPosition.x > (canvasSize-elementSize - 4)){
        playerPosition.x
    }else{
        playerPosition.x += elementSize;
        starGame();

    }
}   
function moveL(){
    if(playerPosition.x < 4){
        playerPosition.x

    }else{
        playerPosition.x -= elementSize;
        starGame();

    }
}   

Esta fue mi soluci贸n, la calaverita ya no puede escapar del mapa
obs: en la funcion move estoy utilizando Closures, por si no se entiende que esta pasando ahi

const move = (key) => {
    return () => {
        console.log(`Pressed: ${key}`)
        if(playerPosition.x && playerPosition.y) {

            if(key === "up" && (playerPosition.y > elementsSize)) {
                playerPosition.y -= elementsSize

            } else if(key === "right" && (playerPosition.x < canvasSize)) {
                playerPosition.x += elementsSize

            } else if(key === "down" && (playerPosition.y < canvasSize)) {
                playerPosition.y += elementsSize

            } else if(key === "left" && (playerPosition.x > elementsSize)) {
                playerPosition.x -= elementsSize
                
            }
    
            startGame()
            movePlayer(playerPosition.x, playerPosition.y)
            console.log({playerPosition})
        }

    }
}


btnUp?.addEventListener("click", move("up"))
btnLeft?.addEventListener("click", move("left"))
btnRight?.addEventListener("click", move("right"))
btnDown?.addEventListener("click", move("down")) 

Combine algunos codigos

function moveUp() {
  console.log("arriba");
  if (playerPosition.y - elementsSize < 1) {
    console.log("OUT");
  } else {
    playerPosition.y -= elementsSize;
    startGame();
  }
}
function moveLeft() {
  console.log("izquierda");
  if (playerPosition.x - elementsSize < 1) {
    console.log("OUT");
  } else {
    playerPosition.x -= elementsSize;
    startGame();
  }
}
function moveRight() {
  console.log("derecha");
  if (playerPosition.x + elementsSize > canvasSize * 0.9) {
    console.log("OUT");
  } else {
    playerPosition.x += elementsSize;
    startGame();
  }
}
function moveDown() {
  console.log("abajo");
  if (playerPosition.y + elementsSize > canvasSize) {
    console.log("OUT");
  } else {
    playerPosition.y += elementsSize;
    startGame();
  }
}

Para hacer que la calavera sea responsive y se adapte al tama帽o de la pantalla como hacen el resto de elementos, decid铆 hacer lo siguiente:

  1. A帽ad铆 dos nuevos valores a la constante playerPosition, que indiquen la fila y la columna en la que se encontrar铆an el jugador.
const playerPosition = {
    x: undefined,
    y: undefined,
    playerCol: undefined,
    playerRow: undefined,
}
  1. En la funci贸n startGame, establezco un valor nuevo para estas, en lugar de establecer la posici贸n en x e y. As铆, podremos calcular la posici贸n del jugador multiplicando estos valores por la variable elementsSize.
function startGame() {
    /* Insert elements with emojis */
    game.font = `${elementsSize}px Verdana`;

    /* Transform each map into a two-dimensional array */
    const map = maps[0];
    const mapRows = map.trim().split("\n")
    const mapRowsCol = mapRows.map(row => row.trim().split(""));

    /* Print each element of the map with the corresponding emoji */
    mapRowsCol.forEach((row, rowIndex) => {
        row.forEach((col, colIndex) => {
            const emoji = emojis[col];
            const posX = elementsSize * colIndex;
            const posY = elementsSize * (rowIndex + 1);

            //I associate the column and row index (plus one), instead of a fixed position. So I can calculate the initial position of the player by multiplying this index by the variable "elementsSize"
            if (playerPosition.playerCol === undefined && playerPosition.playerRow === undefined && col == "O") {
                playerPosition.playerCol = colIndex;
                playerPosition.playerRow = rowIndex + 1;
            }

            game.fillText(emoji, posX, posY);
        });
    });
  1. Cambio las funciones del movimiento del jugador para que tomen como referencia estos nuevos valores en lugar de una posici贸n fija de la siguiente forma:
function movePlayer() {
    //The reason for doing it this way, instead of associating the x and y position of the player to a fixed value, is that in this way we can make the size of the skull (player avatar) also adjust when resizing the screen
    playerPosition.x = elementsSize * playerPosition.playerCol;
    playerPosition.y = elementsSize * playerPosition.playerRow;
    game.fillText(emojis["PLAYER"], playerPosition.x, playerPosition.y);
    console.log(playerPosition);
}

function moveUp() {
    console.log("arriba");
    if (playerPosition.playerRow > 1) {
        playerPosition.playerRow -= 1;
        movePlayer();
        setCanvasSize();
    }
}
function moveLeft() {
    console.log("izquierda");
    if (playerPosition.playerCol >= 1) {
        playerPosition.playerCol -= 1;
        movePlayer();
        setCanvasSize();
    }
}
function moveRight() {
    console.log("derecha");
    if (playerPosition.playerCol < 9) {
        playerPosition.playerCol += 1;
        movePlayer();
        setCanvasSize();
    }
}
function moveDown() {
    console.log("abajo");
    if (playerPosition.playerRow <= 9) {
        playerPosition.playerRow += 1;
        movePlayer();
        setCanvasSize();
    }
}

Asi va quedando mi codigo:

const canvas = document.querySelector('#game');
const game = canvas.getContext('2d');
let canvasSize;
let elementSize;

const playerRender = {
  level: 0,
  playerPosition: {
    x: undefined,
    y:undefined,
  },
  render: function () {
    if (this.level >= maps.length) {
      return console.log("Ese mapa no existe")
    }
    const map = maps[this.level].match(/[IXO\-]+/g)
      .map(a => a.split(""))
    game.font = `${elementSize}px Verdana`;
    game.textAlign = 'center';
    game.textBaseline = 'middle';

    game.clearRect(0,0,canvasSize,canvasSize)
    map.forEach((row, rowIndex) => {
      row.forEach((col,colIndex)=>{
        const emoji = emojis[col];
        const posX = elementSize * ((colIndex - 0.42) + 1);
        const posY = elementSize * ((rowIndex - 0.32) + 1);

        if (col == 'O') {
          if (!this.playerPosition.x && !this.playerPosition.y) {
            this.playerPosition.x = posX;
            this.playerPosition.y = posY;
          }
        }

        game.fillText(emoji, posX, posY);
      });
    });
    this.movePlayer();
  },
  movePlayer: function () {
    game.fillText(emojis['PLAYER'], this.playerPosition.x, this.playerPosition.y);
  }
}



window.addEventListener('load', setCanvasSize);
window.addEventListener('resize', setCanvasSize);

function setCanvasSize() {
 canvasSize = Math.min(window.innerWidth, window.innerHeight) * 0.7;

  canvas.setAttribute('width', canvasSize);
  canvas.setAttribute('height', canvasSize);

  elementSize = canvasSize / 10.20;

  startGame();
}


function startGame() {
  playerRender.render()
}

// Mapeo entre teclas y direcciones
const keyToDirection = {
  ArrowUp: 'up',
  ArrowLeft: 'left',
  ArrowDown: 'down',
  ArrowRight: 'right',
  w: 'up',
  a: 'left',
  s: 'down',
  d: 'right'
};

const directionToButton = {
  up: document.querySelector('#up'),
  left: document.querySelector('#left'),
  down: document.querySelector('#down'),
  right: document.querySelector('#rigth'),
};

Object.keys(directionToButton).forEach(direction => {
  directionToButton[direction].addEventListener('click', () => {
      move(direction);
  });
});

window.addEventListener('keydown', moveByKey);

function moveByKey(event) {
  const direction = keyToDirection[event.key];
  if (direction) {
      move(direction);
  }
}

function move(direction) {
  console.log(`Me muevo hacia ${direction}`);
  if (direction == 'up'){
    if ((playerRender.playerPosition.y) > elementSize)console.log('OUT'),playerRender.playerPosition.y -= elementSize
  } else if(direction == 'left'){
    if ((playerRender.playerPosition.x) > elementSize)console.log('OUTLEFT'),playerRender.playerPosition.x -= elementSize
  } else if(direction == 'right'){
    if (playerRender.playerPosition.x < canvasSize - elementSize)playerRender.playerPosition.x += elementSize
  } else if(direction == 'down'){
    if (playerRender.playerPosition.y < canvasSize - elementSize)playerRender.playerPosition.y += elementSize
  }

  playerRender.movePlayer();
  startGame();
}

Yo tenia el eproblema de que mi Calavera no era responsive, y se rompia el programa, lo solucione de la siguiente manera

function movePlayer() {
  game.fillText(
    emojis["PLAYER"],
    playerPosition.x * elementSize,
    playerPosition.y * elementSize
  );
}

function moveBykeys(event) {
  if (event.key == "ArrowUp") moveUp();
  else if (event.key == "ArrowLeft") moveLeft();
  else if (event.key == "ArrowRight") moveRight();
  else if (event.key == "ArrowDown") moveDown();
}
function moveUp() {
  console.log("Arriba");
  if (playerPosition.y > 1) {
    playerPosition.y -= 1;
  }
  startGame();
}
function moveLeft() {
  console.log("Izquierda");
  if (playerPosition.x > 1) {
    playerPosition.x -= 1;
  }
  startGame();
}
function moveRight() {
  console.log("Derecha");
  if (playerPosition.x < 10) {
    playerPosition.x += 1;
  }
  startGame();
}
function moveDown() {
  console.log("Abajo");
  if (playerPosition.y < 10) {
    playerPosition.y += 1;
  }
  startGame();
}

Tambien hay que modificar la condicion en el statGame()

 if (col == "O" && !playerPosition.x && !playerPosition.y) {
        playerPosition.x = posX / elementSize;
        playerPosition.y = posY / elementSize;
      }

Reto de clase: Limitar el movimiento hacia ABAJO

_







Reto de clase: Limitar el movimiento hacia la DERECHA









Reto de clase: Limitar el movimiento hacia la IZQUIERDA









Reto de clase: Limitar el movimiento hacia ARRIBA









Esta es mi soluci贸n, la validaci贸n la hice solo para la funcion movePlayer y moveUp, etc llaman aesta funci贸n, para evitar repetir tanto el c贸digo

function renderGame() {
  if (!game) return;
  game.clearRect(0, 0, canvas.width, canvas.height);
  mapRowCols.forEach((row, i) => {
    row.forEach((col, j) => {
      const emoji = emojis[col];
      let posX = j * elementSize;
      let posY = (i + 1) * elementSize;
      game.fillText(emoji, posX, posY);
    });
  });
}

function movePlayer() {
  if (!game) return
  renderGame()
  
  if (playerPosition.x < 0) {
    playerPosition.x = 0
  }
  else if (playerPosition.x > (elementSize * 9)) {
    playerPosition.x = 9 * elementSize
  }
  else if (playerPosition.y < elementSize) {
    playerPosition.y = elementSize
  }
  else if (playerPosition.y > (elementSize * 10)) {
    playerPosition.y = 10 * elementSize
  }
  game.fillText(player, playerPosition.x, playerPosition.y);
}

Mi humilde aporte

function moveByKeys(event){
    switch(event.key){
        case 'ArrowUp':
            if(playerPosition.y > (elementSize+0.1)){
                playerPosition.y -= elementSize;
                startGame();
            }
        break;
        case 'ArrowRight':
            if(playerPosition.x < (elementSize*9)){
                playerPosition.x += elementSize;
                startGame();
            }
        break;
        case 'ArrowDown':
            if(playerPosition.y < (elementSize*9.1)){
                playerPosition.y += elementSize;
                startGame();
            }
        break;
        case 'ArrowLeft':
            if(playerPosition.x > (elementSize-0.1)){
                playerPosition.x -= elementSize;
                startGame();
            }
        break;
    }
}

Algo curioso que me pasa es que las funciones de mover arriba y mover derecha no requieren que se sume o reste el elementSize en mi c贸digo xd

function moveUp() {
    console.log("Me movere hacia arriba");
    if (playerPosition.y < elementSize) {
        console.log({playerPosition})
        console.log('OUT');
      } else {
        playerPosition.y -= elementSize;
        startGame();
      }
  }
  
function moveLeft() {
    console.log("Me movere hacia izq");
    if ((playerPosition.x - elementSize) < elementSize) {
        console.log({playerPosition})
        console.log('OUT');
      } else {
        playerPosition.x -= elementSize;
        startGame();
      }    
}
 
function moveDown() {
    console.log("Me movere hacia aba");
    if ((playerPosition.y + elementSize) > canvasSize) {
        console.log({playerPosition})
        console.log('OUT');
      } else {
        playerPosition.y += elementSize;
        startGame();
      }
}
  
function moveRight() {
    console.log("Me movere hacia dere");
    if (playerPosition.x > canvasSize) {
        console.log({playerPosition})
        console.log('OUT');
      } else {
        playerPosition.x += elementSize;
        startGame();
      }
}

Me parecen interesantes estas funciones, me pregunto si habr谩 maneras m谩s eficientes de hacerlo e,e

Mi soluci贸n para evitar que el jugador salga del canvas:

function moveUp(){ 
   if(playerPosition.y - elementSize < 0){ 
        console.log('OUT'); 
   }else{
        playerPosition.y -= elementSize; 
        starGame(); 
   }
    
};

function moveLeft(){
    if(playerPosition.x - elementSize < 0){
        console.log('OUT');
   }else{
        playerPosition.x -= elementSize;
        starGame(); 
   }
    
};

function moveRight(){
    if(playerPosition.x + elementSize > canvasSize - elementSize){
        console.log('OUT');
   }else{
        playerPosition.x += elementSize;
        starGame(); 
   }
    
};

function moveDown(){
    if(playerPosition.y + elementSize > canvasSize ){
        console.log('OUT');
   }else{
    playerPosition.y += elementSize;
        starGame(); 
   }
    
};

Comparado con mi aporte de la clase anterior, agregar un n煤mero fijo no es bueno que digamos, ya que al cambiar la resoluci贸n de pantalla, el 铆cono del jugador no llegar铆a al borde.

As铆 que hice la comparaci贸n de movimiento arriba e izquierda usando elementSize, de tal manera que en todas las vista llegu茅 hasta el borde del canvas.

Yo lo solucion茅 de una forma un poco m谩s simple:

function moveUp() {
    if ((playerPos.y - elementsSize) > 0) playerPos.y -= elementsSize;
    startGame();
}

function moveRight() {
    if (playerPos.x < canvasSize) playerPos.x += elementsSize;
    startGame();
}

function moveLeft() {
    if ((playerPos.x - elementsSize) > 0) playerPos.x -= elementsSize;
    startGame();
}

function moveDown() {
    if (playerPos.y < canvasSize) playerPos.y += elementsSize;
    startGame();
}

Yo le pas茅 la complejidad de trabajar con elementSize a mi metodo drawPlayer, y el player solo maneja datos tales como {x:1, y:9} viendos茅 todo el c贸digo as铆:

const canvas = document.querySelector("#game");
const game = canvas.getContext("2d");
const btnUp = document.querySelector("#up");
const btnDown = document.querySelector("#down");
const btnLeft = document.querySelector("#left");
const btnRight = document.querySelector("#right");

let elementSize;
let canvasSize;

const player = {
  x: undefined,
  y: undefined,
};

window.addEventListener("load", resizeCanvas);
window.addEventListener("resize", resizeCanvas);
window.addEventListener("keydown", moveByKeys);
btnUp.addEventListener("click", moveUp());
btnDown.addEventListener("click", moveDown);
btnLeft.addEventListener("click", moveLeft);
btnRight.addEventListener("click", moveRight);

function moveByKeys(event) {
  if (event.code === "ArrowUp") moveUp();
  else if (event.code === "ArrowDown") moveDown();
  else if (event.code === "ArrowLeft") moveLeft();
  else if (event.code === "ArrowRight") moveRight();
  drawMap();
}

function startGame() {
  game.font = elementSize + "px Verdana";
  game.textAlign = "start";
  game.textBaseline = "top";
  drawMap();
  drawPlayer();
}

function getMap(level) {
  return maps[level].match(/[\-IXO]+/g).map((a) => a.split(""));
}

function drawMap() {
  game.clearRect(0, 0, canvas.width, canvas.height);
  const map = getMap(2);

  map.forEach((rows, row) => {
    rows.forEach((key, col) => {
      const emoji = emojis[key];
      const posX = col * elementSize;
      const posY = row * elementSize;
      game.fillText(emoji, posX, posY);
      if ((player.x === undefined || player.y === undefined) && key === "O") {
        player.x = col;
        player.y = row;
      }
    });
  });
  drawPlayer();
}

function drawPlayer() {
  const emoji = emojis["PLAYER"];
  const posX = player.x * elementSize;
  const posY = player.y * elementSize;
  game.fillText(emoji, posX, posY);
}

function resizeCanvas() {
  canvasSize = Math.min(window.innerHeight, window.innerWidth) * 0.85;
  canvas.setAttribute("width", canvasSize);
  canvas.setAttribute("height", canvasSize);
  elementSize = (canvasSize / 10) * 0.98;
  startGame();
}

function moveUp() {
  if (player.y > 0) player.y -= 1;
}

function moveDown() {
  if (player.y < 9) player.y += 1;
}

function moveLeft() {
  if (player.x > 0) player.x -= 1;
}

function moveRight() {
  if (player.x < 9) player.x += 1;
}

Mi aporte

 function moveUp () {
        console.log (playerPosition.y);
        if (playerPosition.y < elementsSize*2) {
            console.log('nos caimos');
        }else {
            playerPosition.y -= elementsSize;
            startGame();
        }

logr茅 encontrar el detalle para centrar los emojis, fue jugando con estos datos de las posiciones en columnas y filas

mapRowCols.forEach((row, rowI) => {
        row.forEach((col, colI) => {
            const emoji = emojis[col];
            const posX = (elementsSize * (colI + 1.2));
            const posY = (elementsSize * (rowI + 0.8));

por si alguien le pasaba los mismo ahora me quedo bonito jejejeje:

Bueno el detalle cuando se cambia de pantalla, seg煤n vi la respuesta del profe que el problema son los decimales, a mi me funcion贸 usando la funcion Math.floor()

pero solo al inicio en el tama帽o del canvas:


function setCanvasSize() {

    if (window.innerHeight > window.innerWidth) {
        canvasSize = window.innerWidth * 0.7;
    }
    else {
        canvasSize = window.innerHeight * 0.7;
    }
    canvasSize = Math.floor(canvasSize);
...
el 煤nico detalle que aun no he revisado es para que todos los emojis queden en la pantalla y no tan salidos algunos en las esquinas inferiores y izquierda.. 

Cuando se redimensiona se ven en errores para renderizar la posici贸n del jugador, para esto lo que hice fue dinamizar la posici贸n y 鈥hookearla鈥 al resize, us茅 getters para lograr este comportamiento (para que la obtenci贸n de las posiciones est茅 estrechamente ligada a las medidas actuales del canvas), tambi茅n hice que la posici贸n del jugador se basara en la posici贸n de casillero y no en medidas est谩ticas

const playerPostion = {
    xIndex: undefined,
    yIndex: undefined,
    get xPos() {
        return this.xIndex*elementsSize;
    },
    get yPos() {
        return (this.yIndex+1)*elementsSize;
    }	
}```

Despu茅s se puede adaptar el comportamiento de posici贸n en el canvas para (no de medida) para los l铆mites del campo y dem谩s cuestiones

No he visto el video pero aqui esta mi solucion鈥 creo que esta ok, ya veremos :p

function movementControl() {
if(playerPosition.x < 0)playerPosition.x = playerPosition.x + blocksSize;
else if(playerPosition.x > canvasSize)playerPosition.x = playerPosition.x - blocksSize;
else if(playerPosition.y < 0)playerPosition.y = playerPosition.y + blocksSize;
else if(playerPosition.y > canvasSize)playerPosition.y = playerPosition.y - blocksSize;
};```

Mi solucion fue la siguiente

function moveUp() { 
  if(!(playerPosition.y - elementsSize < elementsSize)) {
    playerPosition.y -= elementsSize;
    startGame();
  } 
}

function moveDown() {
  if(!(playerPosition.y + elementsSize > canvasSize)) {
    playerPosition.y += elementsSize;
    startGame();
  }
}

function moveLeft() {
  if(!(playerPosition.x - elementsSize < elementsSize)) {
    playerPosition.x -= elementsSize;
    startGame();
  } 
}

function moveRight() {
  if(!(playerPosition.x + elementsSize > canvasSize)) {
    playerPosition.x += elementsSize;
    startGame();
  }   
}

Comparto mi solucion redondeando las variables

function moveUp() {
  console.log('Me quiero mover hacia arriba');
  if(playerPosition.y.toFixed(2)>elementsSize) playerPosition.y -= elementsSize;
  startGame();
}
function moveLeft() {
  console.log('Me quiero mover hacia izquierda');
  if(playerPosition.x.toFixed(2)>elementsSize) playerPosition.x -= elementsSize;
  startGame();
}
function moveRight() {
  console.log('Me quiero mover hacia derecha');
  if(playerPosition.x.toFixed(2)<elementsSize*10) playerPosition.x += elementsSize;
  startGame();
}
function moveDown() {
  if(playerPosition.y.toFixed(2)<elementsSize*10) playerPosition.y += elementsSize;
  console.log('Me quiero mover hacia abajo');
  startGame();
}
``


Mi solucion es la siguiente

const canvas = document.querySelector('#game');
const game = canvas.getContext('2d');
const btnUp = document.getElementById('up');
const btnDown = document.getElementById('down');
const btnLeft = document.getElementById('left');
const btnRight = document.getElementById('right');

let canvasSize;
let elementsSize;

const playerPosition = {
    x: '',
    y: '',
    initialX: '',
    initialY: '',
}

window.addEventListener('load', setCanvasSize);
window.addEventListener('resize', setCanvasSize);



function setCanvasSize() {
    if (window.innerHeight > window.innerWidth) {
        canvasSize = window.innerWidth * 0.8
    } else {
        canvasSize = window.innerHeight * 0.8
    }
    
    canvas.setAttribute('width', canvasSize+16);
    canvas.setAttribute('height', canvasSize+16);
    elementsSize = canvasSize /10;
        
    startGame();
}

function renderMap() {
    game.font = `${elementsSize}px Verdana`;
    game.textAlign = 'end';
    
    const map = maps[0];
    const mapRows = map.trim().split('\n'); //trim() es un metodo que remueve los espacios en blanco de los treing y lo devuelve en un nuevo `string` sin modificar el original, el .split, elimina el caracter que se le indique en el argumento
    const mapRowsCols = mapRows.map(row => row.trim().split(''));
    game.clearRect(0, 0, canvasSize, canvasSize);
    mapRowsCols.forEach((row, rowIndex) => {
        row.forEach((col, colIndex) => {
            const emoji = emojis[col];
            const posX = (elementsSize * (colIndex + 1))+12;
            const posY = elementsSize * (rowIndex + 1);
            if (col == 'O') {
                playerPosition.initialX = posX;
                playerPosition.initialY = posY;              
              };
            game.fillText(emoji, posX, posY);                        
        });
    });
}

function renderPlayerPosition(){
    game.fillText(emojis['PLAYER'], playerPosition.initialX, playerPosition.initialY)
}

function startGame() {
    renderMap()
    renderPlayerPosition()
    playerPosition.x = playerPosition.initialX;
    playerPosition.y = playerPosition.initialY;
}

        
function movePlayer() {        
    game.fillText(emojis['PLAYER'], playerPosition.x, playerPosition.y)    
}
    
window.addEventListener('keyup', moveByKeys)
btnUp.addEventListener('click', moveUp);
btnLeft.addEventListener('click', moveLeft);
btnRight.addEventListener('click', moveRight);
btnDown.addEventListener('click', moveDown);

function moveByKeys(event) {
    
    switch (event.key) {
        case "ArrowUp": moveUp(); break;
        case "ArrowLeft": moveLeft(); break;
        case "ArrowRight": moveRight(); break;
        case "ArrowDown": moveDown(); break;
    }

}

function moveUp() {
    console.log('Me quiero mover hacia arriba');      
    renderMap();    
    console.log(playerPosition.y, elementsSize);
    if (playerPosition.y <= elementsSize*2) {
        movePlayer();
        console.log('Ya no puedo subir mas');
        return
    }
    playerPosition.y -= elementsSize;
    console.log({playerPosition});
    movePlayer();
}
function moveLeft() {
    console.log('Me quiero mover hacia a la izquierda');
    renderMap();
    console.log(playerPosition.x, elementsSize);
    if (playerPosition.x <= elementsSize*2) {
        movePlayer();
        console.log('Ya no puedo ir mas a la izquierda');
        return
    }
    playerPosition.x -= elementsSize;
    console.log({playerPosition});
    movePlayer();
}
function moveRight() {
    console.log('Me quiero mover hacia a la derecha');
    renderMap();
    console.log(playerPosition.x, canvasSize);
    if (Math.ceil(playerPosition.x) >= canvasSize) {
        movePlayer();
        console.log('Ya no puedo ir m谩s a la derecha');
        return
    }
    playerPosition.x += elementsSize;
    console.log({playerPosition});
    movePlayer();
}
function moveDown() {
    console.log('Me quiero mover hacia abajo');
    renderMap();
    console.log(playerPosition.y,canvasSize);
    if (Math.ceil(playerPosition.y) >= canvasSize) {
        movePlayer();
        console.log('Ya no puedo bajar mas');
        return
    }
    playerPosition.y += elementsSize;
    console.log({playerPosition});
    movePlayer();
}