HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URL's added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<body onload="go()">
<audio id="tone0" type="audio/mpeg" src=" "></audio>
<audio id="tone1" type="audio/mpeg" src=" "></audio>
<audio id="tone2" type="audio/mpeg" src=" "></audio>
<audio id="tone3" type="audio/mpeg" src=" "></audio>
<div class="topp">
<div id="faceType" class="box bord">
<div id="color" class="imageContainer" onclick="imageColor()"></div>
<div id="graphic" class="graph" onclick = "imageGraphic()">
<img id="graphicImage" src=" " class="image">
</div>
<div id="texture" class="graph" onclick = "imageTexture()">
<img id="textureImage" src=" " class="image">
</div>
</div>
<div id="algorithm" class="box bord">
<div id="algorithm0" class="radioButton bordSq" onClick="algorithmButtonClick(0)">
normal</div>
<div id="algorithm1" class="radioButton bordSq" onClick="algorithmButtonClick(1)">
strict</div>
</div>
<div id="sound" class="box bord">
<div id="sound0" class="sounds bordSq" onClick="soundButtonClick(0)">tone</div>
<div id="sound1" class="sounds bordSq" onClick="soundButtonClick(1)">chord</div>
</div>
<div id="admin" class="ctrls bord">
<div id="start" class="adminx bordSq1" onclick="adminStart()">(re)start</div>
<div id="stop" class="adminx bordSq1" onclick="adminPause()">pause</div>
<div id="reset" class="adminx bordSq1" onclick="adminReset()">reset</div>
</div>
<div id="mdl" class="box bord">
<div id="simon" class="smn" >Simon Says</div>
<div id="nmbr" class="smn">00</div>
</div>
<div id="b0" class="box1 shad" onclick = "boxClick(0)">
<img id="boxImg0" class="boxImg shad" src=" ">
</div>
<div id="b1" class="box1 shad" onclick = "boxClick(1)">
<img id="boxImg1" class="boxImg shad" src=" " ">
</div>
<div id="b2" class="box1 shad" onclick = "boxClick(2)">
<img id="boxImg2" class="boxImg shad" src=" " ">
</div>
<div id="b3" class="box1 shad" onclick = "boxClick(3)">
<img id="boxImg3" class="boxImg shad" src=" " ">
</div>
</div>
</body>
$wholeHeight: 700px;
$rectHeight: 100px;
$spaceHeight: 100px;
.topp {
background-color: hsl(0,0,75%);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: $wholeHeight;
}
.box{
position: absolute;
top: $spaceHeight;
left: 0;
width: 50px;
background-color: green;
box-sizing: border-box;
text-align: center;
}
.box1{
@extend .box;
backgrond-color: orange;
}
.ctrls {
position: absolute;
left: 0;
top: 0;
box-sizing: border-box;
width: 60px;
height: 15px;
text-align:center;
z-index: 5; //put these on top
}
.adminx{
@extend .ctrls;
padding-bottom: 2px;
}
.imageContainer{
position: absolute;
left: 0;
top: 0;
box-sizing: content-box;
background-color: white;
border: 1px solid black;
}
.imageContainer:hover{
@extend .imageContainer;
border:2px solid red;
cursor: pointer;
}
.graph{
@extend .imageContainer;
box-sizing: content-box;
}
.graph:hover{
@extend .graph;
border: 2px solid red;
cursor: pointer;
}
.radioButton{
@extend .adminx;
}
.radioButton:hover{
cursor: pointer;
}
.sounds{
@extend .adminx;
}
.sounds:hover{
cursor: pointer;
}
.image{
display: block;
width: 100%;
height:auto;
}
.boxImg{
display: none;
width: 100%;
height: auto;
}
.shad{
border-radius: 50%;
}
.bord{
border-radius: 50%;
}
.smn{
position: absolute;
left: 0;
top: 0;
text-align:center;
}
.bordSq{
border: 1px solid hsl(0,0%,50%);
box-shadow: inset 0 0 1px 1px hsl(0,0%,50%);
}
.bordSq1{
border: 1px solid hsl(0,0%,50%);
box-sizing: content-box;
}
/* *************************************************
GLOBALS - CONSTANTS, FUNCTIONS
***************************************************** */
// CALLBACKS are at the end of the script
window.onresize=resized;
const buttonDisabledColor = "hsl(0,0%,60%)";
const buttonActiveColor = "hsl(50,80%,75%)";
const buttonClickColor = "hsl(50,80%,95%)"; // SYNCH WITH STYLE SHEET
const imageClickOpacity = .3;
const imageBackgroundColor = "white";
const boxClickColor = "hsl(275,80%,90%)";
const boxErrorColor = "hsl(0,0%,30%)";
const buttonNormalBorder="1px solid hsl(0,0%,50%)";
const rbOffColor="hsl(50,30%,50%)"; // for radio button not selected
// FOR CLASSES Rectangle, ImageRectangle
const edgeFract = .05; // indentation
const heightFract = .5; // ratio of box height to width
const maxWinWidth = 800; // convert to pixels eventually
const minWinWidth = 300;
const topRow = 100; // pixels - space at top of screen
// FOR CLASS SimpleButton
const simpleButtonMaxHeight = 20;
const simpleButtonMinHeight = 10;
const simpleButtonMaxWidth = 70;
const simpleButtonMinWidth= simpleButtonMaxWidth*(simpleButtonMinHeight/simpleButtonMaxHeight);
const sbMaxFontSize = 17;
const sbMinFontSize = 10;
// FOR IMAGE SELECTORS
const imageHeightFract = .25;
// FOR RADIO BUTTONS
const radioButtonMaxHeight = 25;
const radioButtonMinHeight = 12;
const rbMaxFontSize = 20;
const rbMinFontSize = 10;
const radioButtonMaxWidth = 80;
const radioButtonMinWidth = radioButtonMaxWidth*(radioButtonMinHeight/radioButtonMaxHeight);
// FOR TEXT
txtMinFontSize = 14;
txtMaxFontSize = 35;
// MAX NUMBER OF MEMORIZE STEPS
const maxNumStore = 20;
// STRICT/NONSTRICT
const STRICT = 0
const NONSTRICT = 1;
const TONE = 0;
const CHORD = 1;
/* Returns a random integer between min (included) and max (excluded)
Using Math.round() will give you a non-uniform distribution!
This is stolen directly from the MDN web site. */
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function interpolate(min, max){
var factor = (windowWidth()-minWinWidth)/(maxWinWidth-minWinWidth);
return min + (max - min)*factor;
}
function windowWidth(){
var w = window.innerWidth;
if(w > maxWinWidth) w = maxWinWidth;
return w;
}
function pix(num){ return (num + "px");}
class BoxConfiguration{
constructor(){
this.type="initial";
this.boxColors = ["red","yellow","green","blue"];
this.soundType = "tone";
this.faceType = "color";
this.algorithm = "normal";
};
};
/* *************************************************
class RECTANGLE
***************************************************** */
class Rectangle{
constructor(id, type, rowNum, colNum, color){
this.id = id;
this.element = document.getElementById(id);
this.colNum = colNum; // 0,1,2
this.rowNum = rowNum; // 0,1,2
this.color = color; // background color
this.audio; // instance of class Audio
};
width(){
return ( (windowWidth()/3)*(1 - 2*edgeFract) );
};
height(){
return heightFract*this.width();
};
edgeWidth(){
return windowWidth()*edgeFract;
};
setColor(col){
if(col === undefined)
this.element.style.backgroundColor = this.color;
else
this.element.style.backgroundColor = col;
};
xPos(){
return ( this.edgeWidth() + this.colNum*this.width() );
};
yPos(){
return ( topRow + this.rowNum*this.height() );
};
setAudio(audioObj){
this.audio = audioObj;
};
render(){
this.element.style.top = pix( this.yPos() );
this.element.style.left = pix( this.xPos() );
this.element.style.width = pix( this.width() );
this.element.style.height = pix( this.height() );
this.setColor();
};
setIndicatorForMemorization(){
this.setColor(boxClickColor);
this.audio.play();
};
undoIndicatorForMemorization(){
this.setColor(); // sets to usual color
this.audio.stop();
};
setIndicatorForUserClick(){
this.setColor(boxClickColor);
this.audio.play();
};
undoIndicatorForUserClick(){
this.setColor();
this.audio.stop();
};
setIndicatorForError(){
this.setColor(boxErrorColor);
this.audio.play();
};
undoIndicatorForError(){
this.setColor();
this.audio.stop();
};
cleanup(){
};
showImage(){
};
log(){
console.log("id: " + this.id + " col: " + this.colNum + " row: " + this.rowNum);
console.log("window width: " + windowWidth());
console.log("xPos: " + this.xPos());
console.log("yPos: " + this.yPos());
console.log("width: " + this.width());
console.log("height: " + this.height());
console.log("color: " + this.color);
};
}; // end Rectangle
/* *************************************************
class IMAGE RECTANGLE
***************************************************** */
/*
class ImageRectangle puts an image in the clickable boxes instead of colors.
rect is a Rectangle object - the same box, but configured with a color.
This class configures it with an image.
*/
class ImageRectangle extends Rectangle{
constructor(rect, imageId, imagePath){
super(rect.id, rect.type,rect.rowNum, rect.colNum, imageBackgroundColor);
this.imageId = imageId;
this.imageElement = document.getElementById(imageId);
this.imagePath = imagePath;
this.setAudio(rect.audio);
};
showImage(){
this.imageElement.style.display="block";
this.imageElement.style.opacity = 1;
this.imageElement.src = this.imagePath;
};
cleanup(){
this.imageElement.style.display="none";
this.imageElement.style.opacity = 1;
};
setIndicatorForMemorization(){
this.imageElement.style.opacity = imageClickOpacity;
this.audio.play();
};
undoIndicatorForMemorization(){
this.imageElement.style.opacity = 1;
this.audio.stop();
};
setIndicatorForUserClick(){
this.imageElement.style.opacity = imageClickOpacity;
this.audio.play();
};
undoIndicatorForUserClick(){
this.imageElement.style.opacity = 1;
this.audio.stop();
};
setIndicatorForError(){
this.imageElement.style.opacity = imageClickOpacity;
this.audio.play();
};
undoIndicatorForError(){
this.imageElement.style.opacity = 1;
this.audio.stop();
};
}; // end class ImageRectangle
/* *************************************************
class AUDIO
***************************************************** */
/*
directory should include "/" at end
id is id of audio element
We assume two sounds available, indexed by 0 and 1.
*/
class Audio{
constructor(id, dir, fileName0, fileName1){
this.dir = dir;
this.fileNames = [fileName0, fileName1];
this.playing = 0;
this.context = new webkitAudioContext();
this.source;
this.buffers=[undefined,undefined]; //AudioBuffer fo each source
this.loadFiles(0);
this.loadFiles(1);
/*
this.id = id;
this.element = document.getElementById(id);
this.element.src = dir + fileName0;
this.element.load();
*/
}; // end construtor
loadFiles(i){
var what = this;
var url = this.dir + this.fileNames[i];
console.log(url);
var request = new XMLHttpRequest();
request.responseType = 'arraybuffer';
request.onload = function() {
what.context.decodeAudioData(request.response, function(buffer)
{
console.log(request.response);
console.log(buffer);
what.buffers[i] = buffer; // an AudioBuffer instance
}
);
}
request.open('GET', url, true);
request.send();
}; // end loadFiles
play(){
//this.element.play();
this.source = this.context.createBufferSource(); // must do this each time
this.source.buffer = this.buffers[this.playing]; // tell the source which sound to play
this.source.connect(this.context.destination);
this.source.start(0);
};
stop(){
this.source.stop();
};
setPlaying(num){
this.playing = num;
};
}; // end class Audio
/* *************************************************
class FACE TYPE SELECTORS
***************************************************** */
/*
class FaceTypeSelectors are for the selectors in the upper left corner.
If imagePath is undefined,this just draws a rectangle with a color..
colNum is not used.
*/
class FaceTypeSelectors extends Rectangle{
constructor(id, type, rowNum, graphicImageId, color, parentObj, imagePath){
super(id,type,rowNum, undefined, color);
this.imagePath = imagePath;
this.parentObj = parentObj;
this.graphicImageId = graphicImageId;
this.imageElement;
if(graphicImageId !== undefined){
this.imgElement = document.getElementById(graphicImageId);
if(imagePath !== undefined) this.imgElement.src=imagePath;
}
};
width(){
var wid = this.parentObj.width();
return (wid* imageHeightFract);
};
height(){
return this.parentObj.height()*imageHeightFract;
};
edge(){
return 0;
};
xPos(){
return ( (this.parentObj.width() - this.width())/2 );
};
yPos(){
var ht0 = 3*this.height();
var pht = this.parentObj.height();
var tp = Math.floor((pht - ht0)/4);
if(tp < 0) tp=0;
return tp + this.rowNum*(tp + this.height());
};
};// end class FaceTypeSelectors
/* *************************************************
class SIMPLE BUTTON
***************************************************** */
/*
class SimpleButton is for the orange buttons in the lower right corner.
*/
class SimpleButton{
constructor(id, rowNum, parent){
this.id = id;
this.parent = parent; // an instance of Rectangle
this.element = document.getElementById(id);
this.rowNum = rowNum; //0,1,2
this.disabled = false;
//this.element.addEventListener("mouseenter",this.mouseEnter);
//this.element.addEventListener("mouseleave", this.mouseLeave);
this.element.onmouseenter = this.mouseEnter.bind(this);
this.element.onmouseleave = this.mouseLeave.bind(this);
this.element.onmousedown = this.mouseDown.bind(this);
this.element.onmouseup = this.mouseUp.bind(this);
console.log("done construct");
/*
color: red;
cursor: pointer;
box-sizing: content-box;
border: 1px solid red;
*/
};
width(){
return interpolate(simpleButtonMinWidth, simpleButtonMaxWidth);
}
height(){
return interpolate(simpleButtonMinHeight, simpleButtonMaxHeight);
};
fontSize(){
return interpolate(sbMinFontSize, sbMaxFontSize);
};
xPos(){
return (this.parent.width() - this.width())/2;
}
yPos(){
var ht0 = this.height();
var tp = Math.floor( (this.parent.height() - 3*ht0 )/4 );
if(tp < 0) tp = 0;
return (tp + this.rowNum*(ht0+tp) );
};
render(){
this.element.style.top = pix( this.yPos() );
this.element.style.left = pix( this.xPos() );
this.element.style.width = pix( this.width() );
this.element.style.height = pix( this.height() );
this.element.style.fontSize = pix( this.fontSize() );
var col = buttonActiveColor;
if(this.disabled) col = buttonDisabledColor;
this.element.style.backgroundColor = col;
};
disable(){
this.disabled=true;
this.element.style.backgroundColor = buttonDisabledColor;
}
enable(){
this.disabled=false;
//this.element.style.backgroundColor = buttonActiveColor;
this.mouseLeave();
};
mouseEnter(){
if(this.disabled) return;
this.element.style.color = "red";
this.element.style.border="1px solid red";
this.element.style.cursor = "pointer";
};
mouseLeave(){
if(this.disabled) return;
this.element.style.backgroundColor = buttonActiveColor;
this.element.style.color = "black"
this.element.style.border=buttonNormalBorder;
this.element.style.cursor = "text";
};
mouseDown(){
if(this.disabled) return;
this.element.style.backgroundColor = buttonClickColor;
};
mouseUp(){
if(this.disabled) return;
this.element.style.backgroundColor = buttonActiveColor;
this.mouseLeave();
}
cleanup(){
};
}; // end class SimpleButton
/* *************************************************
class RADIO BUTTON CONTROLLER
***************************************************** */
class RadioButtonController{
constructor(button0, button1){
this.button0 = button0;
this.button1 = button1;
this.buttons= [this.button0, this.button1];
this.otherButton = [this.button1, this.button0];
};
clicked(buttonNum){
};
render(){
this.button0.render();
this.button1.render();
};
buttonClicked(buttonNum){
var butn = this.buttons[buttonNum];
if(butn.on) return undefined;// button was already on
this.otherButton[buttonNum].turnOff();
return butn.turnOn();
};
}; // end class RadioButtonController
/* *************************************************
class RADIO BUTTON
***************************************************** */
/*
"on" is true or false - is initial state
"id" is the id of the corresponding HTML element.
"num" is 0 or 1
"parentObj" is a Rectangle
"returnVal" is an array which is the value returned from the click
for buttons 0 and 1 respectively
*/
class RadioButton{
constructor(rawIdString, num, offColor, onColor, on, parentObj,returnVal){
this.buttonNumber = num;
this.rawIdString = rawIdString;
this.id = rawIdString + num;
this.element = document.getElementById(this.id);
this.on = on;
this.offColor = offColor;
this.onColor = onColor;
if(on)
this.element.style.backgroundColor = this.onColor;
else
this.element.style.backgroundColor = this.offColor;
this.parent = parentObj;
this.returnVal = returnVal; // keyed by buttonNumber
// horribly unstructured
// but good enuff for here
};
turnOff(){
this.element.style.backgroundColor = this.offColor;
this.on = false;
};
width(){
return interpolate(radioButtonMinWidth, radioButtonMaxWidth);
};
height(){
return interpolate(radioButtonMinHeight, radioButtonMaxHeight);
};
fontSize(){
return interpolate(rbMinFontSize, rbMaxFontSize);
}
xPos(){
return (this.parent.width() - this.width())/2;
};
yPos(){
var ht0 = this.height();
var tp = Math.floor( (this.parent.height() - 2*ht0 )/3 );
if(tp < 0) tp = 0;
return (tp + this.buttonNumber*(ht0+tp) );
};
render(){
this.element.style.width = pix( this.width() );
this.element.style.height = pix( this.height() );
this.element.style.top = pix( this.yPos() );
this.element.style.left = pix( this.xPos() );
this.element.style.fontSize = pix( this.fontSize() );
};
cleanup(){
};
turnOn(){
this.on = true;
this.element.style.backgroundColor = this.onColor;
return this.returnVal[this.buttonNumber];
};
}; // end class Radio Button
/* *************************************************
class SIMPLE TEXT
***************************************************** */
class SimpleText{
constructor(id, parentObj){
this.id = id;
this.element = document.getElementById(id);
this.parentObj = parentObj;
};
fontSize(){
return interpolate(txtMinFontSize, txtMaxFontSize );
};
yPos(){
return ( this.parentObj.height() - this.fontSize())/2;
};
width(){
return this.parentObj.width();
};
render(){
this.element.style.fontSize = pix( this.fontSize() );
this.element.style.top = pix( this.yPos() );
this.element.style.width = pix( this.width() );
this.element.style.lineHeight = .8;
};
}; // end class SimpleText
/* *************************************************
class NUMBER FIELD
***************************************************** */
class NumberField extends SimpleText{
constructor(id, parentObj){
super(id,parentObj);
this.element.textContent = 0;
this.value = 0;
};
render(){
super.render();
//this.element.style.lineHeight = .1;
};
width(){
return this.parentObj.parentObj.width();
};
yPos(){
return .73*this.parentObj.parentObj.height();
};
fontSize(){
return interpolate(rbMinFontSize ,rbMaxFontSize);
};
setValue(num){
this.element.textContent = num;
this.value = num; // could be text
};
getValue(){
return this.value;
};
}; // end class NumberField
/* *************************************************
class GAME BOARD
***************************************************** */
/*
Class GameBoard and the utility classes Rectangle, SimpleButton, etc, all comprise
the VIEW.In general, anything that modifies the "look" of the board goes thruggh
here.
*/
class GameBoard{
constructor(){
this.boxes = []; // array of Rectangle instances - the boxes to click
this.boxesBackup = []; //copy of boxes
this.controlBoxes = []; // array of Rectangle instances - with buttons, etc
this.graphicBoxes = []; // if needed
this.textureBoxes = [];
this.adminButtons = [];
this.faceTypeSelectors=[];
this.audios = []; // Audio instances
this.simpleText; // SimpleText instance
this.moveNumber; //NumberField instance
this.faceType;
this.algorithm;
this.sound;
this.admin;
this.middle;
this.startButton;
this.stopButton;
this.resetButton;
this.colorSelector;
this.graphicSelector;
this.textureSelector;
this.toneButtonController; // RadioButtonController object
this.algorithmController; // ditto
};
resized(){
for(let i=0;i<this.boxes.length;i++)this.boxes[i].render();
for(let i=0;i<this.controlBoxes.length;i++)this.controlBoxes[i].render();
for(let i=0;i<this.adminButtons.length;i++) this.adminButtons[i].render();
for(let i=0;i<this.faceTypeSelectors.length;i++)
this.faceTypeSelectors[i].render();
this.algorithmController.render();
this.toneButtonController.render();
this.simpleText.render();
this.moveNumber.render();
};
setup(){ //(id, type, rowNum, colNum, color)
var col = "hsl(0,0%,72%)";
this.faceType = new Rectangle("faceType","ctrl",0,0,col);
this.algorithm = new Rectangle("algorithm", "ctrl", 0,2,col);
this.sound = new Rectangle("sound", "ctrl", 2,0,col);
this.admin = new Rectangle("admin", "ctrl", 2,2,col);
this.middle = new Rectangle("mdl", "ctrl",1,1,col);
this.controlBoxes =
[this.faceType,this.algorithm,this.sound,this.admin,this.middle];
// constructor(id, rowNum, parent)
this.startButton = new SimpleButton("start", 0,this.admin);
this.stopButton = new SimpleButton("stop", 1, this.admin);;
this.resetButton = new SimpleButton("reset", 2, this.admin);
this.adminButtons = [this.startButton, this.stopButton, this.resetButton];
//FaceTypeSelectors extends Rectangle{
//constructor(id, type, rowNum, graphicImageId, color, parentObj, imagePath)
this.colorSelector = new FaceTypeSelectors("color","ctrl",
0,undefined,"purple", this.faceType, undefined);
var dir = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/946167/";
this.graphicSelector = new FaceTypeSelectors("graphic","ctrl",
1,"graphicImage","white",this.faceType,
dir + "graphicImage1.jpg");
this.textureSelector = new FaceTypeSelectors("texture", "ctrl",2,
"textureImage","white",this.faceType,
dir + "textureImage1.jpg");
//this.colorSelector.log();
//this.graphicSelector.log();
this.faceTypeSelectors=[this.colorSelector, this.graphicSelector,
this.textureSelector];
// constructor(rawIdString, num, offColor, onColor, on, parentObj)
var ret = [NONSTRICT, STRICT];
var rbt0 = new RadioButton("algorithm", 0, rbOffColor,
buttonActiveColor,true, this.algorithm, ret);
var rbt1 = new RadioButton("algorithm", 1, rbOffColor,
buttonActiveColor,false, this.algorithm, ret);
// constructor(button0, button1
this.algorithmController = new RadioButtonController(rbt0, rbt1);
ret = [TONE, CHORD];
rbt0 = new RadioButton("sound", 0, rbOffColor,
buttonActiveColor,true, this.sound, ret);
rbt1 = new RadioButton("sound", 1, rbOffColor,
buttonActiveColor,false, this.sound, ret);
this.toneButtonController = new RadioButtonController(rbt0,rbt1);
this.simpleText = new SimpleText("simon", this.middle);
this.moveNumber = new NumberField("nmbr", this.simpleText);
};
setupColorBoxes(){
this.boxes.push( new Rectangle("b0","box",0,1,"red") );
this.boxes.push( new Rectangle("b1", "box", 1,0,"yellow") );
this.boxes.push( new Rectangle("b2", "box", 2,1,"green") );
this.boxes.push( new Rectangle("b3", "box", 1,2,"blue") );
var audioDir = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/946167/";
var aud = new Audio("tone0", audioDir, "toneC2.mp3", "chord1.mp3");
this.boxes[0].setAudio(aud);
this.audios.push(aud);
aud = new Audio("tone1", audioDir, "toneG2.mp3", "chord2.mp3");
this.boxes[1].setAudio(aud);
this.audios.push(aud);
aud = new Audio("tone2", audioDir, "toneC3.mp3", "chord3.mp3");
this.boxes[2].setAudio(aud);
this.audios.push(aud);
aud = new Audio("tone3", audioDir, "toneG3.mp3","chord4.mp3");
this.boxes[3].setAudio(aud);
this.audios.push(aud);
this.backupBoxes(); // DO ONCE HERE
};
setupGraphicBoxes(){
//constructor(rect, imageId, imagePath)
this.graphicBoxes = [];
var dir = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/946167/";
var gbox = new ImageRectangle(this.boxes[0],"boxImg0",dir+"graphicImage1.jpg");
this.graphicBoxes.push(gbox);
gbox = new ImageRectangle(this.boxes[1],"boxImg1",dir + "graphicImage2.jpg");
this.graphicBoxes.push(gbox);
gbox = new ImageRectangle(this.boxes[2],"boxImg2",dir + "graphicImage3.jpg");
this.graphicBoxes.push(gbox);
gbox = new ImageRectangle(this.boxes[3],"boxImg3",dir +"graphicImage4.jpg");
this.graphicBoxes.push(gbox);
};
setupTextureBoxes(){
this.textureBoxes = [];
var dir = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/946167/";
var gbox = new ImageRectangle(this.boxes[0],"boxImg0",dir +"textureImage1.jpg");
this.textureBoxes.push(gbox);
gbox = new ImageRectangle(this.boxes[1],"boxImg1",dir +"textureImage2.jpg");
this.textureBoxes.push(gbox);
gbox = new ImageRectangle(this.boxes[2],"boxImg2",dir +"textureImage3.jpg");
this.textureBoxes.push(gbox);
gbox = new ImageRectangle(this.boxes[3],"boxImg3",dir +"textureImage4.jpg");
this.textureBoxes.push(gbox);
};
backupBoxes(){
this.backupBoxes=[];
for(let i=0;i<this.boxes.length;i++)
this.backupBoxes.push(this.boxes[i]);
};
setIndicatorForMemorization( boxNum){
this.boxes[boxNum].setIndicatorForMemorization()
};
undoIndicatorForMemorization(boxNum){
this.boxes[boxNum].undoIndicatorForMemorization();
};
setIndicatorForUserClick(boxNum){
this.boxes[boxNum].setIndicatorForUserClick();
};
undoIndicatorForUserClick(boxNum){
this.boxes[boxNum].undoIndicatorForUserClick();
};
showMemoryError(what){
var what=this;
setTimeout( function(){
for(let i=0;i<=3;i++)what.boxes[i].setIndicatorForError(i);
setTimeout(function(){
for(let i=0;i<=3;i++)what.boxes[i].undoIndicatorForError(i);
},
500);
},
100);
};
doGameOver(){
this.moveNumberValue("GAME OVER");
//console.log("game over");
};
displayImageGraphics(){
this.boxes=[];
for(let i=0;i<4;i++){
this.boxes.push(this.graphicBoxes[i]);
this.graphicBoxes[i].showImage();
}
this.resized();
};
displayColors(){
for(let i=0;i<4;i++)this.boxes[i].cleanup();
this.boxes=[];
for(let i=0;i<4;i++){
this.boxes.push(this.backupBoxes[i]);
}
this.resized();
};
displayTextureGraphics(){
this.boxes=[];
for(let i=0;i<4;i++){
this.boxes.push(this.textureBoxes[i]);
this.textureBoxes[i].showImage();
}
this.resized();
};
// return the alorithm selected, or undefined if it is already selected
algorithmButtonClick(n){
return this.algorithmController.buttonClicked(n);
};
soundButtonClick(n){
var num = this.toneButtonController.buttonClicked(n);
// num is TONE, CHORD, which are 0,1;
for(let i=0;i<this.audios.length;i++){
this.audios[i].setPlaying(num);
}
};
moveNumberValue(num){
this.moveNumber.setValue(num);
};
getMoveNumberValue(){
return this.moveNumber.getValue();
};
resetColors(){
};
disableStartButton(){this.startButton.disable();};
enableStartButton() {this.startButton.enable();}
disablePauseButton(){this.stopButton.disable();}
enablePauseButton(){this.stopButton.enable();}
disableResetButton(){this.resetButton.disable();}
enableResetButton(){this.resetButton.enable();}
doSimpleButtons(start, pause, reset){
start? this.enableStartButton():this.disableStartButton();
pause? this.enablePauseButton():this.disablePauseButton();
reset? this.enableResetButton():this.disableResetButton();
};
isStartButtonDisabled(){return this.startButton.disabled;};
isPauseButtonDisabled(){return this.stopButton.disabled;};
isResetButtonDisabled(){return this.resetButton.disabled;};
log(){
for(let i=0;i<this.boxes.length;i++) this.boxes[i].log();
for(let i=0;i<this.controlBoxes.length;i++) this.controlBoxes[i].log();
};
}; // end class GameBoard
/* *************************************************
class BOX PATTERN
***************************************************** */
/* class BoxPattern holds the pattern of clicks to be remembered
memorizeMoveNum is the number of moves by the player on the current
turn.
*/
class BoxPattern{
constructor(){
this.arr = [];
for(let i=0;i<maxNumStore;i++)
this.arr.push(getRandomInt(0,4));
this.memorizeMoveNum = 1;
};
getBox(indx){
if( (indx < 0)||(indx >= maxNumStore))return undefined;
return this.arr[indx];
};
getMoveNum(){return this.memorizeMoveNum;};
incrMoveNum(){this.memorizeMoveNum++;};
// allows to use same pattern, from beginning- for strict mode
startAgain(){this.memorizeMoveNum = 1;}
}; // end BoxPattern
/* *************************************************
class CONTROLLER
***************************************************** */
/*
The control of the game itself is in four functions:
schedule(), runGame(), runGame1(), continueGame().
DO NOT MESS WITH THESE UNLESS YOU REALLY KNOW WHAT YOU ARE
DOING AS THE TIMING CAN GET REALLY GET FOO-BAR'D.
*/
class Controller{
constructor(){
this.pattern = new BoxPattern(); // sequence of moves to be remembered
this.allowBoxClick = false; // flag to disable clicks on boxes
this.playerMoveNum = undefined;// when player is remembering, this keeps
// track of the number of clicks
// not same as pattern.memorizeMovNum
this.isStrict = false; // strict MODE (not a state)
this.state = "begin"; /* states are:
begin, playing, paused, resetting.
States managed in method schedule(). */
this.noActions = false; // If true, NO button works.
};
schedule(action){
// game loaded
// in call board.doSimpleButtons(s,p,r), s is for start, p is for pause, r is for
// reset. If true, corresponding button is enabled. If false, corresponding
// button is disabled.
const what = this;
if( (action == "start") && (this.board.isStartButtonDisabled()) ) return;
if( (action =="pause") && (this.board.isPauseButtonDisabled()) )return;
if( (action == "reset") && (this.board.isResetButtonDisabled()) ) return;
// BEGIN
if( (this.state == "begin") && (action == "go") ){
this.setup();
this.board.resized();
this.board.doSimpleButtons(true,false,false);
this.board.moveNumberValue("'start' to begin");
return;
}
// start button clicked
if( (this.state == "begin") && (action == "start")){
this.board.doSimpleButtons(false, true, true);
this.resetGame();
this.pattern = new BoxPattern();
this.state = "playing";
this.runGame();
return;
}
if(this.state == "begin") return;
// PLAYING
if( (this.state == "playing") && (action == "error") ){
var val = this.board.getMoveNumberValue();
this.board.moveNumberValue("try again");
this.board.showMemoryError(this); // 600 ms delay
this.board.doSimpleButtons(false,false,false);
setTimeout(function(){
if(this.state=="resetting") return;
what.allowBoxClick = false;
what.playerMoveNum = undefined;
if(what.isStrict) {
what.pattern.startAgain();
what.board.moveNumberValue(1);
}else{
what.board.moveNumberValue(val);
}
// state is still "playing"
what.board.doSimpleButtons(false,true,true);
what.runGame1(0, what);
},
1500);
return;
}
if( (this.state == "playing") && (action == "reset") ){
this.state="resetting";
what.board.moveNumberValue("****RESETTING****");
this.board.doSimpleButtons(false,false,false);
this.noActions = true;
setTimeout(function(){
what.resetGame();
what.pattern = new BoxPattern();
what.state = "begin";
what.board.resized();
what.board.doSimpleButtons(true,false,false);
what.noActions = false;
what.board.moveNumberValue("'start' to begin");
return;
},
2000);
return;
}
if( (this.state=="playing") && (action == "pause") ){
this.state = "paused";
this.board.doSimpleButtons(true, false, true);
this.allowBoxClick=false;
return;
}
if( (this.state == "playing") && (action == "gameOver") ){
console.log("sched game over");
this.board.doSimpleButtons(false,false,false);
this.board.doGameOver();
this.noActions = true;
setTimeout(function(){
what.board.doSimpleButtons(true,false,false);
what.board.moveNumberValue("'start' to begin");
what.noActions = false;
what.board.doSimpleButtons(true,false,false);
},
1500);
this.state="begin";
this.allowBoxClick = false;
this.playerMoveNum = undefined;
this.board.resized();
this.pattern = new BoxPattern();
return;
}
if(this.state == "playing") return;
//PAUSED
if( (this.state == "paused" )&& (action == "start") ){
this.board.doSimpleButtons(false, true,true);
this.board.resized();
this.state = "playing";
this.allowBoxClick = false;
this.playerMoveNum = undefined;
return this.runGame1(0, this);
}
if( (this.state=="paused") && (action == "reset") ){
this.board.doSimpleButtons(false,false,false);
what.board.moveNumberValue("****RESETTING****");
this.noActions = true;
this.board.resized();
this.state = "begin";
this.resetGame();
this.pattern = new BoxPattern();
setTimeout(function(){
what.board.doSimpleButtons(true,false,false);
what.noActions = false;
what.board.moveNumberValue("'start' to begin");
},
1000);
return;
}
if(this.state == "paused" ) return;
// RESETTING
if(this.state == "resetting") return;
}; // end schedule()
resetGame(){
this.allowBoxClick = false;
this.playerMoveNum = undefined;
this.board.moveNumberValue(1);
this.board.resetColors();
};
// this is called only when "start" button is pushed.
runGame(){
const what = this;
// after this next function, wait for click from player
setTimeout(function(){
what.runGame1(0, what);
},
500);
};
/* This generates the sequence to be remembered. The quantity "i+1" is
length of the pattern generated. This is called with i=0,1,2,....
The variable "what" is this controller - used because "this" does not
work correctly in nested methods.
*/
runGame1(i, what){
if(what.state == "paused") return;
if(what.state=="resetting") return;
var boxNum = what.pattern.getBox(i);
what.board.setIndicatorForMemorization( boxNum);
setTimeout(function(){
what.board.undoIndicatorForMemorization(boxNum);
if(this.state=="resetting") return;
i++;// this is 1 for 1st move, 2 for 2nd, etc
if(i < what.pattern.getMoveNum() ){
setTimeout(function(){what.runGame1(i, what);},
700);
}else{
// now the player must repeat the pattern
what.playerMoveNum = 0;
what.allowBoxClick = true;
}
}, 500);
};
/*user is repeating the sequence - he clicks on box n.
*/
continueGame(n){
if(this.state == "paused") return;
if(this.state=="resetting") return;
this.allowBoxClick = false; // disable clicks until this method and timeout
// are finished
const what = this;
if(n != this.pattern.getBox(this.playerMoveNum)) {
return this.schedule("error");
}
if(this.state == "paused") return;
this.board.setIndicatorForUserClick(n);
setTimeout(function(){
if(what.state=="resetting")return;
what.board.undoIndicatorForUserClick(n);
what.playerMoveNum++;
what.allowBoxClick = true;
if(what.playerMoveNum >= what.pattern.getMoveNum() ){
setTimeout(function(){
if(what.state=="resetting")return;
what.allowBoxClick = false;
what.playerMoveNum = undefined;
what.pattern.incrMoveNum();
what.board.moveNumberValue( what.pattern.getMoveNum() );
if(what.pattern.getMoveNum() > maxNumStore){
if(what.state=="resetting")return;
return what.schedule("gameOver");
}
what.runGame1(0, what);
},
800);
}// if
},
600);
};
setup(){
this.board = new GameBoard();
this.board.setup();
this.board.setupColorBoxes();
this.board.setupGraphicBoxes();
this.board.setupTextureBoxes();
this.state = "begin";
this.schedule();
};
displayImageGraphics(){
this.board.displayImageGraphics();
//this.schedule("reset");
};
displayColors(){
this.board.displayColors();
//this.schedule("reset");
};
displayTextureGraphics(){
this.board.displayTextureGraphics();
//this.schedule("reset");
};
algorithmButtonClick(n){
var algChosen = this.board.algorithmButtonClick(n);
if(algChosen === undefined) return;
this.changeAlgorithmTo(algChosen);
};
changeAlgorithmTo(algChosen){
console.log("algorithm");
if(algChosen === NONSTRICT){
this.isStrict = false;
}else{
this.isStrict = true;
}
this.schedule("reset");
};
soundButtonClick(n){
this.board.soundButtonClick(n);
};
resized(){
this.board.resized();
};
};
/* *************************************************
CALLBACKS
***************************************************** */
const control = new Controller();
// this is called by window on resizing
function resized(){
control.resized();
}
function go(){
control.schedule("go");
}
function adminStart(){
control.schedule("start");
}
function adminPause(){
control.schedule("pause");
}
function adminReset(){
control.schedule("reset")
}
function boxClick(n){
if(control.noActions) return;
if(! control.allowBoxClick) return;
control.continueGame(Number(n));
}
function imageColor(){
if(control.noActions) return;
control.displayColors();
}
function imageGraphic(){
if(control.noActions) return;
control.displayImageGraphics();
}
function imageTexture(){
if(control.noActions) return;
control.displayTextureGraphics();
}
function algorithmButtonClick(n){
if(control.noActions) return;
control.algorithmButtonClick(Number(n));
}
function soundButtonClick(n){
if(control.noActions) return;
control.soundButtonClick(Number(n));
};
function mouseEnter(){
console.log("mouse enter function");
}
Also see: Tab Triggers