I am trying to make three difficulty settings for a "game" I am using to experiment & learn JavaScript.
I have tried by setting a variable, and three key inputs which value it 1, 2, or 3. By tying each "difficulty" setting to an if statement conditional upon one value of the aforementioned variable. The keys do successfully set the variable, but they do not impact the game in the manner I hoped.
However, if after setting the variable to a value I replace "var gameMode = 0" with "var gameMode", it will open that difficulty level. How might I go about rectifying this?
Here is what I have so far done in the menu:
var gameMode = 0;
if (gameMode === 0) {
draw = function() {
background(255, 255, 255);
fill(0, 0, 0);
text("Mover Game", 160, 200);
text(gameMode, 160, 220);
keyPressed = function() {
if (keyCode === 112) {
gameMode = 1;
}
if (keyCode === 113) {
gameMode = 2;
}
if (keyCode === 114) {
gameMode = 3;
}
};
};
}
Your code is very limited but when looking at the code,
You are setting var gameMode = 0; at the beginning and inside the keyPressed function you are just checking if the appropriate key is pressed and just assigning the value to gameMode. You have to run the game again with the newly assigned game mode.
My suggestion is to use two functions. One to run the game and other to deal with the key press and initiate the game.
function runMyGame(gameMode = 0){
// defaults the gameMode to 0 so it will start the game in 0 mode initially
// here comes your game codes
}
// adding keypress listener
document.addEventListener("keypress", myKeyPressFunction);
// function which fires on key press
function myKeyPressFunction(){
if (keyCode === 112) {
gameMode = 1;
runMyGame(gameMode);
}
if (keyCode === 113) {
gameMode = 2;
runMyGame(gameMode);
}
if (keyCode === 114) {
gameMode = 3;
runMyGame(gameMode);
}
}