How could I restart this current function - javascript

During the use of this function you click a button that will give you a square that will display a colour within a square. However when you click the button 60 times the programme stops working because all the colours have been used. How would I then restart this process so that I can continue clicking ?
<html>
<head>
<script>
var usedColors = [];
function randomColour(){
var colour=[];
colour[0]= '#edf2fb';
colour[1]= '#d7e3fc';
colour[3]= '#c1d3fe';
colour[4]= '#d1d1d1';
colour[5]= '#e1dbd6';
colour[6]= '#e2e2e2';
colour[7]= '#f9f6f2';
colour[8]='#ffc09f';
colour[9]='#ffee93';
colour[10]='#fcf5c7';
colour[11]='#a0ced9';
colour[12]='#adf7b6';
colour[13]='#809bce';
colour[14]='#95b8d1';
colour[15]='#b8e0d2';
colour[16]='#d6eadf';
colour[17]='#eac4d5';
colour[18]='#e8d1c5';
colour[19]='#eddcd2';
colour[20]='#fff1e6';
colour[21]='#f0efeb';
colour[22]='#eeddd3';
colour[23]='#e8dff5';
colour[24]='#fce1e4';
colour[25]='#fcf4dd';
colour[26]='#ddedea';
colour[27]='#daeaf6';
colour[28]='#d3ab9e';
colour[29]='#eac9c1';
colour[30]='#ebd8d0';
colour[31]='#ffe5ec';
colour[32]='#ffc2d1';
colour[33]='#ceb5b7';
colour[35]='#b5d6d6';
colour[36]='#f2f5ff';
colour[37]='#efcfe3';
colour[38]='#eaf2d7';
colour[39]='#b3dee2';
colour[40]='#f8ad9d';
colour[41]='#fbc4ab';
colour[42]='#ffdab9';
colour[43]='#cdb4db';
colour[44]='#ffc8dd';
colour[45]='#ffafcc';
colour[46]='#bde0fe';
colour[47]='#a2d2ff';
colour[48]='#fdffb6';
colour[49]='#caffbf';
colour[50]='#9bf6ff';
colour[51]='#a0c4ff';
colour[52]='#ffc6ff';
colour[53]='#a7bed3';
colour[54]='#c6e2e9';
colour[55]='#f1ffc4';
colour[56]='#ffcaaf';
colour[57]='#dab894';
colour[58]='#fec7bc';
colour[59]='#fcf5ee';
var pick= Math.floor(Math.random()*60);
if(usedColors.includes(pick)){
randomColour();
}
usedColors.push(pick); document.getElementById("colorpad").style.backgroundColor = colour[pick];
console.log(usedColors);
}
</script>
</head>
<body>
<div id="colorpad" style="height: 300px; width: 300px;">
<button onclick="randomColour()">btn</button>
</div>
</body>
</html>

Keep track of the current color:
let curr = 0;
On "Next" button click increment the curr index, and loopback with the help of the Modulo Operator %:
curr += 1;
curr %= colour.length; // On "next" loop back to 0 if we reached the end
Finally there's your color back at 0
console.log(colour[curr]); // '#edf2fb'
Demonstration:
const EL = (sel, EL) => (EL||document).querySelector(sel);
const colors = [
'#edf2fb',
'#d7e3fc',
'#c1d3fe',
'#d1d1d1',
'#e1dbd6',
'#e2e2e2',
'#f9f6f2',
'#ffc09f',
'#ffee93',
'#fcf5c7',
];
const tot = colors.length;
let curr = 0;
const curr_rand = () => curr = Math.floor(Math.random() * tot);
const curr_next = () => (curr += 1, curr %= tot);
const applyColor = () => EL("body").style.background = colors[curr];
EL("#rand").addEventListener("click", () => {
curr_rand();
applyColor();
console.log(curr);
});
EL("#next").addEventListener("click", () => {
curr_next();
applyColor();
console.log(curr);
});
<button type="button" id="rand">Generate</button>
<button type="button" id="next">Next</button>

Here's a snippet using a small factory function to be able to recolor infinitely. The recoloring is done using a randomly shuffled copy of the color array. This way you don't have to check each time if a color is already used.
Furthermore, see comments in the snippet. It uses event delegation for the handler, because it's generally not a good idea to use inline event handlers.
To keep the snippet lean, only 10 colors are used.
const colorize = randomColor(
['#edf2fb', '#d7e3fc', '#c1d3fe', '#d1d1d1', '#e1dbd6',
'#e2e2e2', '#f9f6f2', '#ffc09f', '#ffee93', '#fcf5c7'] );
document.addEventListener(`click`, evt => {
if (evt.target.id === `colorChange`) {
return colorize(document.querySelector(`.color`));
}
});
// randomColor is a factory function, it returns a function.
// The function can use the inner variables as well as the
// [colors] array from the parameter(they are 'closed over').
// The [colors] array is shuffled randomly (Fisher-Yates) and
// on every call (from click) the first color from that shuffled
// array is picked - until it's empty. If [shuffled] is empty
// the original [color] array is reshuffled (into [shuffled]).
// This way the coloring is restarted with a new set of
// random colors.
function randomColor(colors){
const shuffle = array =>
[...Array(array.length)]
.map((el, i) => Math.floor(Math.random() * i))
.reduce( (a, rv, i) =>
([a[i], a[rv]] = [a[rv], a[i]]) && a, array.slice());
// ^ slice copies the original
let shuffled = shuffle(colors);
// return a function
return colorDiv => {
const restarted = !shuffled.length;
shuffled = shuffled.length > 0 ? shuffled : shuffle(colors);
const nwColor = shuffled.shift();
colorDiv.style.backgroundColor = nwColor;
// for demo: color is displayed, and bold/red if [shuffled] is renewed
colorDiv.classList[restarted ? `add` : `remove`](`restart`);
colorDiv.dataset.color = nwColor;
}
}
.color {
width: 100px;
height: 100px;
border: 1px solid #777;
margin: 1rem 0;
text-align: center;
line-height: 100px;
}
.color:before {
content: attr(data-color);
}
.color.restart:before {
color: red;
font-weight: bold;
}
<div class="color"></div>
<button id="colorChange">change</button>

Related

Cannot implement shuffle bars feature in sorting algorithm visualizer - setTimeout updates are not rendering

I'm making a sorting algorithm visualizer project and I'm in the process of implementing a shuffle button. The visualization involves bars of different heights getting moved around. I would like the shuffle button to modify the bar array one step at a time, showcasing each swap at a high speed. I've tried tweaking many different things (some of which do move bars around in a strange manner), but I can't seem to get the desired functionality to work. Here's some of the relevant code:
// Swap does not modify the original array, but the implementation details don't really affect the result.
// It basically swaps two elements in the bar array, and then returns the updated array.
const swapBars = (bars, bar1, bar2) => {
if (!bars || !bar1 || !bar2) {
return;
}
const _bars = bars;
let _bar1 = bar1;
let _bar2 = bar2;
const tempLeft = _bar1.left;
_bar1.left = _bar2.left;
_bar2.left = tempLeft;
const temp = _bar1;
_bar1 = _bar2;
_bar2 = temp;
return _bars;
};
// Init bars is basically synchronous shuffle. It takes the array that is created and shuffles it
// because the array should begin in a shuffled state. This is working properly.
const initBars = (bars) => {
let currentIndex = bars.length - 1;
while (currentIndex > 0) {
// randomIndex will always be different from currentIndex, so each bar will always shuffle
const randomIndex = Math.floor(Math.random() * currentIndex);
swapBars(bars, bars[currentIndex], bars[randomIndex]);
currentIndex--;
}
setBarsToRender(bars);
};
// createBarArray is what is used to actually populate an empty array with bars depending on a number passed
// through by a slider. This is also working properly.
const createBarArray = (quantity) => {
let bars = [];
const width = calcWidthPercentage(quantity);
for (let i = 0; i < quantity; i++) {
const height = calcHeightPercentage(quantity, i + 1);
const left = calcLeftPosPercentage(quantity, i + 1);
bars.push({ correctPos: i, height: height, width: width, left: left });
}
return initBars(bars);
};
// shuffleBars seems to be broken. I've tried many different things, and this is just the latest snapshot of it.
// It is being called when the shuffle button is being clicked using `shuffleBars(barsToRender)` where barsToRender is the stateful value that is being rendered.
const shuffleBars = (bars) => {
let currentIndex = bars.length - 1;
while (currentIndex > 0) {
const randomIndex = Math.floor(Math.random() * currentIndex);
setTimeout(() => {
setBarsToRender((prev) => {
return swapBars(prev, prev[currentIndex], prev[randomIndex]);
});
}, 50 * (bars.length - currentIndex));
currentIndex--;
}
};
If I do something like moving the swapBars call inside setBarsToRender outside of it and then
do setBarsToRender[...bars], I can see some of the bars moving, but not with the intended behavior (the smallest bar is the only one that keeps swapping). I'm not sure if I'm misunderstanding how state updates work inside setTimeout, or if it's something else, so I'd greatly appreciate some help.
I removed the setTimeout and used a transition delay to create the staggered effect.
Working demo below:
const swapBars = (bars, bar1, bar2) => {
if (!bars || !bar1 || !bar2) {
return;
}
const _bars = bars;
let _bar1 = bar1;
let _bar2 = bar2;
const tempLeft = _bar1.left;
_bar1.left = _bar2.left;
_bar2.left = tempLeft;
const temp = _bar1;
_bar1 = _bar2;
_bar2 = temp;
return _bars;
};
const initBars = (bars) => {
let currentIndex = bars.length - 1;
while (currentIndex > 0) {
const randomIndex = Math.floor(Math.random() * currentIndex);
swapBars(bars, bars[currentIndex], bars[randomIndex]);
currentIndex--;
}
return bars;
};
const createBarArray = (quantity) => {
let bars = [];
const width = 100 / quantity;
for (let i = 0; i < quantity; i++) {
const height = width * (i + 1);
const left = width * i;
bars.push({ correctPos: i, height: height, width: width, left: left });
}
return initBars(bars);
};
function Bars({ quantity = 10 }) {
const [barsToRender, setBarsToRender] = React.useState([]);
React.useEffect(() => {
const bars = createBarArray(quantity);
setBarsToRender(bars);
}, [quantity]);
const shuffleBars = () => {
const bars = [...barsToRender];
setBarsToRender(initBars(bars));
};
return (
<div>
<ul
style={{
height: "50vh",
display: "flex",
position: "relative"
}}
>
{barsToRender.map((bar, i) => (
<Bar key={bar.correctPos} bar={bar} index={i} />
))}
</ul>
<button onClick={shuffleBars}>Shuffle</button>
</div>
);
}
function Bar({ bar, index: i }) {
return (
<li
style={{
background: "blue",
height: `${bar.height}%`,
width: `${bar.width}%`,
left: `${bar.left}%`,
position: "absolute",
bottom: 0,
transitionProperty: "left",
transitionTimingFunction: "ease-in-out",
transitionDuration: ".25s",
transitionDelay: `${i*50}ms`
}}
>
<p>{bar.correctPos}</p>
</li>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<Bars />)
p {
font-family: sans-serif;
font-weight: 700;
height: 1.5rem;
width: 1.5rem;
display: grid;
place-content: center;
background: white;
border-radius: 50%;
border: 1px solid;
}
ul {
padding: 0;
list-style-type: none;
}
li {
display: grid;
align-content: end;
justify-items: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
<div id="root"></div>

How to style a singular v-for item in vue, based on a condition?

I am making a multiple choice quiz game and want what the user clicked to change to either red or green depending on if that answer is correct or incorrect. I made a variable called selected which is what the user pressed- this does correctly update. I have also got all of the v-for items to change to the same colour depending on if the answer is correct or not, I only need help separating it so that only one of the v-for things change colour.
Here is my relative HTML:
<button type="button" class="btn" class="answer" v-for="option in options" #click="checkAnswer(option)" #click="selected = option" :style="{backgroundColor: colour}">
{{option}}<br/>
</button>
<button type="button" #click="getQ" #click="shuffle(options)" class="btn button next">Next</button>
Here is the relative JS:
let colour = Vue.ref('');
let selected = Vue.ref('');
let options = Vue.ref([correctAnswer, incorrectAnswerOne, incorrectAnswerTwo, incorrectAnswerThree]);
// Methods
let shuffle = function(options) {
let num = options.length, t, raInt;
//while there are remaining elements to shuffle
while (num) {
//choose random
raInt = Math.floor(Math.random() * num--);
//swap with current element
t = options[num];
options[num] = options[raInt];
options[raInt] = t;
}
return options;
};
let checkAnswer = function(clicked) {
console.log(clicked.value);
console.log(correctAnswer.value);
if (clicked.value == correctAnswer.value) { // checks if the button that was clicked is the same as the answers value
this.result = "Correct!"; //if it does, result changes to Correct!
this.colour = "green";
} else {
this.result = "Incorrect!"; //if the answer is incorrect, result changes to Incorrect!
this.colour = "red";
};
};
And here is some CSS:
.answer {
width: 100%;
background-color: #dbdbdb;
padding: 4% 2%;
margin: 1 0;
}
.answer:hover {
background-color: #c2c2c2
}
I haven’t really tried that much. I’m not sure what to try. In a different project I did style a different div based on what other div was selected, but I am not sure how to change just one part of a v-for, or if it is even possible.
Thanks in advance
You can set condition for showing color style:
const { ref, computed } = Vue
const app = Vue.createApp({
setup() {
let correctAnswer = 3
let incorrectAnswerOne = 1
let incorrectAnswerTwo = 2
let incorrectAnswerThree = 4
let colour = ref('');
let selected = ref('');
let options = ref([correctAnswer, incorrectAnswerOne, incorrectAnswerTwo, incorrectAnswerThree]);
let shuffled = ref([])
let shuffle = (array) => {
selected.value = null
let currentIndex = array.length, randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
shuffled.value = array;
};
shuffle(options.value)
let checkAnswer = function(clicked) {
// 👇 set selected
selected.value = clicked
if (clicked == correctAnswer) {
this.result = "Correct!";
this.colour = "green";
} else {
this.result = "Incorrect!";
this.colour = "red";
};
};
return { colour, selected, options, shuffle, checkAnswer, shuffled }
},
})
app.mount('#demo')
.answer {
width: 100%;
background-color: #dbdbdb;
padding: .5em 2em;
margin: 1 0;
}
.answer:hover {
background-color: #c2c2c2
}
.btns {
display: flex;
}
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<div id="demo">
<div class="btns">
<div v-for="(option, i) in shuffled" :key="i" >
<!-- 👇 condition -->
<button class="answer" #click="checkAnswer(option)" :style="selected == option && {backgroundColor: colour}">
{{option}}<br/>
</button>
</div>
</div>
<button type="button" #click="getQ, shuffle(options)" class="btn button next">Next</button>
</div>

Player interaction in a while javascript

i've encountered a few errors while working on a round by round script for a game on browser, sorry for my spelling mistakes.
I have a function with a while separated in three parts as the following (full javascript):
function turn(player, monster){
//player and monster are object
turns=2;
//few other unimportant variable
while(//as long as they have >0 hp){
if(turns==2){
//listen to click on html to know if player used a spell
// if he didn't in a few seconds, then he'll just use a normal
// attack
startingTurn = settimeout(startTurn, 2000);
sleep(2000);
turns=1;
}
if(turns==1 ){
//Turn of the player (working perfectly)
...
turns=0;
}
if(turns==0 and hp>0){
//Turn of the monster (working perfectly)
...
turns=2;
}
}
}
The problem that i've encountered is that in the listening of an action, i have to set a pause so that the player will have time to click on one of the spell.
To do this, i've tryed using "sleep" function to let 2 seconds for the player to act and a settimeout() to set a normal attack if there were no spell clicked.
The sleep function that i used looked like this one: https://www.sitepoint.com/delay-sleep-pause-wait/
Both those methods gave me errors:
-The settimeout() were effective only after the whole script(while) was finished (all at once).
-The "sleep" function caused the whole page to freeze, not only the while but also the html wasn't clickable.
So I'm looking for a way of leting the player interact while the function is running, if this isn't possible i will probably have to give up the interaction part.
I've looked online for quite a long time and didn't found any solution so i hope you can help me there!.
EDIT
I have tried to use the methods from Jacob (with async function and a loop() )because it was what looks the most clear for me.
But then i found the same first problem wich is that the settimeout() are executed after the loop() function here's where i think the problem is:
function attaqueBasic (attacker, defender) {
console.log("basic attack");
return new Promise((res, rej) => {
setTimeout(() => {
var dodge = dodge(defender);
if(dodge == false){
console.log("attack damage :"+attacker.dmg);
defender.life = defender.life - attacker.dmg;
console.log("life defender: "+defender.vie);
if(attacker.hasOwnProperty("bonus")==true && defender.life>0){
attackBonus(attacker, defender);
}
}
res()
}, 2000);
})
}
This is the function that let the player do a basic attack but it doesn't wait for the resolve to continue.
In the console i find the "basic attack" while the loop is running but never the following wich is in the settimeout and is executed only after all loops are done. Sorry if i made a big mistake here.
Here's the function loop() just in case i made some mistake:
function loop(perso, monstre){
nbtour += 1
if(nbtour>=6){
nbtour=0;
return;
}
console.log('---New tour'+nbtour+'---');
Turn(perso,monstre)
.then(checkWin(perso,monstre))
.then(Turn(monstre,perso))
.then(checkWin(perso,monstre))
.then(loop(perso, monstre))
.catch(() => {
console.log('End of combat, number of tours ='+nbtour);
nbtour=0;
})
}
Thanks for your time.
I assume this is on a browser or similar platform.
You can't have reasonably have meaningful input from the user within a while loop (I'm intentionally ignoring the unreasonable prompt function). Instead, handle an event that occurs when a player moves, and have that event handler process the changes the event causes. At the end of the handler's logic, check what used to be the loop termination condition ("as long as they have >0 hp") and if the termination condition has been reached, modify the page to say that the game is over or whatever (and probably disable the buttons).
For instance, here's a simple example using number guessing:
var number = Math.floor(Math.random() * 10) + 1;
var guesses = 3;
var btn = document.getElementById("guess");
var input = document.getElementById("guess-value");
btn.addEventListener("click", function() {
var value = input.value.trim();
if (!value) {
guessError("Please fill in a value");
return;
}
var guess = +value;
if (isNaN(guess)) {
guessError("Please only fill in simple numbers");
return;
}
if (guess < 1 || guess > 10) {
guessError("What part of 'between 1 and 10, inclusive' did you not understand? ;-)");
return;
}
if (guess === number) {
console.log("Congrats! You won!");
input.disabled = btn.disabled = true;
} else {
console.log("Nope, it's not " + guess);
if (--guesses === 0) {
console.log("You're out of guesses, the computer wins.");
input.disabled = btn.disabled = true;
} else {
input.value = "";
input.focus();
}
}
});
console.log("Guess a whole number between 1 and 10 inclusive");
input.focus();
function guessError(msg) {
console.log(msg);
input.focus();
}
<input type="text" id="guess-value">
<input type="button" id="guess" value="Guess">
That's very quick-and-dirty, but the key thing is that instead of a while loop with the number of times the user is allowed to guess, we just respond to them guessing and count the number of times they guess, and change the state of the page when they run out (or win).
First, we can not use while for game loop, because it will freeze browser, user would can not interact with game.
We will use recursion , something like this:
function loop () {
loop()
}
Second, we have to use async to stop loop to wait user operation, otherwise the recursion would have no difference with iteration, something like this:
setTimemout(attack, 2000)
Third, we have to chain all of the code in loop to make it run one by one, because they are async, otherwise the order cann't be guaranteed, like this:
firstAttack()
.then(secondAttack)
.then(thirdAttack)
.catch(gameOver())
Here is a simple demo.
const php = document.querySelector('.p-hp')
const mhp = document.querySelector('.m-hp')
const output = document.querySelector('.output')
const fireballEl = document.querySelector('.fireballEl')
let isAbility = false
let hp = ''
fireballEl.addEventListener('click' , e => {
isAbility = true
fireballEl.disabled = true
e.preventDefault()
})
function playerTurn () {
if (isAbility) {
isAbility = false
return fireball()
}
return slash()
}
function slash () {
return new Promise((res, rej) => {
setTimeout(() => {
const dmg = getRandomInt(1, 200)
hp.m -= dmg
if (hp.m < 0) {
hp.m = 0
}
mhp.textContent = hp.m
output.innerHTML += `<li class="player-info">You slashed monster which damaged ${dmg} hp</li>`
res()
}, 2000);
})
}
function fireball () {
return new Promise((res, rej) => {
setTimeout(() => {
const dmg = getRandomInt(260, 400)
hp.m -= dmg
if (hp.m < 0) {
hp.m = 0
}
mhp.textContent = hp.m
fireballEl.disabled = false
output.innerHTML += `<li class="player-info ability">You thrown a fireball to monster which damaged ${dmg} hp</li>`
res()
}, 2000);
})
}
function bite () {
return new Promise((res, rej) => {
setTimeout(() => {
const dmg = getRandomInt(6, 20)
hp.p -= dmg
if (hp.p < 0) {
hp.p = 0
}
php.textContent = hp.p
output.innerHTML += `<li class="monster-info">Monster bite you for ${dmg} hp</li>`
res()
}, 2000);
})
}
function check () {
if (hp.p <= 0) {
output.innerHTML += '<li class="lose">System terminated, rebuild enviroment, monster is ready,experiment can be continued... </li>'
return Promise.reject(1)
}
if (hp.m <= 0) {
output.innerHTML += '<li class="win">Hooray! Now the princess is yours.</li>'
return Promise.reject(0)
}
return Promise.resolve(1)
}
function init () {
output.innerHTML = ''
php.textContent = 100
mhp.textContent = 1000
return {
p: 100,
m: 1000
}
}
function updateDom () {
php.textContent = hp.p
mhp.textContent = hp.m
}
function loop () {
output.innerHTML += '<li class="bar">=====================</li>'
playerTurn()
.then(updateDom)
.then(check)
.then(bite)
.then(updateDom)
.then(check)
.then(loop)
.catch(() => {
startEl.disabled = false
fireballEl.disabled = true
})
}
function getRandomInt(min, max) {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min)) + min
}
const startEl = document.querySelector('.start')
startEl.addEventListener('click', e => {
hp = init()
fireballEl.disabled = false
startEl.disabled = true
loop()
})
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.stage {
overflow:hidden;
margin: 0 auto;
max-width: 600px;
padding: 15px;
}
.player, .monster, .split {
width: 33%;
float: left;
}
.split {
font-size: 50px;
font-weight: 900;
}
h1 {
font-size: 16px;
margin-top: 0;
}
.output {
max-width: 600px;
margin: 0 auto;
border-top: 1px solid #333;
}
.output .player-info {
background-color: forestgreen;
color: #333;
}
.output .monster-info {
background-color:fuchsia;
color: #333;
}
.output .bar {
color: #eee;
/* margin: 3px 0; */
}
.output .ability {
background-color:yellow;
font-size: 16px;
}
.output .win {
font-size: 30px;
}
.output .lose {
font-size: 30px;
}
<div class="stage">
<div class="player">
<h1>Self-confident Player</h1>
<p>HP: <span class="p-hp">100</span></p>
<div class="abl">
Spell:
<button class="fireballEl" disabled>Inaccurate fireball</button>
</div>
</div>
<div class="split">
VS
<div>
<button class="start">Start to fight</button>
</div>
</div>
<div class="monster">
<h1>Young Monster</h1>
<p>HP: <span class="m-hp">1000</span></p>
</div>
</div>
<ul class="output">
</ul>

Checking function for sliding puzzle javascript

I created a sliding puzzle with different formats like: 3x3, 3x4, 4x3 and 4x4. When you run my code you can see on the right side a selection box where you can choose the 4 formats. The slidingpuzzle is almost done. But I need a function which checks after every move if the puzzle is solved and if that is the case it should give out a line like "Congrantulations you solved it!" or "You won!". Any idea how to make that work?
In the javascript code you can see the first function loadFunc() is to replace every piece with the blank one and the functions after that are to select a format and change the format into it. The function Shiftpuzzlepieces makes it so that you can move each piece into the blank space. Function shuffle randomizes every pieces position. If you have any more question or understanding issues just feel free to ask in the comments. Many thanks in advance.
Since I don't have enough reputation I will post a link to the images here: http://imgur.com/a/2nMlt . These images are just placeholders right now.
Here is the jsfiddle:
http://jsfiddle.net/Cuttingtheaces/vkyxgwo6/19/
As always, there is a "hacky", easy way to do this, and then there is more elegant but one that requires significant changes to your code.
Hacky way
To accomplish this as fast and dirty as possible, I would go with parsing id-s of pieces to check if they are in correct order, because they have this handy pattern "position" + it's expected index or "blank":
function isFinished() {
var puzzleEl = document.getElementById('slidingpuzzleContainer').children[0];
// convert a live list of child elements into regular array
var pieces = [].slice.call(puzzleEl.children);
return pieces
.map(function (piece) {
return piece.id.substr(8); // strip "position" prefix
})
.every(function (id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == parseInt(id);
});
}
Now we need to check it somewhere, and naturally the best place would be after each move, so shiftPuzzlepieces() should be updated to call isFinished() function, and show the finishing message if it returns true:
function shiftPuzzlepieces(el) {
// ...
if (isFinished()) {
alert("You won!");
}
}
And voilà: live version.
How would I implement this game
For me, the proper way of implementing this would be to track current positions of pieces in some data structure and check it in similar way, but without traversing DOM or checking node's id-s. Also, it would allow to implement something like React.js application: onclick handler would mutate current game's state and then just render it into the DOM.
Here how I would implement the game:
/**
* Provides an initial state of the game
* with default size 4x4
*/
function initialState() {
return {
x: 4,
y: 4,
started: false,
finished: false
};
}
/**
* Inits a game
*/
function initGame() {
var gameContainer = document.querySelector("#slidingpuzzleContainer");
var gameState = initialState();
initFormatControl(gameContainer, gameState);
initGameControls(gameContainer, gameState);
// kick-off rendering
render(gameContainer, gameState);
}
/**
* Handles clicks on the container element
*/
function initGameControls(gameContainer, gameState) {
gameContainer.addEventListener("click", function hanldeClick(event) {
if (!gameState.started || gameState.finished) {
// game didn't started yet or already finished, ignore clicks
return;
}
if (event.target.className.indexOf("piece") == -1) {
// click somewhere not on the piece (like, margins between them)
return;
}
// try to move piece somewhere
movePiece(gameState, parseInt(event.target.dataset.index));
// check if we're done here
checkFinish(gameState);
// render the state of game
render(gameContainer, gameState);
event.stopPropagation();
return false;
});
}
/**
* Checks whether game is finished
*/
function checkFinish(gameState) {
gameState.finished = gameState.pieces.every(function(id, index, arr) {
if (arr.length - 1 == index) {
// last peace, check if it's blank
return id == "blank";
}
// check that every piece has an index that matches its expected position
return index == id;
});
}
/**
* Moves target piece around if there's blank somewhere near it
*/
function movePiece(gameState, targetIndex) {
if (isBlank(targetIndex)) {
// ignore clicks on the "blank" piece
return;
}
var blankPiece = findBlankAround();
if (blankPiece == null) {
// nowhere to go :(
return;
}
swap(targetIndex, blankPiece);
function findBlankAround() {
var up = targetIndex - gameState.x;
if (targetIndex >= gameState.x && isBlank(up)) {
return up;
}
var down = targetIndex + gameState.x;
if (targetIndex < ((gameState.y - 1) * gameState.x) && isBlank(down)) {
return down;
}
var left = targetIndex - 1;
if ((targetIndex % gameState.x) > 0 && isBlank(left)) {
return left;
}
var right = targetIndex + 1;
if ((targetIndex % gameState.x) < (gameState.x - 1) && isBlank(right)) {
return right;
}
}
function isBlank(index) {
return gameState.pieces[index] == "blank";
}
function swap(i1, i2) {
var t = gameState.pieces[i1];
gameState.pieces[i1] = gameState.pieces[i2];
gameState.pieces[i2] = t;
}
}
/**
* Handles form for selecting and starting the game
*/
function initFormatControl(gameContainer, state) {
var formatContainer = document.querySelector("#formatContainer");
var formatSelect = formatContainer.querySelector("select");
var formatApply = formatContainer.querySelector("button");
formatSelect.addEventListener("change", function(event) {
formatApply.disabled = false;
});
formatContainer.addEventListener("submit", function(event) {
var rawValue = event.target.format.value;
var value = rawValue.split("x");
// update state
state.x = parseInt(value[0], 10);
state.y = parseInt(value[1], 10);
state.started = true;
state.pieces = generatePuzzle(state.x * state.y);
// render game
render(gameContainer, state);
event.preventDefault();
return false;
});
}
/**
* Renders game's state into container element
*/
function render(container, state) {
var numberOfPieces = state.x * state.y;
updateClass(container, state.x, state.y);
clear(container);
var containerHTML = "";
if (!state.started) {
for (var i = 0; i < numberOfPieces; i++) {
containerHTML += renderPiece("", i) + "\n";
}
} else if (state.finished) {
containerHTML = "<div class='congratulation'><h2 >You won!</h2><p>Press 'Play!' to start again.</p></div>";
} else {
containerHTML = state.pieces.map(renderPiece).join("\n");
}
container.innerHTML = containerHTML;
function renderPiece(id, index) {
return "<div class='piece' data-index='" + index + "'>" + id + "</div>";
}
function updateClass(container, x, y) {
container.className = "slidingpuzzleContainer" + x + "x" + y;
}
function clear(container) {
container.innerHTML = "";
}
}
/**
* Generates a shuffled array of id-s ready to be rendered
*/
function generatePuzzle(n) {
var pieces = ["blank"];
for (var i = 0; i < n - 1; i++) {
pieces.push(i);
}
return shuffleArray(pieces);
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
body {
font-family: "Lucida Grande", "Lucida Sans Unicode", Verdana, Helvetica, Arial, sans-serif;
font-size: 12px;
color: #000;
}
#formatContainer {
position: absolute;
top: 50px;
left: 500px;
}
#formatContainer label {
display: inline-block;
max-width: 100%;
margin-bottom: 5px;
}
#formatContainer select {
display: block;
width: 100%;
margin-top: 10px;
margin-bottom: 10px;
}
#formatContainer button {
display: inline-block;
width: 100%;
}
.piece {
width: 96px;
height: 96px;
margin: 1px;
float: left;
border: 1px solid black;
}
.slidingpuzzleContainer3x3,
.slidingpuzzleContainer3x4,
.slidingpuzzleContainer4x3,
.slidingpuzzleContainer4x4 {
position: absolute;
top: 50px;
left: 50px;
border: 10px solid black;
}
.slidingpuzzleContainer3x3 {
width: 300px;
height: 300px;
}
.slidingpuzzleContainer3x4 {
width: 300px;
height: 400px;
}
.slidingpuzzleContainer4x3 {
width: 400px;
height: 300px;
}
.slidingpuzzleContainer4x4 {
width: 400px;
height: 400px;
}
.congratulation {
margin: 10px;
}
}
<body onload="initGame();">
<div id="slidingpuzzleContainer"></div>
<form id="formatContainer">
<label for="format">select format:</label>
<select name="format" id="format" size="1">
<option value="" selected="true" disabled="true"></option>
<option value="3x3">Format 3 x 3</option>
<option value="3x4">Format 3 x 4</option>
<option value="4x3">Format 4 x 3</option>
<option value="4x4">Format 4 x 4</option>
</select>
<button type="submit" disabled="true">Play!</button>
</form>
</body>
Here we have the initGame() function that starts everything. When called it will create an initial state of the game (we have default size and state properties to care about there), add listeners on the controls and call render() function with the current state.
initGameControls() sets up a listener for clicks on the field that will 1) call movePiece() which will try to move clicked piece on the blank spot if the former is somewhere around, 2) check if after move game is finished with checkFinish(), 3) call render() with updated state.
Now render() is a pretty simple function: it just gets the state and updates the DOM on the page accordingly.
Utility function initFormatControl() handles clicks and updates on the form for field size selection, and when the 'Play!' button is pressed will generate initial order of the pieces on the field and call render() with new state.
The main benefit of this approach is that almost all functions are decoupled from one another: you can tweak logic for finding blank space around target piece, to allow, for example, to swap pieces with adjacent ids, and even then functions for rendering, initialization and click handling will stay the same.
$(document).on('click','.puzzlepiece', function(){
var count = 0;
var imgarray = [];
var test =[0,1,2,3,4,5,6,7,8,'blank']
$('#slidingpuzzleContainer img').each(function(i){
var imgalt = $(this).attr('alt');
imgarray[i] = imgalt;
count++;
});
var is_same = (imgarray.length == test.length) && imgarray.every(function(element, index) {
return element === array2[index];
});
console.log(is_same); ///it will true if two array is same
});
try this... this is for only 3*3.. you pass the parameter and makethe array value as dynamically..

Javascript - next/previous buttons on slide show - New kid needs assistance

I am brand new at this so I apologize because I'm sure an intermediate could pull his or her answer from what's already been asked, but I need specific help.
I'm having trouble getting my "next" and "previous" buttons for my slideshow to work in Javascript. Once the user clicks through all 5 images, it needs to return to the first image, ready to click through again-- a continuous loop. I think arrays are supposed to be utilized. What am I missing?
Thank you!!
var imageCache = [];
var imageItem = 0;
var images = 0;
var captionNode;
var imageNode;
var $ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
var listNode = $("image_list");
var nextButton = $("next");
var previousButton = $("previous");
captionNode = $("caption");
imageNode = $("image");
var links = listNode.getElementsByTagName("a");
var i, linkNode, image;
for ( i = 0; i < links.length; i++ ) {
linkNode = links[i];
// Pre-load image and copy title properties.
image = new Image();
image.src = linkNode.getAttribute("href");
image.title = linkNode.getAttribute("title");
imageCache.push(image);
}
// Now record the total images we have.
images = imageCache.length;
// Set up the button handlers.
nextButton.onclick = nextButtonClick;
previousButton.onclick = previousButtonClick;
}
function nextButtonClick() {
}
function previousButtonClick() {
}
article, aside, figure, figcaption, footer, header, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
width: 380px;
margin: 0 auto;
padding: 20px;
border: 3px solid blue;
}
h1, h2, ul, p {
margin: 0;
padding: 0;
}
h1 {
padding-bottom: .25em;
color: blue;
}
h2 {
font-size: 120%;
padding: .5em 0;
}
ul {
display: none;
}
img {
height: 250px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Slide Show</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="slide_show.js"></script>
</head>
<body>
<section>
<h1>Fishing Slide Show</h1>
<ul id="image_list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<h2 id="caption">Casting on the Upper Kings</h2>
<p>
<img src="images/casting1.jpg" alt="" id="image">
</p>
<input type="button" value="Previous" name="previous" id="previous">
<input type="button" value="Next" name="next" id="next">
</section>
</body>
</html>
You have the following variables:
var imageCache = [];
var imageItem = 0;
var images = 0;
Presumably imageItem is the index of the currently displayed image (e.g. 0 for the first one) and images is the number of images (i.e. imageCache.length). To get the next image:
imageItem = ++imageItem % images;
var nextImage = imageCache[imageItem];
This will wrap around to zero when imageItem reaches the number of images in the cache. Similarly for previous:
imageItem = (--imageItem + images) % images;
var prevImage = imageCache[imageItem];
so that when imageItem reaches 0, subtracting 1 goes to -1 and adding imageCache.length sets it to the last image. The rest of the time it's left at imageItem - 1.
It's up to you to fill in the rest of the code. :-)
I would use an array zipper to implement the next and prev functions. An array zipper is a data structure that allows you to move forward and backward through an array.
function ArrayZipper(array) {
var length = array.length, index = 0;
this.getCurrent = function () {
return array[index];
};
this.getNext = function () {
return array[index = (index + 1) % length];
};
this.getPrevious = function () {
return array[index = (length + index - 1) % length];
};
}
You can use an array zipper to create a slide show as follows:
var zipper = new ArrayZipper([ "black"
, "blue"
, "green"
, "cyan"
, "red"
, "magenta"
, "yellow"
, "white"
]);
var style = $("color").style;
style.backgroundColor = zipper.getCurrent();
$("next").addEventListener("click", function () {
style.backgroundColor = zipper.getNext();
});
$("prev").addEventListener("click", function () {
style.backgroundColor = zipper.getPrevious();
});
function $(id) {
return document.getElementById(id);
}
function ArrayZipper(array) {
var length = array.length, index = 0;
this.getCurrent = function () {
return array[index];
};
this.getNext = function () {
return array[index = (index + 1) % length];
};
this.getPrevious = function () {
return array[index = (length + index - 1) % length];
};
}
#color {
height: 100px;
width: 100px;
}
<div id="color"></div>
<button id="next">Next</button>
<button id="prev">Prev</button>
Hope that helps.

Categories