Not able to get the input text box editable inside animated javascript - javascript

I have added the code snippet over here. I was trying to do some random exercise. Can someone look why my textbox is not editable. There is falling leaf animation over here. Along with I have added one textbox on top of it. But currently I am not able to add any text to the textbox.
I am just adding more text in order to overcome the error message that the post is mostly having code and not much explanation.
var LeafScene = function(el) {
this.viewport = el;
this.world = document.createElement('div');
this.leaves = [];
this.options = {
numLeaves: 20,
wind: {
magnitude: 1.2,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 0
},
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
// animation helper
this.timer = 0;
this._resetLeaf = function(leaf) {
// place leaf towards the top left
leaf.x = this.width * 2 - Math.random()*this.width*1.75;
leaf.y = -10;
leaf.z = Math.random()*200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = Math.random()*this.height/2;
}
// at the start, the leaf can be anywhere
if (this.timer == 0) {
leaf.y = Math.random()*this.height;
}
// Choose axis of rotation.
// If axis is not X, chose a random static x-rotation for greater variability
leaf.rotation.speed = Math.random()*10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = 'X';
} else if (randomAxis > 0.25) {
leaf.rotation.axis = 'Y';
leaf.rotation.x = Math.random()*180 + 90;
} else {
leaf.rotation.axis = 'Z';
leaf.rotation.x = Math.random()*360 - 180;
// looks weird if the rotation is too fast around this axis
leaf.rotation.speed = Math.random()*3;
}
// random speed
leaf.xSpeedVariation = Math.random() * 0.8 - 0.4;
leaf.ySpeed = Math.random() + 1.5;
return leaf;
}
this._updateLeaf = function(leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = 'translateX( ' + leaf.x + 'px ) translateY( ' + leaf.y + 'px ) translateZ( ' + leaf.z + 'px ) rotate' + leaf.rotation.axis + '( ' + leaf.rotation.value + 'deg )';
if (leaf.rotation.axis !== 'X') {
t += ' rotateX(' + leaf.rotation.x + 'deg)';
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
// reset if out of view
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
}
this._updateWind = function() {
// wind follows a sine curve: asin(b*time + c) + a
// where a = wind magnitude as a function of leaf position, b = wind.duration, c = offset
// wind duration should be related to wind magnitude, e.g. higher windspeed means longer gust duration
if (this.timer === 0 || this.timer > (this.options.wind.start + this.options.wind.duration)) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration = this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function(t, y) {
// should go from full wind speed at the top, to 1/2 speed at the bottom, using leaf Y
var a = this.magnitude/2 * (screenHeight - 2*y/3)/screenHeight;
return a * Math.sin(2*Math.PI/this.duration * t + (3 * Math.PI/2)) + a;
}
}
}
}
LeafScene.prototype.init = function() {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement('div'),
x: 0,
y: 0,
z: 0,
rotation: {
axis: 'X',
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0,
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = 'leaf-scene';
this.viewport.appendChild(this.world);
// set perspective
this.world.style.webkitPerspective = "400px";
this.world.style.MozPerspective = "400px";
this.world.style.oPerspective = "400px";
this.world.style.perspective = "400px";
// reset window height/width on resize
var self = this;
window.onresize = function(event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
}
LeafScene.prototype.render = function() {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
}
// start up leaf scene
var leafContainer = document.querySelector('.falling-leaves'),
leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
body, html {
height: 100%;
}
form {
width: 600px;
margin: 0px auto;
padding: 15px;
}
input[type=text] {
display: block;
padding: 10px;
box-sizing: border-box;
font-size: x-large;
margin-top: 25%;
}
input[type=text] {
width: 100%;
margin-bottom: 15px;
}
.falling-leaves {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 100%;
max-width: 880px;
max-height: 880px; /* image is only 880x880 */
transform: translate(-50%, 0);
border: 20px solid #fff;
border-radius: 50px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/sidebar-bg.png) no-repeat center center;
background-size: cover;
overflow: hidden;
}
.leaf-scene {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 100%;
transform-style: preserve-3d;
}
.leaf-scene div {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/125707/leaf.svg) no-repeat;
background-size: 100%;
transform-style: preserve-3d;
backface-visibility: visible;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="style/style.css">
</head>
<body>
<div class="falling-leaves">
<form id="frmContact">
<input type="text" id="txtName" name="txtName" placeholder="Text goes here">
</form>
</div>
<script src="script/script.js"></script>
</body>
</html>

Related

Cannot read properties of null (reading 'animate') error chrome JS animation

I am new to webdev and I am trying to use this CodePen to animate my buttons:
https://codepen.io/Mamboleoo/pen/JjdXPgR
However, I am still getting this error on chrome when trying to run the code:
Uncaught TypeError: Cannot read properties of null (reading 'animate')
I tried replacing the last JS line to: if ( document.getElementByID("aaa").animate ){} but no success.enter code here
Can anyone help me please ?
HTML
<div class="contianer">
<div class="wrapper" id="aaa">
<button data-type="square">Square particles</button>
<button data-type="emoji">Emoji particles</button>
<button data-type="mario">Mario particles</button>
<button data-type="shadow">Shadow particles</button>
<button data-type="line">Line particles</button>
</div>
<span class="preloader"></span>
</div>
CSS
particle {
position: fixed;
top: 0;
left: 0;
opacity: 0;
pointer-events: none;
background-repeat: no-repeat;
background-size: contain;
}
.wrapper {
position: absolute;
}
.wrapper button {
padding: 20px;
margin: 10px;
align-self: center;
}
.preloader {
position: absolute;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/127738/mario-face.png);
}
JS:
function pop (e) {
let amount = 30;
switch (e.target.dataset.type) {
case 'shadow':
case 'line':
amount = 60;
break;
}
// Quick check if user clicked the button using a keyboard
if (e.clientX === 0 && e.clientY === 0) {
const bbox = e.target.getBoundingClientRect();
const x = bbox.left + bbox.width / 2;
const y = bbox.top + bbox.height / 2;
for (let i = 0; i < 30; i++) {
// We call the function createParticle 30 times
// We pass the coordinates of the button for x & y values
createParticle(x, y, e.target.dataset.type);
}
} else {
for (let i = 0; i < amount; i++) {
createParticle(e.clientX, e.clientY + window.scrollY, e.target.dataset.type);
}
}
}
function createParticle (x, y, type) {
const particle = document.createElement('particle');
document.body.appendChild(particle);
let width = Math.floor(Math.random() * 30 + 8);
let height = width;
let destinationX = (Math.random() - 0.5) * 300;
let destinationY = (Math.random() - 0.5) * 300;
let rotation = Math.random() * 520;
let delay = Math.random() * 200;
switch (type) {
case 'square':
particle.style.background = `hsl(${Math.random() * 90 + 270}, 70%, 60%)`;
particle.style.border = '1px solid white';
break;
case 'emoji':
particle.innerHTML = ['❀','🧑','πŸ’›','πŸ’š','πŸ’™','πŸ’œ','🀎'][Math.floor(Math.random() * 7)];
particle.style.fontSize = `${Math.random() * 24 + 10}px`;
width = height = 'auto';
break;
case 'mario':
particle.style.backgroundImage = 'url(https://s3-us-west-
2.amazonaws.com/s.cdpn.io/127738/mario-face.png)';
break;
case 'shadow':
var color = `hsl(${Math.random() * 90 + 90}, 70%, 50%)`;
particle.style.boxShadow = `0 0 ${Math.floor(Math.random() * 10 + 10)}px ${color}`;
particle.style.background = color;
particle.style.borderRadius = '50%';
width = height = Math.random() * 5 + 4;
break;
case 'line':
var color = `hsl(${Math.random() * 90 + 90}, 70%, 50%)`;
particle.style.background = 'black';
height = 1;
rotation += 1000;
delay = Math.random() * 1000;
break;
}
particle.style.width = `${width}px`;
particle.style.height = `${height}px`;
const animation = particle.animate([
{
transform: `translate(-50%, -50%) translate(${x}px, ${y}px) rotate(0deg)`,
opacity: 1
},
{
transform: `translate(-50%, -50%) translate(${x + destinationX}px, ${y + destinationY}px)
rotate(${rotation}deg)`,
opacity: 0
}
], {
duration: Math.random() * 1000 + 5000,
easing: 'cubic-bezier(0, .9, .57, 1)',
delay: delay
});
animation.onfinish = removeParticle;
}
function removeParticle (e) {
e.srcElement.effect.target.remove();
}
if (document.body.animate) {
document.querySelectorAll('button').forEach(button => button.addEventListener('click', pop));
}

Clearinterval method is unable to clear Rotation javascript animation

I am new to JS and i am trying to move object from left to right while spinning clockwise, here i applied setinterval for movement animation from left to right and also for rotation. I am able to clearinterval Movement from left to right but unable to clearinterval my Rotation i don't know why please if you can take a look
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
e.style.left = (eLeftPos + s) + 'px';
function rot() {
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
}
var rotID = setInterval(rot, 1000)
var leftPos = (eLeftPos + s) >= 1000
if ((eLeftPos + s) >= 1000) {
clearInterval(rotID)
console.log(rotID)
}
if ((eLeftPos + s) >= 1000) {
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>
You're unable to clear the interval from the rotation, because you start a new setInterval every time the first (movement) interval executes. You'll have a new rotation interval every 1000ms. Why not just move and rotate within the same setInterval callback and then theres only 1 to cancel:
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
var leftPos = (eLeftPos + s); // new left pos
e.style.left = leftPos + 'px';
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
if (leftPos >= 100) { // made 100 just to show the effect quicker
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>

how do I make this element move backwards?

how do I stop the following interval and make the alien move backwards when it reaches 700px? I know I can do this with CSS but I want to do this strictly with JS. I don't understand how to stop the interval once it reaches the 700px left...
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = left + 2 + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
clearInterval(interval);
alien.style.left = left - 10 + "px";
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>
Any help?
Introduce a speed variable which will switch from 2 to -2 when it reaches the right limit. You should then do the same at the left side, and switch the speed from -2 to 2 again.
As you want to keep moving, the stop function is no longer needed.
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
character.style.height = 20 + "px";
character.style.width = 20 + "px";
character.style.background = "gold";
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
alien.style.height = 20 + "px";
alien.style.width = 20 + "px";
alien.style.background = "red";
alien.style.position = "absolute";
let speed = 2;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) speed = -2;
else if (left <= 0) speed = 2;
alien.style.left = left + speed + "px";
}
interval = setInterval(flow, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
}
<div class="game">
</div>
To move your element you use left + 2 so it always is moving to one direction.
So when reaching 700px mark you should reverse it to be left - 2 until it's 0.
I have modified your code adding currentDirection variable
var game = document.querySelector(".game");
var character = document.createElement("div");
character.setAttribute("class", "character");
game.appendChild(character);
var alien = document.createElement("div");
alien.setAttribute("class", "alien");
game.appendChild(alien);
var currentDirection = 1;
var hasMoved = false;
function flow() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
alien.style.left = (left + 2 * currentDirection) + "px";
}
interval = setInterval(flow, 10);
function stop() {
var left = parseInt(window.getComputedStyle(alien).getPropertyValue("left"));
if (left > 700) {
currentDirection = -1;
} else if (left < 0) {
currentDirection = 1;
}
};
setInterval(stop, 10);
* {
padding: 0;
margin: 0;
}
.game {
background: black;
height: 100vh;
}
.character {
position: absolute;
top: 490px;
left: 440px;
background: gold;
height: 20px;
width: 20px;
}
.alien {
background: red;
height: 20px;
width: 20px;
position: absolute;
}
<div class="game">
</div>

trail without a canvas

I've created the following code and I would like to have a trail following the dropped ball.
JSFiddle: https://jsfiddle.net/uj896hmq/72/
Code
var generateGame = function(){
var string = "";
var discAmount = 0;
for(var x = 0; x < 13; x++){
discAmount++;
string += "<div class='row'>";
for(var y = 1; y <= discAmount; y++){
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function(){
startGame();
});
var startGame = function(){
var $board = $('.board .wrapper'),
$el = $(".falling");
var currentRow = 0,
path = generatePath();
setInterval(function(){
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow]),
top = getPosition.position().top,
left = getPosition.position().left;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}, 500);
}
var generatePath = function(){
var path = [0];
for(var x = 1; x < 13; x++){
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
console.log(generatePath());
Point is I have no idea how I would achieve this with regular javascript and or jQuery, I thought of maybe placing a lot of divs at the position of the ball but that didn't seem proper.
Anyone has any ideas?
You can use SVG to dynamically add lines to the HTML without canvas. I've created a crude example that you can refer to. Basically it is just some calculations to position the lines.
var generateGame = function() {
var string = "";
var discAmount = 0;
for (var x = 0; x < 13; x++) {
discAmount++;
string += "<div class='row'>";
for (var y = 1; y <= discAmount; y++) {
string += "<div class='disc'></div>";
}
string += "</div>";
}
$('.board .wrapper').append(string);
var getPosition = $('.board').find('.disc').eq(0),
top = getPosition.position().top,
left = getPosition.position().left;
var $el = $('<div class="falling"></div>');
$('.board .wrapper').prepend($el);
$el.css({
top: top,
left: left
});
}
generateGame();
$(document).on('click', 'button', function() {
startGame();
});
var startGame = function() {
var $board = $('.board .wrapper'),
$el = $(".falling"),
$trail = $('.trail'),
$prevDisc = null;
var currentRow = 0,
path = generatePath();
$trail.empty();
setInterval(function() {
var getPosition = $board.find('.row').eq(currentRow).find('.disc').eq(path[currentRow])
if (getPosition.length > 0) {
var top = getPosition.position().top,
left = getPosition.position().left;
if ($prevDisc) {
var isLeft = left < $prevDisc.position().left;
drawPath($prevDisc.position().left, currentRow - 1, isLeft);
}
$prevDisc = getPosition;
$el.animate({
top: top,
left: left
}, 500);
//random between 1-2, 3-5, 4-8
currentRow++;
}
}, 500);
}
var generatePath = function() {
var path = [0];
for (var x = 1; x < 13; x++) {
var previousPath = path[x - 1];
var randomPath = generateNext(previousPath, (previousPath + 1));
path.push(randomPath);
}
return path;
}
function generateNext(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function drawPath(xPos, prevRow, isLeft) {
if (prevRow >= 0) {
var svgTopOffSet = 12;
var svgHeight = 22;
var svgWidth = 22;
var $trail = $('.trail');
var $newTrail = $(document.createElementNS('http://www.w3.org/2000/svg', 'svg'));
$newTrail.attr({
x: xPos,
y: prevRow * svgHeight + svgTopOffSet
});
var $line = $(document.createElementNS('http://www.w3.org/2000/svg', 'line'));
$line.attr({
x1: svgWidth / 2,
y1: 0,
x2: isLeft ? 0 : svgWidth,
y2: svgWidth,
style: 'stroke:orange;stroke-width:3'
});
$newTrail.append($line);
$trail.append($newTrail);
}
}
body {
background: rgb(26, 30, 35);
}
.board {
width: 500px;
height: 300px;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
.row {
display: flex;
justify-content: center;
}
.row .disc {
height: 6px;
width: 6px;
border-radius: 50%;
background: gray;
margin: 8px;
}
.wrapper .falling {
position: absolute;
height: 11px;
width: 11px;
border-radius: 50%;
background: orange;
transform: translate(50%, 50%);
z-index: 1;
}
.wrapper {
position: relative;
}
.trail {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
line { stroke-dasharray: 25; stroke-dashoffset: 25; animation: offset 0.5s linear forwards; }
#keyframes offset {
to {
stroke-dashoffset: 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='board'>
<div class='wrapper'>
<svg class="trail">
</svg>
</div>
<button>
test game
</button>
</div>

Tracking Javascript keyboard event in a player object constructor

I’m doing a simple JS 2D board game for learning purposes. And I’m having trouble making sure that the player’s movements which are kicked off by arrow-keyboard-inputs get properly tracked in the console.
Supposing, I just want to limit myself to tracking any movement using the left arrow key:
then below there is the corresponding constructor function used for pre-defining the player objects that make their moves on the board (as I said, only to the left, for the time being:
function Player(name, posY, posX, currentTurn, numberMoves, weapon, previousWeapon) {
this.name = name;
this.posY = posY;
this.posX = posX;
this.currentTurn = currentTurn;
this.numberMoves = numberMoves; // counting the number of moves player has made.
this.weapon = weapon;
this.locatePosition = function() {
var l = 0;
var m = 0;
for (l = 0; l < mapArray.length; l++) {
for (m = 0; m < mapArray.length; m++) {
if ((mapArray[l][m]) === this.number) {
this.posY = [l];
this.posX = [m];
console.log("Player Position Y: " + this.posY + " + position X: " + this.posX);
}
}
}
}
//
this.movement = function() {
document.onkeydown = (e) => {
switch (e.which) {
case 37: // left - 1
this.numberMoves += 1;
console.log("player's number of moves made:" + this.numberMoves);
this.posX = parseInt((this.posX) - 1);
this.newPosY = this.posY;
this.newPosX = this.posX;
console.log("new position: " + this.newPosY + ", " + this.newPosX);
break;
}
}
};
}
Later, however, when an object is created and I try to move it on the board using the left-key, I get this console.message:
new position: undefined, NaN
Why?
For the complete code of this work in progress:
// * / constructor function pre-defining the player objects
function Player(name, posY, posX, currentTurn, numberMoves, weapon, previousWeapon) {
this.name = name;
this.posY = posY;
this.posX = posX;
this.currentTurn = currentTurn;
this.numberMoves = numberMoves;
this.weapon = weapon;
this.locatePosition = function() {
var l = 0;
var m = 0;
for (l = 0; l < mapArray.length; l++) {
for (m = 0; m < mapArray.length; m++) {
if ((mapArray[l][m]) === this.number) {
this.posY = [l];
this.posX = [m];
console.log("Player Position Y: " + this.posY + " + position X: " + this.posX);
}
}
}
}
//
this.movement = function() {
document.onkeydown = (e) => {
switch (e.which) {
case 37: // left - 1
this.numberMoves += 1;
console.log("player's number of moves made:" + this.numberMoves);
this.posX = parseInt((this.posX) - 1);
this.newPosY = this.posY;
this.newPosX = this.posX;
console.log("new position: " + this.newPosY + ", " + this.newPosX);
break;
}
}
};
}
// * creating two Player Objects
var player1 = new Player("Red Sonja");
var player2 = new Player("Robin");
// array that will be useful for a function that answers the question: "Whose turn is it?": determineInitialTurn
var turnArray = [player1, player2];
//* function that picks a random element of an array, a function we use in determineInitialTurn
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;
};
function determineInitialTurn() {
shuffleArray(turnArray);
turnArray[0].currentTurn = true; // this player will have the first turn.
turnArray[1].currentTurn = false;
console.log("Is it " + (turnArray[0].name) + "'s turn? :" + turnArray[0].currentTurn);
};
//constructor for weapon objects
function Weapon(name, posY, posX, force) {
this.name = name;
this.posY = posY;
this.posX = posX;
this.force = force;
this.locatePositionWeapon = function() {
var l = 0;
var m = 0;
for (l = 0; l < mapArray.length; l++) {
for (m = 0; m < mapArray.length; m++) {
if ((mapArray[l][m]) === 6) {
this.posY = [l];
this.posX = [m];
console.log(this.position + " posY: " + this.posY + " + posX: " + this.posX);
}
}
}
}
};
// we create 4 weapon objects
var weapon1 = new Weapon("Tank", 10);
var weapon2 = new Weapon("Molotov", 8);
var weapon3 = new Weapon("Gun", 6);
var weapon4 = new Weapon("Bomb", 14);
// simple array where the weapons are listed. needed later in defining movement function.
var weapons = [weapon1, weapon2, weapon3, weapon4];
/*
bi-dimensional array with an initial distribution of elements.
Each number stands for an element in the game:
0 - empty
1 - rocktexture
*/
var mapArray = [ // bi-dimensional array with an initial distribution of elements (each number stands for an element in the game ()
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, weapon1, 0, player1, 0, 0, 0, 0, 0],
[0, 1, weapon2, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, weapon3, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, player2, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, weapon4, 0, 0, 0, 0, 0, 0],
];
// function that allows to shuffle the initial distribution of elements to create a random map.
function shuffleMap() {
function fisherYates(myArray) {
var i = myArray.length,
j, tempi, tempj;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = myArray[i];
tempj = myArray[j];
myArray[i] = tempj;
myArray[j] = tempi;
}
}
mapArray.forEach(fisherYates);
};
// for each number in the array there is a div and we drap the map accordingly.
function drawMap() {
for (v = 0; v < mapArray.length; v++) {
for (w = 0; w < mapArray.length; w++) {
switch ((mapArray[v][w])) {
case weapon1:
$('#container').append('<div class="weapon1"></div>');
break;
case weapon2:
$('#container').append('<div class="weapon2"></div>');
break;
case weapon3:
$('#container').append('<div class="weapon3"></div>');
break;
case weapon4:
$('#container').append('<div class="weapon4"></div>');
break;
case player1:
$('#container').append('<div class="player1"></div>');
break;
case player2:
$('#container').append('<div class="player2"></div>');
break;
case 0:
$('#container').append('<div class="empty"></div>');
break;
case 1:
$('#container').append('<div class="rock"></div>');;
break;
}
}
}
};
// the program
$('document').ready(function() {
shuffleMap();
drawMap();
determineInitialTurn();
player1.locatePosition();
player2.locatePosition();
player1.movement();
player2.movement();
});
#container {
width: 40em;
height: 40em;
border: 1px solid black;
background-color: antiquewhite;
}
.empty {
height: 4em;
width: 4em;
position: relative;
float: left;
background-color: lawngreen;
}
.rock {
height: 4em;
width: 4em;
position: relative;
float: left;
background-image: url("http://img.hb.aicdn.com/91fd74edefe009c9058249832093409b505306dd65e1-h1FZVz_fw658");
background-position: center;
background-repeat: no-repeat;
background-size: 4em;
}
.weapon1 {
height: 4em;
width: 4em;
position: relative;
float: left;
background-image: url("https://image.flaticon.com/icons/svg/544/544497.svg");
background-position: center;
background-repeat: no-repeat;
background-size: 4em;
z-index: 90;
}
.weapon2 {
height: 4em;
width: 4em;
position: relative;
float: left;
background-image: url('https://image.flaticon.com/icons/svg/544/544497.svg');
background-position: center;
background-repeat: no-repeat;
background-size: 4em;
z-index: 90;
}
.weapon3 {
height: 4em;
width: 4em;
position: relative;
float: left;
background-image: url("https://image.flaticon.com/icons/svg/544/544497.svg");
background-position: center;
background-repeat: no-repeat;
background-size: 4em;
z-index: 90;
}
.weapon4 {
height: 4em;
width: 4em;
position: relative;
float: left;
background-image: url("https://image.flaticon.com/icons/svg/544/544497.svg");
background-position: center;
background-repeat: no-repeat;
background-size: 4em;
z-index: 90;
}
.player1 {
height: 4em;
width: 4em;
position: relative;
float: left;
background-image: url("https://cdn2.iconfinder.com/data/icons/many-people-flat-icons/128/wonder-women-512.png");
background-position: center;
background-repeat: no-repeat;
background-size: 4em;
z-index: 100;
}
.player2 {
height: 4em;
width: 4em;
position: relative;
float: left;
background-image: url("https://cdn2.iconfinder.com/data/icons/many-people-flat-icons/128/superman-128.png");
background-position: center;
background-repeat: no-repeat;
background-size: 4em;
z-index: 100;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Boarderino</title>
<meta name="description" content="a simple JS board-game">
<meta name="author" content="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="js/main.js"></script>
<link rel="stylesheet" href="css/styles.css">
<!--[if lt IE 9]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div id="container"></div>
</body>
</html>
The values of this.posX, this.posY, this.numberMoves, this.weapon are never given a value. True, they are assigned a value in the Person constructor, but you don't pass the arguments, so they will still be undefined.
You'll get something when doing:
var player1 = new Player("Red Sonja", 0, 0, false, 0);
// ^^^^^^^^^^^^^^^^
...etc.
There is a lot more that should be changed/fixed in your code, but it is too much to list. Just a few things:
A function locatePosition seems useless when you already have posX, posY. It is a waste of time to look for the item in the whole array, when you know where it is by its coordinates.
In a turn-based game, the number of moves made should not be stored for each player separately, but only once. It is common to store the "ply" number instead of the move number, i.e. the count of separate moves: 0 means player1 is to move, 1 means player2 is to move, 2 means player 1 is to move, ...etc.
Similarly, you should not store the fact whether it's a player's turn in its own properties. This should either be a separate variable, and only one, or even better be just derived from the ply-number (ply % 2).
In constructors you should not accept that many arguments. It is not practical, and often not necessary either. Instead, give default values for some of the properties.

Categories

Resources