2

I'm trying to launch sketch.js when I click on the "start game" button.

Pacman general idea

This is my code:

//THIS IS THE CODE FOR SKETCH.JS WITH THE PACMAN GAME....

var rocaImage;
var foodImage;
var grapeImage;
var pacManImage;
var roca;
var myMaze;
var arrayRocasMapa = [];
var arrayComidaMapa = [];
var arrayGrapesMapa = [];
var myPacman;
var font;
var username = "Eduardo";
var song;
//Pacman resources: http://www.classicgaming.cc/classics/pac-man/
function preload() {
  rocaImage = loadImage("images/roca.bmp");
  foodImage = loadImage("images/food.png");
  grapeImage = loadImage("images/grape.png");
  pacManImage = loadImage("images/pac.png");
  song = loadSound("assets/pacman_chomp.wav");
  //  font = loadFont('assets/SourceSansPro-Regular.otf');
}

function setup() {
  createCanvas(COLUMNS * IMAGE_SIZE, ROWS * IMAGE_SIZE + HEIGHT_TEXT);
  roca = new Roca(200, 300);
  myMaze = new Maze();

  for (var i = 0; i < myMaze.rows; i++)
    for (var j = 0; j < myMaze.columns; j++) {
      if (myMaze.mapa[i][j] == 0) {
        arrayRocasMapa.push(new Roca(j * IMAGE_SIZE, i * IMAGE_SIZE));
      } else if (myMaze.mapa[i][j] == 1) {
        arrayComidaMapa.push(new Food(j * IMAGE_SIZE, i * IMAGE_SIZE));
      } else if (myMaze.mapa[i][j] == 2) {
        arrayGrapesMapa.push(new Grapes(j * IMAGE_SIZE, i * IMAGE_SIZE));
      } else if (myMaze.mapa[i][j] == 3) {
        myPacman = new Pacman(j * IMAGE_SIZE, i * IMAGE_SIZE);
      }
    }
  // Set text characteristics
  textFont("monospace"); //https://developer.mozilla.org/en-US/docs/Learn/CSS/Styling_text/Fundamentals#Web_safe_fonts
  textSize(14);
  textAlign(LEFT, CENTER); //  Constant:horizontal alignment, vertical aligntment either LEFT, CENTER, or RIGHT
  textStyle(NORMAL); //Italic o Bold
}

function draw() {
  background(0);
  //  roca.show();
  //with i i count the rows, with j the columns
  for (var i = 0; i < arrayRocasMapa.length; i++) {
    console.log("Imprimo una roca:" + i);
    arrayRocasMapa[i].show();
  }
  i = 0;
  for (i = 0; i < arrayComidaMapa.length; i++) {
    console.log("Imprimo una bola de comida:" + i);
    arrayComidaMapa[i].show();
  }
  i = 0;
  for (i = 0; i < arrayGrapesMapa.length; i++) {
    console.log("Imprimo una uva de poder:" + i);
    arrayGrapesMapa[i].show();
  }

  myPacman.show();

  for (i = 0; i < arrayComidaMapa.length; i++) {
    console.log("Compruebo si hay comida en la :" + i);
    if (myPacman.eatFood(arrayComidaMapa[i])) {
      arrayComidaMapa.splice(i, 1);
    }
  }

  for (i = 0; i < arrayGrapesMapa.length; i++) {
    if (myPacman.eatGrapes(arrayGrapesMapa[i])) {
      arrayGrapesMapa.splice(i, 1);
    }
  }

  for (i = 0; i < arrayRocasMapa.length; i++) {
    if (myPacman.eatRock(arrayRocasMapa[i])) {
      //arrayRocaMapa.splice(i,1);
    }
  }


  drawtext();
  //  addSound();
  if (arrayGrapesMapa.length == 0 && arrayComidaMapa.length == 0) {

    alert("Victory !!!");
    remove();
  }

  if (myPacman.lives == 0) {

    alert("Defeat !!!");
    remove();
  }
}

function addSound() {
  if (song.isPlaying()) { // .isPlaying() returns a boolean

  } else {
    song.play(); // playback will resume from the pause position

  }
}

function drawtext() {
  //  textSize(18);
  var textCoordY = ROWS * IMAGE_SIZE + HEIGHT_TEXT / 2;
  var txtUser = "User :" + username;
  var txtScore = "Score :" + myPacman.score;
  var txtLives = "Lives :" + myPacman.lives;

  fill('white');
  text(txtUser, 30, textCoordY);
  var cWidthUser = textWidth(txtUser) + 10 + 30;

  fill('blue');
  text(txtScore, cWidthUser, textCoordY);

  cWidthScore = textWidth(txtScore) + 10;
  fill('red');
  text(txtLives, cWidthUser + cWidthScore, textCoordY);
  // /*
  //   textSize(24);
  //   text('User', 30, ROWS*32+HEIGHT_TEXT/2);
  //   fill(0, 102, 153);
  //   text('Score', 100, ROWS*32+HEIGHT_TEXT/2);
  //   fill(0, 102, 153, 51);
  //   fill(0);
  //   text('Lives', 250, ROWS*32+HEIGHT_TEXT/2);
}

function mousePressed() {
  if (song.isPlaying()) { // .isPlaying() returns a boolean
    song.pause();
    background(255, 0, 0);
  } else {
    song.play(); // playback will resume from the pause position
    background(0, 255, 0);
  }
}

function keyPressed() {
  //  console.log("Algo pasa nenn");
  if (keyCode === 68 || keyCode === RIGHT_ARROW) //Letra d
  {
    console.log("Estoy dentro de mover derecha");
    myPacman.moveRight();
    //console.log("Estoy dentro de mover derecha");
  }
  if (keyCode === 65 || keyCode === LEFT_ARROW) // Letra a
  {
    console.log("Estoy dentro de mover izquierda");
    myPacman.moveLeft();
    //console.log("Estoy dentro de mover derecha");
  }
  if (keyCode === 87 || keyCode === UP_ARROW) // Letra W
  {
    console.log("Estoy dentro de mover arriba");
    myPacman.moveUp();
    //console.log("Estoy dentro de mover derecha");
  }
  if (keyCode === 88 || keyCode === DOWN_ARROW) // Letra X
  {
    console.log("Estoy dentro de mover abajo");
    myPacman.moveDown();
    //console.log("Estoy dentro de mover derecha");
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Pacman</title>
  <link rel="icon" href="images/ghost.png" />
  <link rel="stylesheet" type="text/css" href="css/style.css" />

</head>

<body>
  <script src="library/p5.js" type="text/javascript"></script>
  <script src="library/addons/p5.dom.js" type="text/javascript"></script>
  <script src="library/addons/p5.sound.js" type="text/javascript"></script>
  <!-- <script src="sketch.js" type="text/javascript"></script> -->
  <script src="roca.js" type="text/javascript"></script>
  <script src="maze.js" type="text/javascript"></script>
  <script src="food.js" type="text/javascript"></script>
  <script src="grapes.js" type="text/javascript"></script>
  <script src="pacman.js" type="text/javascript"></script>
  <script>
    function startGame() {

      //HERE I WANT TO LAUNCH SKETCH.JS BUT I CANT I HAVE TESTED MANY DIFFERENT ORDERS
      document.write("<script src='sketch.js' type='text\/javascript'><\/script>");

    }
  </script>
  <header>
    <h1> Pacman Game by Eduardo</h1>
  </header>
  <img src="./images/splash-image.jpg" alt="Splash image of Pacman" />
  <nav class="topnav">
    <a href="/">Settings</a>
    <a href="">Start Game</a>
    <button onclick="startGame()" class="topnav"> Start Game</button>
    <a href="">Credits</a>
  </nav>
</body>

</html>

So if i comment ( like in the code) the loading of the script sketch.js i cant go to my sketch.js where i load the maze and the game background… But i have tried many things ( document.write, innerHTML, etc…) i just want to load sketch when i click on Button startGame ( so the function startGame would be launched)… If i delete the comments, and use the script, it works ok, but i want to control when to launch sketch.js ( when i press the button Start Game and not before)

If you know of anything easier would be nice…

Also i have another doubt… i want to print some text like scores, lives and time remaining… do you use another canvas to put text on it ( perhaps in a side of the screen or in the bottom), o in the same canvas you make room to have enough space to write ??

Thanks

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107

1 Answers1

1

You could store whether the game is started in a variable at the top of your sketch:

var started = false;

function draw(){
  if(started){
    // draw your game
  }
}

function mousePressed(){
  started = true;
}

You could set started equal to true when you press the button.

Or you could look into instance mode which allows you to load a sketch on the fly. You can read more about instance mode here.

Also i have another doubt… i want to print some text like scores, lives and time remaining… do you use another canvas to put text on it ( perhaps in a side of the screen or in the bottom), o in the same canvas you make room to have enough space to write ??

Either approach is fine. It's completely up to you. You could also modify the webpage and print the score there. The P5.dom library could come in handy for this.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • Sorry for my bad english, but i wanted to start the game by pressing button start game in the index.html file, and then lunch game inside the function StartGame... I tried the instance mode but it didnt work, i just created a new p5 instance but it does nothing... nothing is loaded... So how can i change the started value from html ?? The natural way would be create a new p5 instance and dont know what to do next, perhaps p5.draw() or execute all the functions in sketch.js ( preload, setup, draw...) ... – Eduardo Gutierrez Nov 10 '18 at 17:19
  • @EduardoGutierrez No, you don't want to call the P5.js functions yourself. You'd want to set up a listener on the button, and create the sketch inside that listener. Or you could just use a boolean like in my answer. – Kevin Workman Nov 10 '18 at 17:22
  • Could you edit the code and how can i do it ? Also the starter boolean in your solution should be applied to setup and preload ( just to avoid creating the canvas or preloading images or staff that is not going to be used)...Create new p5 seems more elegant Edited: know i remembered the instance mode didnt work because i have to use sketch. in every command involving p5 like create canvas, image, load image, text...and function name like sketch.draw, sketch.setup....it didnt work for me... – Eduardo Gutierrez Nov 10 '18 at 17:32