Make the selected images same as randomindex selected from array in javascript - javascript

I have an array notes having nine jpg's on it, and an array items nine label and nine url's on it.
this code has three boxes It selected 3 items randomly from an array items.
I have placed the randomly selected item's label inside 3 boxes, inside <P> tags, and corresponding image on background from array items
I have stored currosponding images of notes on randomIndex selection to array notesselected this is called to box002 img src
Class box002 can be dragged and dropped to the corresponding number in four boxes displayed. then blue digit and background in box dissappears.
I have a working code now
My problem is that I want the box002 item should be same as the box digit, now drop is form left side box onwards
ie if box002 digit is 2 the drop(leftmost box) should be blue 2 number with background url image2
how to change my code to make this happen.
var array2 = [];
var items = [{
label: '1',
url: 'https://via.placeholder.com/150x150.jpg?text=image1'
},
{
label: '2',
url: 'https://via.placeholder.com/150x150.jpg?text=image2'
},
{
label: '3',
url: 'https://via.placeholder.com/150x150.jpg?text=image3'
},
{
label: '4',
url: 'https://via.placeholder.com/150x150.jpg?text=image4'
},
{
label: '5',
url: 'https://via.placeholder.com/150x150.jpg?text=image5'
},
{
label: '6',
url: 'https://via.placeholder.com/150x150.jpg?text=image6'
},
{
label: '7',
url: 'https://via.placeholder.com/150x150.jpg?text=image7'
},
{
label: '8',
url: 'https://via.placeholder.com/150x150.jpg?text=image8'
},
{
label: '9',
url: 'https://via.placeholder.com/150x150.jpg?text=image9'
}
];
var notes = ['https://via.placeholder.com/75x75?text=1',
'https://via.placeholder.com/75x75?text=2',
'https://via.placeholder.com/75x75?text=3',
'https://via.placeholder.com/75x75?text=4', 'https://via.placeholder.com/75x75?text=5',
'https://via.placeholder.com/75x75?text=6',
'https://via.placeholder.com/75x75?text=7',
'https://via.placeholder.com/75x75?text=8',
'https://via.placeholder.com/75x75?text=9'
];
var tempimages = [];
var notesselected = [];
array2 = items.slice();
var item;
function rvalue() {
ptags = document.querySelectorAll('[name="values"]');
boxtags = document.getElementsByClassName("box");
for (var index = 0; index < 3; index++) {
randomIndex = Math.floor(Math.random() *array2.length)
item = array2[randomIndex];
array2.splice(randomIndex, 1);
try {
ptags[index].style.visibility = "visible";
ptags[index].textContent = item.label;
ptags[index].dataset.itemIndex = randomIndex;
tempimages.push({data: item,index: randomIndex
});
notesselected.push({data: notes[randomIndex],
index: randomIndex});
boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
} catch (err) {
console.log('Exception');
}
}
var tlen = tempimages.length;
}
function displayAllImages() {
try {
if (tempimages.length == 0) {
rvalue();
}
var arr2 = notesselected;
item = arr2.shift();
image = document.getElementById('slide');
//image.src = "images/"+item.data.url;
image.src = item.data;
image.dataset.itemIndex = item.index;
} catch (err) {
console.log(err.message);
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var el = document.getElementById(data);
var x = document.getElementById("slide").dataset.itemIndex;
var y = ev.target.dataset.itemIndex;
if (x == y) {
ev.currentTarget.style.backgroundColor = 'initial';
ev.currentTarget.style.backgroundImage = 'initial';
ev.currentTarget.style.border = 'initial';
var pParagraph = ev.currentTarget.firstElementChild;
pParagraph.style.visibility = "hidden";
item = this.item;
var arrayvalue = item.dataindex;
tempimages.splice(arrayvalue, 1);
if (tempimages.length == 0)
{
rvalue();
}
displayAllImages();
}
else {
alert("WRONG PLACED");
}
}
body {
overflow: hidden;
}
.box {
width: calc(10.3% - 4px);
display: inline-block;
border-radius: 5px;
border: 2px solid #333;
border: #000 border-color: #e6e600;
margin: -2px;
border-radius: 0%;
background-color: #99ffff;
}
.box {
height: 15vh;
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
background-size: contain;
}
.box002 {
position: absolute;
top: 10.3vh;
left: 40.98vw;
cursor: pointer;
}
.box002 img {
width: 14.0vw;
height: 23.0vh;
border-radius: 50%;
}
p {
font: "Courier New", Courier, monospace;
font-size: 30px;
color: rgba(0, 0, 0, 0.6);
text-shadow: 2px 8px 6px rgba(0, 0, 0, 0.2), 0px -5px 35px rgba(255, 255, 255, 0.3);
color: #005ce6;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container2">
<div class="containerr">
<div class="pic" id="content">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
</div>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" border="rounded" />
</div>

I think you have many things going wrong here:
Using index is a wrong idea, you can use the label as the key as you have unique item for each object.
Your displayAllImages returns wrong iterations, I have applied proper filter to display the random image from the available tempImages.
Things you need to take care of:
Assign proper levels
You can possibly use 1 array instead of 2 notes, items.
Here is the demo to resolve your problem to display the image right from the available items randomly.
I have added comments to the code, so you can check the changes.
var array2 = [];
var items = [{
label: '1',
url: 'https://via.placeholder.com/150x150.jpg?text=image1'
},
{
label: '2',
url: 'https://via.placeholder.com/150x150.jpg?text=image2'
},
{
label: '3',
url: 'https://via.placeholder.com/150x150.jpg?text=image3'
},
{
label: '4',
url: 'https://via.placeholder.com/150x150.jpg?text=image4'
},
{
label: '5',
url: 'https://via.placeholder.com/150x150.jpg?text=image5'
},
{
label: '6',
url: 'https://via.placeholder.com/150x150.jpg?text=image6'
},
{
label: '7',
url: 'https://via.placeholder.com/150x150.jpg?text=image7'
},
{
label: '8',
url: 'https://via.placeholder.com/150x150.jpg?text=image8'
},
{
label: '9',
url: 'https://via.placeholder.com/150x150.jpg?text=image9'
}
];
var notes = ['https://via.placeholder.com/75x75?text=1',
'https://via.placeholder.com/75x75?text=2',
'https://via.placeholder.com/75x75?text=3',
'https://via.placeholder.com/75x75?text=4', 'https://via.placeholder.com/75x75?text=5',
'https://via.placeholder.com/75x75?text=6',
'https://via.placeholder.com/75x75?text=7',
'https://via.placeholder.com/75x75?text=8',
'https://via.placeholder.com/75x75?text=9'
];
var tempimages = [];
var notesselected = [];
array2 = items.slice();
var item;
function rvalue() {
ptags = document.querySelectorAll('[name="values"]');
boxtags = document.getElementsByClassName("box");
//if array length is 0 then we need to identify the game as completed
if (array2.length === 0) {
alert('Game completed');
return;
}
for (var index = 0; index < 3; index++) {
randomIndex = Math.floor(Math.random() * array2.length)
item = array2[randomIndex];
array2.splice(randomIndex, 1);
try {
ptags[index].style.visibility = "visible";
ptags[index].textContent = item.label;
ptags[index].dataset.itemLabel = item.label;
//using label as an identity
tempimages.push({
data: item,
label: item.label
});
notesselected.push({
data: item.url,
label: item.label
});
boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
} catch (err) {
console.log('Exception');
}
}
var tlen = tempimages.length;
}
function displayAllImages() {
try {
if (tempimages.length == 0) {
rvalue();
}
if(tempimages.length === 0){
image = document.getElementById('slide');
image.style.display = 'none';
return;
}
// getting random item from the available items
var arr2 = tempimages;
item = arr2[Math.floor(Math.random() * arr2.length)]
image = document.getElementById('slide');
//getting notes item
var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
image.src = dataURL;
image.dataset.itemLabel = item.label;
} catch (err) {
console.log(err.message);
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var x = document.getElementById("slide").dataset.itemLabel;
var y = ev.target.dataset.itemLabel;
//add improvisation box drag is valid
if(ev.target.tagName === "DIV"){
y = ev.target.children[0].dataset.itemLabel;
}
if (x == y) {
ev.currentTarget.style.backgroundColor = 'initial';
ev.currentTarget.style.backgroundImage = 'initial';
ev.currentTarget.style.border = 'initial';
var pParagraph = ev.currentTarget.firstElementChild;
pParagraph.style.visibility = "hidden";
item = this.item;
tempimages = tempimages.filter(a => a.label !== item.label);
if (tempimages.length == 0) {
rvalue();
}
displayAllImages();
} else {
alert("WRONG PLACED");
}
}
body {
overflow: hidden;
}
.box {
width: calc(10.3% - 4px);
display: inline-block;
border-radius: 5px;
border: 2px solid #333;
border: #000 border-color: #e6e600;
margin: -2px;
border-radius: 0%;
background-color: #99ffff;
}
.box {
height: 15vh;
display: inline-flex;
align-items: center;
justify-content: center;
cursor: pointer;
background-size: contain;
}
.box002 {
position: absolute;
top: 10.3vh;
left: 40.98vw;
cursor: pointer;
}
.box002 img {
width: 14.0vw;
height: 23.0vh;
border-radius: 50%;
}
p {
font: "Courier New", Courier, monospace;
font-size: 30px;
color: rgba(0, 0, 0, 0.6);
text-shadow: 2px 8px 6px rgba(0, 0, 0, 0.2), 0px -5px 35px rgba(255, 255, 255, 0.3);
color: #005ce6;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container2">
<div class="containerr">
<div class="pic" id="content">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
</div>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" border="rounded" />
</div>

Related

How to Output chosen DIV elements that are stored in an array

I'm creating a card game where the user chooses 2 out of 3 cards. I then store those cards into an array and want to be able to print out the cards that were stored in the array with the actual image of the cards that the user chose.
I've tried looping through the array and then using innerHTML to push the results to a specific div but I keep getting "[object HTMLDivElement]". It also prints that out 3 times instead of 2 (since we are choosing 2 cards there should only be two elements to print out, I suspect the loop is running an extra time).
The below is the loop I have tried but I also am including a codepen for further clarity.
https://codepen.io/cramos2/pen/pMVjez
var holder = document.getElementById("cardResults");
for(var i=0; i < chosenCards.length; i++){
holder.innerHTML += "<p>" + chosenCards[i] + "</p><br>";
}
let chosenCards = new Array();
class tarot {
//constructor
constructor(cards) {
this.cardsArray = cards;
}
startReading() {
this.shuffleCards(this.cardsArray);
//call shuffle method
}
//Adds class "flipped" to the cards
flipCard(card, cards) {
if (this.canFlipCard(card)) {
if (chosenCards.length >= 2) {
console.log("removing1");
//from here
for (let card0 in cards) {
let list = card0.classList;
if (list) {
if (!list.contains('visible')) {
card0.removeEventListener('click', card0.fn);
}
}
}
} //to here
else if (!card.classList.contains('visible')) {
debugger;
card.classList.add('visible');
chosenCards.push(card);
console.log(chosenCards);
//this is where print out
var holder = document.getElementById("cardResults");
for (var i = 0; i < chosenCards.length; i++) {
holder.innerHTML += "<p>" + chosenCards[i] + "</p><br>";
}
card.removeEventListener('click', card.fn);
}
}
}
//Need a Shuffle method in here
shuffleCards(cardsArray) {
for (let i = cardsArray.length - 1; i > 0; i--) {
const randIndex = Math.floor(Math.random() * (i + 1));
[cardsArray[i], cardsArray[randIndex]] = [cardsArray[randIndex], cardsArray[i]];
}
cardsArray = cardsArray.map((card, index) => {
card.style.order = index;
});
}
//gets the card
getCardType(card) {
return card.getElementsByClassName('card-value')[0].src;
}
//returns card
canFlipCard(card) {
return card
}
}
//this will call the reading to start when page is loaded
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
//declares card's' & sets it to the card class in HTML
let cards = Array.from(document.getElementsByClassName('card'));
//creates new instance of tarot class
let tarotReading = new tarot(cards);
let over = Array.from(document.getElementsByClassName('over'));
over.forEach(overlay => {
overlay.addEventListener('click', () => {
overlay.classList.remove('visible');
tarotReading.startReading();
});
});
//flips the cards
cards.forEach(card => {
card.addEventListener('click', card.fn = function clicked() {
tarotReading.flipCard(card, cards);
//remove cards that dont have visible tag
});
})
console.log(chosenCards[0]);
}
h1 {
color: #7B68EE;
padding left: 50px;
padding right: 50px;
padding-top: 5px;
text-align: center;
}
.container {
display: grid;
grid-template-columns: repeat(6, auto);
grid-gap: 10px;
margin: 50px;
justify-content: center;
perspective: 500px;
}
.card {
position: relative;
height: 175px;
width: 125px;
}
.card-face {
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
backface-visibility: hidden;
border-radius: 12px;
border-width: 1px;
border-style: solid;
transition: transform 500ms ease-in-out;
}
.card.visible .card-back {
transform: rotateY(-180deg);
}
.card.visible .card-front {
transform: rotateY(0)
}
.card-back {
background-color: black;
border-color: white;
color: white;
}
.card-front {
background-color: black;
border-color: white;
color: white;
transform: rotateY(180deg);
}
<body>
<h1>Tarot</h1>
<div class="container">
<div class="card">
<div class="card-back card-face card1" id="card1">
<p> 1
<p>
</div>
<div class="card-front card-face">
<p> The Hermit
<p>
</div>
</div>
<div class="card">
<div class="card-back card-face card2">
2
</div>
<div class="card-front card-face">
The Fool
</div>
</div>
<div class="card">
<div class="card-back card-face card3">
3
</div>
<div class="card-front card-face">
The Empress
</div>
</div>
</div>
<button type="button" class="over container">Shuffle</button>
</div>
<hr>
<div id="cardResults">
</div>
</body>
The expected result would be the flipped over card with the text (not the number of the card) that the user has chosen.
You could try something like this:
for(var i=0; i < chosenCards.length; i++){
holder.appendChild(chosenCards[i].cloneNode(true));
}

images from array to img src of class in javascript

I have some code which tries to display temporary images from tempimages[] to img src with id=slide of box002, according to the random number selected from arrayVariable to ptag[i].
I want to display tempimages[0] first on img src of class box002, after dropping that image it gets deleted by the function Drop(ev), after that tempimages[i] should display img src of box002 for dropping likewise.
How to display images from an image array tempimages to class box img src?
I have used the function displayAllImages() to allocate images to img src id=slide, but it failed to display images.
box002 can be dragged and dropped to any box.
I want to display each image one by one from tempimages[] to img src of the box after each drop. How to change the code to achieve this property?
var tempimages = [];
function rvalue() {
var array = [];
var arrayVariable = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
var ArrayOfImages = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg'];
arrayLength = arrayVariable.length;
ptags = document.getElementsByName("values");
for (i = 0; i < ptags.length; i++) {
ptags[i].innerHTML = arrayVariable[Math.floor(Math.random() * arrayLength)];
array.push(ptags[i].textContent);
tempimages.push(`${ptags[i].textContent}.jpg`); // want to display array to box002 to imgtag
}
}
function displayAllImages() {
var
i = 0,
len = tempimages.length;
for (; i < tempimages.length; i++) {
var img = new Image();
img.src = tempimages[i];
img.style.width = '100px';
img.style.height = '100px';
document.getElementById('slide').appendChild(img);
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var el = document.getElementById(data);
el.parentNode.removeChild; // deleting drag item
ev.target.style.backgroundColor = 'initial'; //[value indicate which box element] bgcoclor none
var pParagraph = ev.target.firstElementChild;
ev.target.removeChild(pParagraph);
alert(el);
}
#container {
margin-top:-2%;
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.box {
background-color: coral;
width: 60px;
height:60px;
margin-top:10px;
display:inline-block;
border-radius:5px;
border:2px solid #333;
border-color: #e6e600;
border-radius: 10%;
background-color: #ffcc00;
}
.box002 {
float: left;
width: 50px;
height: 50px;
float: left;
margin-left:30%;
padding-top:2%;
background-color:#ffff00 2px;
border:2px solid #000066;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
#container {
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="rvalue()">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>
</div>
</body>
I'm not a 100% sure what it is you're trying achieve but here is something which might get you to the where you want to get. It picks three items at random and updates the image in the slide element after each time the slide is dropped on one of the boxes.
I've made a couple of changes, see the comments in the code as to why I've made the changes. When I saw this code first I didn't understand the need for two separate arrays so I've merged them into a single array.
var tempimages = [];
function rvalue() {
const
items = [
{ label: '1', url: 'https://via.placeholder.com/75x75?text=1' },
{ label: '2', url: 'https://via.placeholder.com/75x75?text=2' },
{ label: '3', url: 'https://via.placeholder.com/75x75?text=3' },
{ label: '4', url: 'https://via.placeholder.com/75x75?text=4' },
{ label: '5', url: 'https://via.placeholder.com/75x75?text=5' },
{ label: '6', url: 'https://via.placeholder.com/75x75?text=6' },
{ label: '7', url: 'https://via.placeholder.com/75x75?text=7' },
{ label: '8', url: 'https://via.placeholder.com/75x75?text=8' },
{ label: '9', url: 'https://via.placeholder.com/75x75?text=9' },
{ label: '10', url: 'https://via.placeholder.com/75x75?text=10' }
],
ptags = Array.from(document.querySelectorAll('[name="values"]'));
ptags.forEach(ptag => {
const
// Generate a random index.
randomIndex = Math.floor(Math.random() * items.length),
// Get the at item from the random index (it is possible the same item
// gets picked multiple times as there is no check for duplicates).
item = items[randomIndex];
// Update the label
ptag.textContent = item.label;
// Push the item into the array.
tempimages.push(item);
});
}
function displayAllImages() {
// Check if there are still images in the array, if not exit.
if (tempimages.length === 0) {
return;
}
const
// Remove the item at index 0 from the array.
item = tempimages.shift(),
// Get the image element.
image = document.getElementById('slide');
// Update src attribute so it points to the new URL.
image.src = item.url;
};
$(function() {
// On start, do rvalue first. This is taken from the onload in the body
// as that fired later than this method which meant displayAllImages was
// called before rvalue.
rvalue();
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var el = document.getElementById(data);
el.parentNode.removeChild; // deleting drag item
// ev.currentTarget is a div with class box whereas target can
// be either the div or the p element. Using currentTarget ensures
// you know which element you're working with.
ev.currentTarget.style.backgroundColor = 'initial'; //[value indicate which box element] bgcoclor none
var pParagraph = ev.currentTarget.firstElementChild;
ev.currentTarget.removeChild(pParagraph);
// Show the next image in the slider..
displayAllImages();
}
#container {
margin-top:-2%;
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.box {
background-color: coral;
width: 60px;
height:60px;
margin-top:10px;
display:inline-block;
border-radius:5px;
border:2px solid #333;
border-color: #e6e600;
border-radius: 10%;
background-color: #ffcc00;
}
.box002 {
float: left;
width: 50px;
height: 50px;
float: left;
margin-left:30%;
padding-top:2%;
background-color:#ffff00 2px;
border:2px solid #000066;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
#container {
white-space:nowrap;
text-align:center;
margin-left:20%;
margin-right:30%;
}
.text {
padding: 20px;
margin:7 px;
margin-top:10px;
color:white;
font-weight:bold;
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" style="width:30px; height:30px; border-radius: 50%;" border="rounded"/>
</div>
</body>

Vue.js Battle - confirm box overrides reset function

i'm currently working through Udemy's Vue.js tutorial. I've reached the section where you are building a battle web app game. After finishing it, I decided to practice my refactoring and came across this bug.
When you click the attack buttons and then the confirm box comes up to ask if you want to play again, it seems to add one extra item in my log array instead of resetting the game fully.
I'm suspecting it is to do with pressing the attack buttons too quickly, and then the confirm box comes up before running an addToLog() and then it runs it afterwards.
Or it could be my bad code. lol
Note that I know that clicking cancel on the confirm box also comes up with bugs too.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Monster Slayer</title>
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<link rel="stylesheet" href="css/foundation.min.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div id="app">
<section class="row">
<div class="small-6 columns">
<h1 class="text-center">YOU</h1>
<div class="healthbar">
<div class="healthbar text-center" style="background-color: green; margin: 0; color: white;" :style="{width: playerHealth + '%'}">
{{ playerHealth }}
</div>
</div>
</div>
<div class="small-6 columns">
<h1 class="text-center">BADDY</h1>
<div class="healthbar">
<div class="healthbar text-center" style="background-color: green; margin: 0; color: white;" :style="{width: computerHealth + '%'}">
{{ computerHealth }}
</div>
</div>
</div>
</section>
<section class="row controls" v-if="!isRunning">
<div class="small-12 columns">
<button id="start-game" #click="startGame">START GAME</button>
</div>
</section>
<section class="row controls" v-else>
<div class="small-12 columns">
<button id="attack" #click="attack">ATTACK</button>
<button id="special-attack" #click="specialAttack">SPECIAL ATTACK</button>
<button id="heal" #click="heal">HEAL</button>
<button id="restart" #click="restart">RESTART</button>
</div>
</section>
<section class="row log" v-if="turns.length > 0">
<div class="small-12 columns">
<ul>
<li v-for="turn in turns" :class="{'player-turn': turn.isPlayer, 'monster-turn': !turn.isPlayer}">
{{ turn.text }}
</li>
</ul>
</div>
</section>
</div>
<script src="app.js"></script>
</body>
</html>
css/app.css
.text-center {
text-align: center;
}
.healthbar {
width: 80%;
height: 40px;
background-color: #eee;
margin: auto;
transition: width 500ms;
}
.controls,
.log {
margin-top: 30px;
text-align: center;
padding: 10px;
border: 1px solid #ccc;
box-shadow: 0px 3px 6px #ccc;
}
.turn {
margin-top: 20px;
margin-bottom: 20px;
font-weight: bold;
font-size: 22px;
}
.log ul {
list-style: none;
font-weight: bold;
text-transform: uppercase;
}
.log ul li {
margin: 5px;
}
.log ul .player-turn {
color: blue;
background-color: #e4e8ff;
}
.log ul .monster-turn {
color: red;
background-color: #ffc0c1;
}
button {
font-size: 20px;
background-color: #eee;
padding: 12px;
box-shadow: 0 1px 1px black;
margin: 10px;
}
#start-game {
background-color: #aaffb0;
}
#start-game:hover {
background-color: #76ff7e;
}
#attack {
background-color: #ff7367;
}
#attack:hover {
background-color: #ff3f43;
}
#special-attack {
background-color: #ffaf4f;
}
#special-attack:hover {
background-color: #ff9a2b;
}
#heal {
background-color: #aaffb0;
}
#heal:hover {
background-color: #76ff7e;
}
#restart {
background-color: #ffffff;
}
#restart:hover {
background-color: #c7c7c7;
}
app.js
new Vue({
el: app,
data: {
playerHealth: 100,
computerHealth: 100,
isRunning: false,
turns: [],
},
methods: {
startGame: function() {
this.isRunning = true;
this.playerHealth = 100;
this.computerHealth = 100;
this.clearLog();
},
attackController: function(attacker, maxRange, minRange) {
let receiver = this.setReceiver(attacker);
let damage = 0;
if (attacker === 'player') {
damage = this.randomDamage(maxRange, minRange);
this.computerHealth -= damage;
}
if (attacker === 'computer') {
damage = this.randomDamage(maxRange, minRange);
this.playerHealth -= damage;
}
this.addToLog(attacker, receiver, damage);
if (this.checkWin()) {
return;
}
},
attack: function() {
this.attackController('player', 10, 3);
this.attackController('computer', 10, 3);
},
specialAttack: function() {
this.attackController('player', 30, 5);
this.attackController('computer', 30, 5);
},
heal: function() {
if (this.playerHealth <= 90) {
this.playerHealth += 10;
} else {
this.playerHealth = 100;
}
this.turns.unshift({
isPlayer: true,
text: 'Player heals for ' + 10,
});
},
randomDamage: function(max, min) {
return Math.floor(Math.random() * max, min);
},
checkWin: function() {
if (this.computerHealth <= 0) {
this.alertBox('YOU WIN! New Game?');
} else if (this.playerHealth <= 0) {
this.alertBox('LOSER!!! New Game?');
}
return false;
},
alertBox: function(message) {
if (confirm(message)) {
this.isRunning = false;
this.startGame();
} else {
this.isRunning = false;
}
return true;
},
restart: function() {
this.isRunning = false;
this.startGame();
},
addToLog: function(attacker, receiver, damage) {
this.turns.unshift({
isPlayer: attacker === 'player',
text: attacker + ' hits ' + receiver + ' for ' + damage,
});
},
clearLog: function() {
this.turns = [];
},
setReceiver: function(attacker) {
if (attacker === 'player') {
return 'computer';
} else {
return 'player';
}
},
damageOutput: function(attacker, health) {
if (attacker === 'player') {
damage = this.randomDamage(maxRange, minRange);
this.computerHealth -= damage;
}
},
},
});
Github repo is here if you prefer that. Thanks!
Your attack (and specialAttack) function attacks for both players:
attack: function() {
this.attackController('player', 10, 3);
this.attackController('computer', 10, 3);
},
Currently, it is checking for win at every attackController call. So when the first attacker (player) wins, the game resets AND the second player attacks.
So, my suggestion, move the checkWin out of the attackController into the attack functions:
attack: function() {
this.attackController('player', 10, 3);
this.attackController('computer', 10, 3);
this.checkWin();
},
The same to specialAttack.
Code/JSFiddle: https://jsfiddle.net/acdcjunior/wwc1xnyc/10/
Note, when the player wins, in the code above, the computer will still "strike back", even though the game is over. If you want to halt that, make checkWin return if the game is over:
checkWin: function() {
if (this.computerHealth <= 0) {
this.alertBox('YOU WIN! New Game?');
return true;
} else if (this.playerHealth <= 0) {
this.alertBox('LOSER!!! New Game?');
return true;
}
return false;
},
And add an if to attack (and specialAttack):
attack: function() {
this.attackController('player', 10, 3);
if (this.checkWin()) return;
this.attackController('computer', 10, 3);
this.checkWin();
},
Updated fiddle: https://jsfiddle.net/acdcjunior/wwc1xnyc/13/

Is it possible to simplify this matrix-like column selecting built with javascript?

I have a grid and when selecting an item in it, i want to add different classes to every column that is before or after the current item. I came up with the following function to do this, but wondering if theres an easier and simpler way to do this:
var items = document.querySelectorAll('.item');
var bodyWidth = 200;
var itemWidth = 50;
var itemsInRow = Math.floor(bodyWidth/itemWidth);
var activeItemIndexInRow;
var directionClass;
var otherItemIndexInRow;
var removeClasses = function(){
items.forEach(function (item, i) {
item.className = 'item';
});
}
items.forEach(function (selectedItem, selectedItemIndex) {
selectedItem.addEventListener('click', function(event) {
removeClasses();
activeItemIndexInRow = selectedItemIndex-Math.floor(selectedItemIndex/itemsInRow)*itemsInRow;
selectedItem.classList.add('active');
items.forEach(function (otherItem, otherItemIndex) {
otherItemIndexInRow = otherItemIndex-Math.floor(otherItemIndex/itemsInRow)*itemsInRow;
if(otherItemIndexInRow < activeItemIndexInRow) directionClass = 'green';
if(otherItemIndexInRow === activeItemIndexInRow) directionClass = 'red';
if(otherItemIndexInRow > activeItemIndexInRow) directionClass = 'blue';
otherItem.classList.add(directionClass);
});
});
});
* {
margin:0;
padding:0;
}
#wrapper {
width: 400px;
}
.item {
width:25%;
background:gray;
text-align:center;
height:100px;
line-height:100px;
color:#fff;
font-size:30px;
float:left;
}
.item.green {background:green}
.item.red {background:red}
.item.blue {background:blue}
.item.active {background:black}
<div id="wrapper">
<div class="item">1</div><div class="item">2</div><div class="item">3</div><div class="item">4</div><div class="item">5</div><div class="item">6</div><div class="item">7</div><div class="item">8</div><div class="item">9</div><div class="item">10</div>
</div>
This should work.
var items = document.querySelectorAll('.item');
var itemsInRow = 4;
items.forEach(function(selectedItem, selectedItemIndex) {
selectedItem.addEventListener('click', function(event) {
var directionClass;
selectedItem.classList.add('active');
var selectedCol = selectedItemIndex % itemsInRow;
items.forEach(function(otherItem, otherItemIndex) {
otherItem.className = 'item';
var otherCol = otherItemIndex % itemsInRow;
if (otherItemIndex === selectedItemIndex) directionClass = 'active';
else if (otherCol === selectedCol) {
directionClass = 'red';
} else {
directionClass = selectedCol < otherCol ? 'blue' : 'green'
}
otherItem.classList.add(directionClass);
});
});
});
* {
margin: 0;
padding: 0;
}
#wrapper {
width: 400px;
}
.item {
width: 25%;
background: gray;
text-align: center;
height: 100px;
line-height: 100px;
color: #fff;
font-size: 30px;
float: left;
}
.item.green {
background: green
}
.item.red {
background: red
}
.item.blue {
background: blue
}
.item.active {
background: black
}
<div id="wrapper">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>

How to download sketch with quote included

I will try this one more time.
I am having trouble getting the quote to download as part of the sketch canvas. I am using sketch.js.
Here is the jsfiddle, you can draw like MSpaint but I when pressing the download button only what is drawn is copied. I would like the sketch and the words downloaded.
http://jsfiddle.net/e1ovm9mn/
I should also add that I am quite new to all.
Here is the code
<body>
<nav>
<div id="SketchTools">
<!-- Basic tools -->
<img src="img/black_icon.png" alt="Black"/>
<img src="img/red_icon.png" alt="Red"/>
<img src="img/green_icon.png" alt="Green"/>
<img src="img/blue_icon.png" alt="Blue"/>
<img src="img/yellow_icon.png" alt="Yellow"/>
<img src="img/cyan_icon.png" alt="Cyan"/>
<!-- Advanced colors -->
<img src="img/alizarin_icon.png" alt="Alizarin"/>
<img src="img/pomegrante_icon.png" alt="Pomegrante"/>
<img src="img/emerald_icon.png" alt="Emerald"/>
<img src="img/torquoise_icon.png" alt="Torquoise"/>
<img src="img/peterriver_icon.png" alt="Peter River"/>
<img src="img/amethyst_icon.png" alt="Amethyst"/>
<img src="img/sunflower_icon.png" alt="Sun Flower"/>
<img src="img/orange_icon.png" alt="Orange"/>
<img src="img/clouds_icon.png" alt="Clouds"/>
<img src="img/silver_icon.png" alt="Silver"/>
<img src="img/asbestos_icon.png" alt="Asbestos"/>
<img src="img/wetasphalt_icon.png" alt="Wet Asphalt"/>
</br> <img src="img/eraser_icon.png" alt="Eraser"/>
<!-- Size options -->
<img src="img/pencil_icon.png" alt="Pencil"/>
<img src="img/pen_icon.png" alt="Pen"/>
<img src="img/stick_icon.png" alt="Stick"/>
<img src="img/smallbrush_icon.png" alt="Small brush"/>
<img src="img/mediumbrush_icon.png" alt="Medium brush"/>
<img src="img/bigbrush_icon.png" alt="Big brush"/>
<img src="img/bucket_icon.png" alt="Huge bucket"/>
Download
<br/>
</div>
<div class="links">
<ul>
<li><img src="ficon.png" alt="Facebook"></li>
<li><img src="igramicon.png" alt="Instagram"></li>
<li><img src="picon.png" alt="Pinterest"></li>
<li><img src="mcicon.png" alt="Mixcloud"></li>
<li><img src="twicon.png" alt="Twitter"></li>
</ul>
</div>
<div class="message">
<div id="quote"></div>
<script>
(function() {
var quotes = [
{ text: "Snuggletooth likes pancakes"},
{ text: "Would you like Snuggletooth to tuck you in?"},
{ text: " Snuggletooth loves you"},
{ text: "Snuggletooth is here for you"},
{ text: "Did you know that Snuggletooth </br>can be in 2 places at once?"},
{ text: "Heyyyy!<br> I was just thinking about you </br>Love Snuggletooth" },
{ text: "Wanna Sandwich??</br>xSnuggletooth"},
{ text: "Want some breakfast???</br> ;) Snuggletooth"},
{ text: "Snuggletooth-a-riffic!!!"},
{ text: "Snuggletooth makes great popcorn!"},
{ text: "Come over to Snuggletooth's! He makes a great guacamole!"},
{ text: "Snuggletooth likes his bubblebaths to smell like bubblegum"},
{ text: "Snuggletooth wants to know what are you up to later?"},
{ text: "Snuggletooth-a-licious!!!"},
];
var quote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("quote").innerHTML =
'<p>' + quote.text + '</p>' +
'' + '';
})();
</script>
</div>
</nav>
<canvas id="SketchPad" width="1125" height="600">
</canvas>
</div>
<script type="text/javascript">
$(function() {
$('#SketchPad').sketch();
});
</script>
</body>
And here is the sketch.js
var __slice = Array.prototype.slice;
(function($) {
var Sketch;
$.fn.sketch = function() {
var args, key, sketch;
key = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (this.length > 1) {
$.error('Sketch.js can only be called on one element at a time.');
}
sketch = this.data('sketch');
if (typeof key === 'string' && sketch) {
if (sketch[key]) {
if (typeof sketch[key] === 'function') {
return sketch[key].apply(sketch, args);
} else if (args.length === 0) {
return sketch[key];
} else if (args.length === 1) {
return sketch[key] = args[0];
}
} else {
return $.error('Sketch.js did not recognize the given command.');
}
} else if (sketch) {
return sketch;
} else {
this.data('sketch', new Sketch(this.get(0), key));
return this;
}
};
Sketch = (function() {
function Sketch(el, opts) {
this.el = el;
this.canvas = $(el);
this.context = el.getContext('2d');
this.options = $.extend({
toolLinks: true,
defaultTool: 'marker',
defaultColor: 'black',
defaultSize: 5
}, opts);
this.painting = false;
this.color = this.options.defaultColor;
this.size = this.options.defaultSize;
this.tool = this.options.defaultTool;
this.actions = [];
this.action = [];
this.canvas.bind('click mousedown mouseup mousemove mouseleave mouseout touchstart touchmove touchend touchcancel', this.onEvent);
if (this.options.toolLinks) {
$('body').delegate("a[href=\"#" + (this.canvas.attr('id')) + "\"]", 'click', function(e) {
var $canvas, $this, key, sketch, _i, _len, _ref;
$this = $(this);
$canvas = $($this.attr('href'));
sketch = $canvas.data('sketch');
_ref = ['color', 'size', 'tool'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
if ($this.attr("data-" + key)) {
sketch.set(key, $(this).attr("data-" + key));
}
}
if ($(this).attr('data-download')) {
sketch.download($(this).attr('data-download'));
}
return false;
});
}
}
Sketch.prototype.download = function(format) {
var mime;
format || (format = "png");
if (format === "jpg") {
format = "jpeg";
}
mime = "image/" + format;
return window.open(this.el.toDataURL(mime));
};
Sketch.prototype.set = function(key, value) {
this[key] = value;
return this.canvas.trigger("sketch.change" + key, value);
};
Sketch.prototype.startPainting = function() {
this.painting = true;
return this.action = {
tool: this.tool,
color: this.color,
size: parseFloat(this.size),
events: []
};
};
Sketch.prototype.stopPainting = function() {
if (this.action) {
this.actions.push(this.action);
}
this.painting = false;
this.action = null;
return this.redraw();
};
Sketch.prototype.onEvent = function(e) {
if (e.originalEvent && e.originalEvent.targetTouches) {
e.pageX = e.originalEvent.targetTouches[0].pageX;
e.pageY = e.originalEvent.targetTouches[0].pageY;
}
$.sketch.tools[$(this).data('sketch').tool].onEvent.call($(this).data('sketch'), e);
e.preventDefault();
return false;
};
Sketch.prototype.redraw = function() {
var sketch;
this.el.width = this.canvas.width();
this.context = this.el.getContext('2d');
sketch = this;
$.each(this.actions, function() {
if (this.tool) {
return $.sketch.tools[this.tool].draw.call(sketch, this);
}
});
if (this.painting && this.action) {
return $.sketch.tools[this.action.tool].draw.call(sketch, this.action);
}
};
return Sketch;
})();
$.sketch = {
tools: {}
};
$.sketch.tools.marker = {
onEvent: function(e) {
switch (e.type) {
case 'mousedown':
case 'touchstart':
this.startPainting();
break;
case 'mouseup':
case 'mouseout':
case 'mouseleave':
case 'touchend':
case 'touchcancel':
this.stopPainting();
}
if (this.painting) {
this.action.events.push({
x: e.pageX - this.canvas.offset().left,
y: e.pageY - this.canvas.offset().top,
event: e.type
});
return this.redraw();
}
},
draw: function(action) {
var event, previous, _i, _len, _ref;
this.context.lineJoin = "round";
this.context.lineCap = "round";
this.context.beginPath();
this.context.moveTo(action.events[0].x, action.events[0].y);
_ref = action.events;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
event = _ref[_i];
this.context.lineTo(event.x, event.y);
previous = event;
}
this.context.strokeStyle = action.color;
this.context.lineWidth = action.size;
return this.context.stroke();
}
};
return $.sketch.tools.eraser = {
onEvent: function(e) {
return $.sketch.tools.marker.onEvent.call(this, e);
},
draw: function(action) {
var oldcomposite;
oldcomposite = this.context.globalCompositeOperation;
this.context.globalCompositeOperation = "copy";
action.color = "rgba(0,0,0,0)";
$.sketch.tools.marker.draw.call(this, action);
return this.context.globalCompositeOperation = oldcomposite;
}
};
})(jQuery);
And just in case here is the css
#import url(http://fonts.googleapis.com/css?family=Codystar);
#import url(http://fonts.googleapis.com/css?family=Lobster);
img {
width: 25px;
height: 25px;
}
li{
}
ul li {
list-style-type: none;
display: inline;
}
.message {
margin-left: 20%;
margin-top: 20%;
z-index: 1;
position: absolute;
font-family: Lobster, Codystar, arial;
font-size: 3.5em;
color:white;
text-align: center;
text-shadow: 2px 2px #ff0000;
}
.links {
float: right;
padding-right: 1em;
}
#SketchPad {
border-color: black;
border-width: 3px;
border-style: solid;
position: fixed;
}
#DownloadPng {
padding: 4px 2px;
font-size: 1em;
line-height: 100%;
text-shadow: 0 1px rgba(0, 0, 0, 0.5);
color: #fff;
display:inline-block;
/*vertical-align: middle;
text-align: center;*/
cursor: pointer;
font-weight: bold;
transition: background 0.1s ease-in-out;
-webkit-transition: background 0.1s ease-in-out;
-moz-transition: background 0.1s ease-in-out;
-ms-transition: background 0.1s ease-in-out;
-o-transition: background 0.1s ease-in-out;
text-shadow: 0 1px rgba(0, 0, 0, 0.3);
color: #fff;
font-family: Arial, sans-serif;
background-color: #2ecc71;
box-shadow: 0px 7px 0px 0px #27ae60;
text-decoration: none;
margin-top: 10px;
margin-bottom: 15px;
}
#DownloadPng:hover {
background-color: #27ae60;
border-radius: 7px;
}
#DownloadPng:active {
box-shadow: 0px 1px 0px 0px #27ae60;
border-radius: 7px;
}
#SketchTools {
width: 65%;
height: 5%;
position: fixed;
float: left;
z-index: 1;
padding: .2em;
}

Categories