Example of a basic typing Game with inputs
var stage = 0;
var phrases = ["Welcome to my game", "This is example of typing", "And another example"];
var inputBox; //store the text box
var userAnswer = "";
var confirmBut;
var phraseNumber = 0;
var points = 0;
function preload() {
}
function setup() {
createCanvas(640, 480);
inputBox = createInput(''); //create the text box and then hide it
inputBox.hide();
confirmBut = createButton('Confirm');
confirmBut.hide();
//function for mouse listener
confirmBut.mousePressed(function () {
checkAnswer(phraseNumber); //when button pressed run the function checkAnswer
});
}
function draw() {
if (stage == 0) {
menu();
} else if (stage == 1) {
game();
}
//mouse clicks for stages
if (stage == 0 && mouseIsPressed == true) { //menu
stage = 1; //start game
} else if (stage == 2 && mouseIsPressed == true) { //go to start screen
setTimeout(start, 1000); //prevent game from jumping stages
} else if (stage == 4 && mouseIsPressed == true) { //go to start screen
setTimeout(start, 1000); //prevent game from jumping stages
}
}
//this function returns the game to the munu -
function start() {
stage = 0;
}
//display the menu
function menu() {
background(200);
stroke(100);
textSize(20);
text("Typing Game - menu", 100, 100);
}
function game() {
background(200);
stroke(100);
textSize(20);
text("Typing Game - Game screen", 100, 100);
//show copy text
text(phrases[0], 50, 150);
//input box
inputBox.show(); //show text box
inputBox.position(40, 200); //set position
inputBox.size(400); //set the size
inputBox.input(typingIn); //key detector and then runs the finction typingIn
//confirmBut
confirmBut.show();
confirmBut.position(40, 300);
//score
text("Score: " + points, 400, 120);
}
function typingIn() {
console.log(this.value()); //write the input to the console log for testing
userAnswer = this.value();
}
function checkAnswer() {
console.log("check answer clicked");
points = 0;
//split the phrase by spaces and letters
var phraseSplit = phrases[phraseNumber].split("");
var userSplit = userAnswer.split("");
for (var i = 0; i < phraseSplit.length; i++) {
if (phraseSplit[i] == userSplit[i]) {
points++;
} else {
points--
}
}
console.log(points);
}