javascript - How to make a Simon Js game based on arrays? -
im writing js simple simon game , im clueless on how it.
i know :
i need create 2 arrays, , level(score) variable
- a randomly generated number 1 4 (inclusive) needs added first array, when 1 of 4 buttons pressed, value of added second array, if second array not the
same size or bigger first array. each time value added second array, check value equal value in
same position in first array, if not, clear both arrays, , set levelvar 1, , alert "gameover" means if one
wrong, cannot continue. if length of second array
matches level variable, add random number array one, clear
array two, increment levelvar.
but, clueless in aspect code.
my jsfiddle :http://jsfiddle.net/jbwcg/2/
js:
var x = [] var y = [] var levelvar = 1 document.getelementbyid("test").onclick= function() { document.getelementbyid("test").innerhtml=x }; document.getelementbyid("button1").onclick= function() { x.push("red") }; document.getelementbyid("button2").onclick= function() { x.push("green") }; document.getelementbyid("button3").onclick= function() { x.push("yellow") }; document.getelementbyid("button4").onclick= function() { x.push("blue") };
html:
<button id="button1">red</button><br /> <button id="button2">green</button><br /> <button id="button3">yellow</button><br /> <button id="button4">blue</button><br /> <p id="test">click see have clicked</p>
how make 2 arrays see if value same?
lets say, generated array : [1,2,3,4,1,2,3] , @ position 5 , press 2, how check 2 numbers match? in advance
the easiest way check 1 @ time position i
of array x
is
if (gen_arr[i] == x) { // matches } else { // doesn't match }
so if conceptualize flow of game, you're going want to, @ each button press:
- somehow keep track of index on (maybe have counter increments each button press)
- checks if
gen_arr[i] == x
(and displays game on if doesn't).
alternatively, instead of keeping track of index, can call gen_array.shift()
first item in gen_array
, delete array, in flow kind of this:
var gen_array = [1,2,3,4,1]; function press_button(button_pressed) { var supposed_to_be = gen_array.shift(); // @ point, on first call, // supposed_to_be = 1, , gen_array = [2,3,4,1] if (supposed_to_be != button_pressed) { // game over! } else { // survive now! if (gen_array.length() == 0) { // gen_array empty, made through entire array // game won! } } }
while represents general "what check" @ every step, using verbatim not recommended leads unstructured game.
i recommend looking things called "game state" diagrams, flow charts have every "state" of game -- in case, includes @ least
- "displaying" pattern
- waiting button press
- checking if button press correct
- game over
- game won
and each state, draw arrows on "how" transition 1 state next. can google search see examples.
once have game state diagram/flow chart, it's easier break down program specific chunks , organize better ... , can see need code , missing/what not missing.
Comments
Post a Comment