CreateJS swapping display list containers with the use of classes - easeljs

This is a 2D Jenga game.
So I am currently making a Jenga game in createjs. When users take a block out from the Jenga building they can move it around, ultimately users are suppose to be able to take the piece and move it to the top like a typical Jenga game. The problem is you can take any piece out move it towards the bottom it appears to be in front of the Jenga building, but once you move a block towards the top it goes behind the building. I have a piece class which creates one block looks like this:
var GamepeiceComponent = (function() {
var assets = {};
var offset;
var gamePeice;
var currentX;
var currentY;
var newContainer;
this.makePiece = function(ingredient) {
gamePeice = new createjs.Container();
assets.peice = new createjs.Bitmap(queue.getResult(ingredient));
gamePeice.on('pressmove', handlePieceDrag);
gamePeice.on("pressup", handlePieceUp);
gamePeice.on("mousedown", handleMouseDown);
gamePeice.cursor = 'pointer';
gamePeice.addChild(assets.peice);
}
function handleMouseDown(e) {
// Game.block.swapChildren(e.currentTarget, Game.block);
for(var i = 0; i < Game.stage.children.length; i++){
console.log(Game.stage.children[i]);
//Game.stage.swapChildren(e.currentTarget, Game.stage.children[i])
}
//Game.stage.addChildAt(gamePeice,1);
offset = {x: e.target.x - e.stageX, y: e.target.y - e.stageY};
createjs.EventDispatcher.initialize(GamepeiceComponent.prototype);
gamePeice.dispatchEvent("pieceClicked");
}
function handlePieceDrag(e) {
e.target.x = e.stageX + offset.x;
e.target.y = e.stageY + offset.y;
}
function handlePieceUp(e) {
e.target.x = 0;
e.target.y = 0;
}
this.addPiece = function() {
return gamePeice;
}
return this;
});
I then have a block class which creates a block using the piece class because it creates 3 pieces per block (just like Jenga) heres what that is:
var GameblockComponent = (function() {
var gameBlock;
this.makeBlock = function(ingredient, yOffset, xOffset) {
gameBlock = new createjs.Container();
for(var i=0;i<3;i++) {
var gamePieces = new GamepeiceComponent();
var makePiece = gamePieces.makePiece(ingredient);
gamePieces.addPiece().y = yOffset * i;
gamePieces.addPiece().x = xOffset * i;
gamePieces.addPiece().on('pieceClicked', handleClick);
gameBlock.addChild(gamePieces.addPiece());
}
}
function handleClick(e) {
console.log('Game Piece Clicked');
}
this.addBlock = function() {
return gameBlock;
}
return this;
});
Lastly I have a building which organizes all the blocks in order:
var GamebuildingComponent = (function(game) {
var jengaContainer;
var left = ['burger_l', 'cheese_l', 'egg_l', 'ham_l', 'lettuce_l', 'onion_l', 'pickle_l', 'salmon_l', 'sausage_l', 'tomato_l'];
var right = ['burger_r', 'cheese_r', 'egg_r', 'ham_r', 'lettuce_r', 'onion_r', 'pickle_r', 'salmon_r', 'sausage_r', 'tomato_r'];
var bread = ['bread_l', 'bread_r'];
var seed = [];
var offsets = {
xOffsetLeft: 15,
yOffsetLeft: -33,
xPosLeft: 170,
xOffsetRight: 17,
yOffsetRight: 33,
yPosRight:100
};
function init() {
jengaContainer = new createjs.Container();
createBread(15);
createSubBlock(40);
createBread(160);
createSubBlock(185);
createBread(305);
}
function createBread(yOffset) {
var block = new GameblockComponent();
var breadLeft = block.makeBlock(bread[0], offsets.xOffsetLeft, offsets.yOffsetLeft);
block.addBlock().x = 170;
block.addBlock().y = yOffset;
jengaContainer.addChildAt(block.addBlock(), 0);
}
// LEFT: left side facing to left
// RIGHT: right side facing to right
function createSubBlock(yOffset) {
for(var i=0;i<5;i++) {
var block = new GameblockComponent();
var random = Math.floor(Math.random()*left.length);
// prevents duplicates
while(seed.indexOf(random) > -1) {
var random = Math.floor(Math.random()*left.length);
}
if(i%2 != 0) {
var ingredient = block.makeBlock(left[random], offsets.xOffsetLeft, offsets.yOffsetLeft);
block.addBlock().x = 170;
} else {
var ingredient = block.makeBlock(right[random], offsets.xOffsetRight, offsets.yOffsetRight);
block.addBlock().x = 105;
}
seed.push(random);
block.addBlock().y = 23 * i + yOffset;
jengaContainer.addChildAt(block.addBlock(), 0);
}
}
this.addBuilding = function() {
return jengaContainer;
}
init();
return this;
});
It all works fine except for when you move a lower piece towards the top the piece goes behind the jenga building, and of course its how the displaylist works, how would I be able to swap the piece correctly and where? I was listing all my child elements that are on the stage and it gave me one child (the jenga building). That child gave me 13 children (each block).
Then I just add the Jenga building to a view, and that view gets called from a controller.

You're probably looking for the setChildIndex method of the Container object.
function handleMouseDown(e) {
Game.block.setChildIndex(e.currentTarget, Game.block.children.length - 1);
}

Related

React Leaflet.Arc - Animate

I am trying create ReactLeafletArc Plugin with animation this is the code
if (!L) {
throw "Leaflet.js not included";
} else if (!arc || !arc.GreatCircle) {
throw "arc.js not included";
} else {
L.Polyline.Arc = function (from, to, options) {
from = L.latLng(from);
to = L.latLng(to);
var vertices = 10;
var arcOptions = {};
if (options) {
if (options.offset) {
arcOptions.offset = options.offset;
delete options.offset;
}
if (options.vertices) {
vertices = options.vertices;
delete options.vertices;
}
}
var generator = new arc.GreatCircle({ x: from.lng, y: from.lat }, { x: to.lng, y: to.lat });
var line = generator.Arc(vertices, arcOptions);
var latLngs = [];
var newLine = L.polyline(line.geometries[0].coords.map(function (c) {
return c.reverse();
}), options);
var totalLength = newLine._path.getTotalLength() * 4;
newLine._path.classList.add('path-start');
newLine._path.style.strokeDashoffset = totalLength;
newLine._path.style.strokeDasharray = totalLength;
setTimeout((function (path) {
return function () {
path.style.strokeDashoffset = 0;
};
})(newLine._path), 200);
return newLine;
};
}
I get error
Uncaught TypeError: Cannot read property 'getTotalLength' of undefined
with console.log(newLine) i can see that there is not _path.
NewClass
_bounds:L.LatLngBounds
_initHooksCalled:true
_latlngs:Array[100]
options:Object
__proto__:NewClass
But if i comment the part
var totalLength = newLine._path.getTotalLength() * 4;
newLine._path.classList.add('path-start');
newLine._path.style.strokeDashoffset = totalLength;
newLine._path.style.strokeDasharray = totalLength;
setTimeout((function (path) {
return function () {
path.style.strokeDashoffset = 0;
};
})(newLine._path), 200);
The line is created without animation and with console.log(newLine) i get this
NewClass
_bounds:L.LatLngBounds
_initHooksCalled:true
_latlngs:Array[100]
_leaflet_id:122
_map:NewClass
_mapToAdd:NewClass
_parts:Array[1]
_path:path
_pxBounds:L.Bounds
_renderer:NewClass
_rings:Array[1]
_zoomAnimated:true
options:Object
__proto__:NewClass
Any suggestion?

css/javascript multiple card flip: reset other cards

So I'm currently using this one: http://jsfiddle.net/nawdpj5j/10/
Now what I need is that when I flip one card (doesn't matter which one) and then flip another one the first one resets/turnes back.
I think I need to add something in here:
var init = function() {
var flippers = document.getElementsByClassName("flip");
for(i = 0; i < flippers.length; i++){
flippers[i].addEventListener( 'click', function(){
var cardID = this.dataset.targetid;
var card = document.getElementById(cardID);
card.toggleClassName('flipped');
}, false);
}
};
Thank you in advance!
You can get an array of all flipped cards and flip them back whenever a card is flipped like so:
var init = function() {
var flippers = document.getElementsByClassName("flip");
for (i = 0; i < flippers.length; i++) {
flippers[i].addEventListener('click', function() {
var cardID = this.dataset.targetid;
var card = document.getElementById(cardID);
var flipped = document.getElementsByClassName('flipped');
for (i = 0; i < flipped.length; i++) {
if (card !== flipped[i]) {
flipped[i].toggleClassName('flipped');
}
}
card.toggleClassName('flipped');
}, false);
}
};
window.addEventListener('DOMContentLoaded', init, false);
Here is a link to a working demo JS FIDDLE

jssor multiple instances - change the slide of second jssor instance on $EVT_POSITION_CHANGE event of the first jssor instance

Can anyone/jssor support help me how to change the images of second and third jssor sliders when slide show position change event trigger from the first jssor slider? I would be so much appreciated.
thanks,
c
this jssor_slider2.$GoTo(1); is not working.
++++++++++++++++++++++++++++++
function OnSlidePositionChange(slideIndex, fromIndex) {
var jssor_slider2 = new $JssorSlider$('slider2_container', { $AutoPlay: false });
if (slideIndex == 3)
jssor_slider2.$GoTo(1);
else
jssor_slider2.$GoTo(slideIndex + 1);
}
jssor_slider1.$On($JssorSlider$.$EVT_POSITION_CHANGE, OnSlidePositionChange);
++++++++++++++++++++++++++++++
<script>
jssor_slider1_starter("slider1_container");
jssor_slider2_starter("slider2_container");
jssor_slider3_starter("slider3_container");
</script>
script.js file
jssor_slider1_starter = function (containerId) {
var jssor_slider1 = new $JssorSlider$(containerId, {
...
}
function OnSlidePositionChange(slideIndex, fromIndex) {
//HELP ME PLEASE HERE.....
//var jssor_slider2 = new $JssorSlider$('slider2_container', {});
//if (slideIndex == 3)
// nestedSliders[1].$GoTo(1);
//else
// nestedSliders[1].$GoTo(slideIndex + 1);
}
jssor_slider1.$On($JssorSlider$.$EVT_POSITION_CHANGE, OnSlidePositionChange);
}
jssor_slider2_starter = function (containerId) {
var jssor_slider2 = new $JssorSlider$(containerId, {
......
}
}
jssor_slider3_starter = function (containerId) {
var jssor_slider3 = new $JssorSlider$(containerId, {
......
}
}
$JssorSlider$.$EVT_POSITION_CHANGE fires continuously while sliding.
$JssorSlider$.$EVT_PARK fires while slide change.
Please do this job this way,
function jssor_slider3_starter(containerId_1, containerId_2, containerId_3)
{
var options1 = {};
var options2 = {};
var options3 = {};
...
var jssor_slider1 = new $JssorSlider$(containerId_1, options1);
var jssor_slider2 = new $JssorSlider$(containerId_2, options2);
var jssor_slider3 = new $JssorSlider$(containerId_3, options3);
...
function OnSlidePark(slideIndex, fromIndex) {
if (slideIndex == 3)
jssor_slider2.$GoTo(1);
else
jssor_slider2.$GoTo(slideIndex + 1);
}
jssor_slider1.$On($JssorSlider$.$EVT_PARK, OnSlidePark);
...
}

drag and drop using Starling

I am have difficulty getting drop and drop to work using Starling with feathers ui.
Here is my code:
function begin(){
var quadx = squareSize/4 + squareSize/8;
var quady = 20;
var quadcounter = 0;
for(var f=0;f<totalsquares;f++){
var sprite:Sprite = new Sprite();
var quad:Quad = new Quad(squareSize, squareSize);
sprite.name = "" + f;
spriteunder.name = "" + f * 1000;
quad.setVertexColor(0, 0x3683ed);
quad.setVertexColor(1, 0x3683ed);
quad.setVertexColor(2, 0x3683ed);
quad.setVertexColor(3, 0x3683ed);
sprite.x=quadx;
sprite.y = quady;
var lv3 = new TextField(squareSize, squareSize, f,"Corpid", 14,0xf1f1f1);
sprite.touchable = true;
quad.touchable = true;
lv3.touchable = false;
sprite.addChild(quad);
sprite.addChild(lv3);
addChild(sprite);
sprite.addEventListener(TouchEvent.TOUCH, touchHandler);
quadx = quadx + squareSize + 1;
quadcounter++;
if(quadcounter == boardWidth){
quadx = squareSize/4 + squareSize/8;
quady = quady + squareSize + 1;
quadcounter = 0;
}
}
}
function touchHandler(e : TouchEvent) : void
{
var touch:Touch = e.getTouch(stage);
var position:Point = touch.getLocation(stage);
var target:Quad = e.target as Quad;
if(touch.phase == TouchPhase.MOVED ){
target.x = position.x - target.width/2;
target.y = position.y - target.height/2;
}
}
The problem is that whenever i run this , its the QUAD child that gets dragged around, not the parent sprite.
What do i change in order to get this to drag correctly.
Perhaps you must start with
var touch:Touch = event.getTouch(this, TouchPhase.BEGAN);
if (touch)
{
//get and lock your target, maybe a trace of your actual target, just to be sure!
}
And then in the MOVED phase, actually drag it.

Titanium Appcelerator Photo Gallery (Display grid of photos based on list from server)

I'm having some problems with the Photo Gallery view in Titanium Appcelerator (iPhone app). I don't really have any example code at the moment to share because I'm at a loss for exactly how this is supposed to function.
I just want to call my server for a list of images, and show these images in a grid as thumbnails that can be viewed in full screen, like you would normally expect from a phone photo gallery.
In all the example code I've looked at, it talks about saving photos to the phone. I don't really have to save however many event photos for how ever many tents all on the phone before displaying, do I?
How would I go about looping over a list of URLs to show in a grid, in a standard system way?
Thanks in advance for the help.
var newsFeed = Titanium.Facebook.requestWithGraphPath('me/feed', {}, 'GET', function(e) {
if (e.success) {
var videoObjs = new Array();
var result = (JSON.parse(e.result)).data;
for(var c = 0; c < result.length;c++) {
if(result[c].type == 'video') {
var vid = result[c].source.substring((result[c].source.indexOf("/v/"))+3, (result[c].source.indexOf('?')));
vidInfo = {
vGuid:vid,
thumb:"http://img.youtube.com/vi/"+vid+"/0.jpg",
descr:result[c].name
};
videoObjs.push(vidInfo);
}
}
updateTable(videoObjs);
buildCoverFlow(videoObjs);
buildDashboard(videoObjs);
} else if (e.error) {
alert(e.error);
} else {
alert('Unknown response');
}
});
var tableData = [];
var colorSet = [
"#D44646",
"#46D463",
"#46D4BE",
"#C2D446",
"#D446D5",
"#4575D5",
"#E39127",
"#879181",
"#E291D4"
];
var cellWidth = 240;
var cellHeight = 180;
var xSpacer = 12;
var ySpacer = 20;
var xGrid = 3;
var yGrid = parseInt(videoObjs.length / 3);
thumbProps = {
xSpace : xSpacer,
cellH : cellHeight,
cellW : cellWidth
}
for (var y=0; y<yGrid; y++) {
var thisRow = Ti.UI.createTableViewRow({
className: "grid",
layout: "horizontal",
height: cellHeight+(2*ySpacer),
selectedBackgroundColor:"red",
backgroundColor:"black"
});
for (var x=0; x<xGrid; x++) {
var index = x + xGrid * y;
var videoObj = videoObjs[index];
var thisView = createPlayerThumb(videoObj, thumbProps);
thisRow.add(thisView);
}
tableData.push(thisRow);
}
tableview.data = tableData;
tableview.separatorColor = 'black';
galWin.add(tableview);
tableview.addEventListener("click", function(e) {
if(e.source.objName) {
Ti.API.info("---> " + e.source.objName+e.source.objIndex + " was clicked!");
}
});
}
That's code I wrote for building an array of youtube thumbnails from a given facebook feed for the iPad. Should be a good start.