Make compatible two different pieces of code - javascript

So, am creating a game where a spaceship moves and must avoid one fireball in order to win. However I would like to have many fireballs and I managed (after hours) to get this following piece of code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<style> img {position: absolute}</style>
<body id="body"></body>
<script>
const fireballArray = [];
function generateFireBallWithAttributes(el, attrs) {
for (var key in attrs) {el.setAttribute(key, attrs[key])}
return el}
function createFireBalls(amount){
for (let i = 0; i <= amount; i++) {
fireballArray.push(
generateFireBallWithAttributes(document.createElement("img"), {
src: "Photo/fireball.png", width: "36"}))}}
createFireBalls(7)
fireballArray.forEach((fireballElement) => {
const fallStartInterval = setInterval(function(){})
document.getElementById("body").appendChild(fireballElement)
const fireball = {x: fFireball(fireballElement.offsetWidth), y: 0}
const fireLoop = function() {
fireball.y += 1
fireballElement.style.top = fireball.y + "px"
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + "px"
fireball.y = 0}}
fireballElement.style.left = fireball.x + "px"
let fireInterval = setInterval(fireLoop, 1000 / ((Math.random() * (125 - 75)) + 75))})
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))}
</script>
</html>
Source: https://stackoverflow.com/questions/63328402/add-multiple-images-video-game-js
So I would like that someone could try to put together those two pieces of code (you can also give me another solution for code n°1).
I know it is not a very good question but I really need to end this game so if anyone of you can help me it would be REALLY appreciated. Thanks.
Ps: As previously said you can give me another solution for adding fireballs

Related

I want to convert paper.js Examples from paperscript to javascript

I am Japanese and I apologize for my unnatural English, but I would appreciate it if you could read it.
I learned how to convert paperscript to javascript from the official documentation.
Its means are as follows
Change the type attribute of the script tag to text/paperscript. <script type="text/paperscript" src="./main.js"></script>
Enable Paperscope for global use.  paper.install(window)
Specify the target of the canvas. paper.setup(document.getElementById("myCanvas"))
Write the main code in the onload window.onload = function(){ /* add main code */ }
Finally, add paper.view.draw()
The onFrame and onResize transforms as follows. view.onFrame = function(event) {}
onMouseDown, onMouseUp, onMouseDrag, onMouseMove, etc. are converted as follows. var customTool = new Tool(); customTool.onMouseDown = function(event) {};
I have tried these methods, but applying these to the Examples on the paper.js official site does not work correctly.
The following code is the result of trying these.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<script type="text/javascript" src="./main.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function(){
paper.setup(myCanvas)
var points = 25;
// The distance between the points:
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
customTool.onMouseMove=function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
customTool.onMouseDown=function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp=function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
The original paperscript can be found here.
What is the problem with this code?
Thank you for reading to the end!
The var vector in the for loop is not getting the correct values in your code. Change the math operators and it will work like the paperjs demo.
Math operators (+ - * /) for vector only works in paperscript. In Javascript, use .add() .subtract() .multiply() .divide(). see http://paperjs.org/reference/point/#subtract-point
// paperscript
segment.point - nextSegment.point
// javascript
segment.point.subtract(nextSegment.point)
Here's a working demo of your example
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function() {
paper.setup(myCanvas)
var points = 15; //25
// The distance between the points:
var length = 20; //35
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++) {
path.add(start + new Point(i * length, 0));
}
customTool.onMouseMove = function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
//var vector = segment.point - nextSegment.point;
var vector = segment.point.subtract(nextSegment.point);
vector.length = length;
//nextSegment.point = segment.point - vector;
nextSegment.point = segment.point.subtract(vector);
}
path.smooth({
type: 'continuous'
});
}
customTool.onMouseDown = function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp = function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
html,
body {
margin: 0
}
canvas {
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<!-- you can add this back in -->
<!-- <script type="text/javascript" src="./main.js"></script> -->
<title>Document</title>
</head>
<body>
<!-- set any size you want, or use CSS/JS to make this resizable -->
<canvas id="myCanvas" width="600" height="150"></canvas>
</body>
</html>

Github Pages as Static Image Hosting

I am trying to use GitHub pages to host static images for a website I am working on. The website randomizes div locations across the page, and it's supposed to use the photos from the repository. Here is the repository that is hosting the images.
The issue is that the images are not loading from the Github pages. Am I not referencing the photos correctly in the Javascript? Here is a photo that shows what the page looks like when I run it. As you can see, none of the images load into the webpage. Not sure if I am referencing the photo incorrectly in the JS, or if I need to add any HTML code to reference the photos. Either way, I would really appreciate any help. :)
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>page</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<!-- <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> -->
</head>
<body>
<h1><b>Issy B. Designs</b></h1><br>
<div class="random"></div>
</body>
</html>
JS:
const imgPoss = [];
let maxX, maxY;
function placeImg() {
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const randImg = Math.random() * NUM_OF_IMAGES;
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';
const {random: r} = Math;
const x = r() * maxX;
const y = r() * maxY;
if(!isOverlap(x,y)) {
var link = `<img class="random" style="left: ${x}px; top: ${y}px;" src="${imgSrc}" />`;
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = bodyHtml + link;
imgPoss.push({x, y}); // record all img positions
}
}
function isOverlap(x, y) { // return true if overlapping
const img = {x: 128, y:160};
for(const imgPos of imgPoss) {
if( x>imgPos.x-img.x && x<imgPos.x+img.x &&
y>imgPos.y-img.y && y<imgPos.y+img.y ) return true;
}
return false;
}
onload = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
setInterval(placeImg, 10);
}
onresize = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
}
In JavaScript Math.random() returns float between 0 and 1. By multiplying it by 90 you get a float, but all your photos are intigers. And since your pictures start from 10.png it should look like this
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const START_OF_IMAGES = 10;
const randImg = Math.round(Math.random() * NUM_OF_IMAGES + START_OF_IMAGES);
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';

Trying to figure out why balloon pop game is not resetting clickCount

I have followed along with video from video number 76 of the Udemy "last Intro to Programming Course". I have moved code that was included all in one function to another function called "draw" I have reviewed the video multiple times and I cannot see any difference between my code and the video. The goal of the code is to reset the clickCount back to zero. Here is the code. Help would be greatly appreciated everything is working except resetting of the balloon size and clickCount with each timeout:
let startButton = document.getElementById('start-button')
let inflateButton = document.getElementById('inflate-button')
let clickCount = 0
let height = 120
let width = 100
let inflationRate = 20
let maxsize = 300
let popCount = 0
function startGame() {
startButton.setAttribute("disabled", "true")
inflateButton.removeAttribute("disabled")
setTimeout(() => {
console.log("it's been 3 seconds")
inflateButton.setAttribute("disabled", "true")
startButton.removeAttribute("disabled")
clickCount = 0
height = 120
width = 100
draw()
}, 3000)
}
function inflate() {
clickCount++
height += inflationRate
width += inflationRate
if (height >= maxsize) {
console.log("pop the balloon")
popCount++
height = 0
width = 0
}
draw()
}
function draw() {
let balloonElement = document.getElementById("balloon")
let clickCountElem = document.getElementById("click-count")
let popCountElem = document.getElementById('pop-count')
balloonElement.style.height = height + "px"
balloonElement.style.width = width + "px"
clickCountElem.innerText = clickCount.toString()
popCountElem.innerText = popCount.toString()
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Balloon Pop</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<button id="start-button" onclick="startGame()" >START GAME</button>
</div>
<button id="inflate-button" onclick="inflate()" disabled="true">Inflate <span id="click-count"> </span></button>
<div>
<span>Balloons Popped</span>
<span id="pop-count"></span>
</div>
<div id="balloon" class="balloon" ></div>
<script src="main.js"></script>
</body>
</html>
I figured this out by looking at the source tab in dev tools. For whatever reason all of the lines weren't being saved or loaded to Chrome from VSCode. What I did was copy all the code from VSCode and pasted it into Notepad, saved and then refreshed. All is working fine now.

How to replace a moving <img> with another one during movement using JavaScript?

I have a moving image that moves across the screen from left to right. I need to replace it in the middle of the screen with another image for 5 seconds and then replace it back again resume the movement. could anyone please help me with that ?
Here's the code I have so far. I'm new to this , any help would be very much appreciated ! Thanks in advance !
const catImg = document.querySelector('img');
let marginLeft = (catImg.style.left = 0);
let marginRight = catImg.style.right;
const body = document.querySelector('body');
body.style.position = 'relative';
function catWalk() {
let halfWidth = window.innerWidth / 2 - catImg.width / 2;
marginLeft = '0px';
if (
parseInt(window.getComputedStyle(catImg).left) <
Math.floor(window.innerWidth / 2 - catImg.width / 2)
) {
marginLeft = parseInt(window.getComputedStyle(catImg).left) + 10 + 'px';
catImg.style.left = marginLeft;
return;
} else if (parseInt(window.getComputedStyle(catImg).left) == Math.round(halfWidth / 10) * 10) {
catImg.src = 'https://tenor.com/StFI.gif';
function dancingCat(timePassed) {
let startTime, endTime;
function start() {
startTime = performance.now();
return startTime;
}
function end() {
endTime = performance.now();
timePassed = endTime - startTime;
console.log(timePassed);
return endTime;
}
if (timePassed == 5000) {
catImg.src = 'http://www.anniemation.com/clip_art/images/cat-walk.gif';
}
}
} else if (
parseFloat(window.getComputedStyle(catImg).left) >
window.innerWidth - catImg.width / 2
) {
console.log('stop here');
catImg.style.left = '0px';
return;
}
return;
}
setInterval(catWalk, 50);
catWalk();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cat Walk</title>
</head>
<body>
<img style="position: absolute;" src="http://www.anniemation.com/clip_art/images/cat-walk.gif" />
<script src="ex5-catWalk.js"></script>
</body>
</html>
Based on your code I made a refactor separating each sentence between functions. BTW, try to avoid declare functions within functions. I'm giving you just an example of how can you make it. I'm sure it could be better turning each function as pure, but it works fine.
Edition
Adding some lines to start function you can achieve a loop cycle when the cat overflows the right side window.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cat Walk</title>
</head>
<body>
<img width="200" src="http://www.anniemation.com/clip_art/images/cat-walk.gif" />
<script type="text/javascript">
let interval, leftPos = 0, stopped = 0;
const img = document.querySelector('img');
const windowHalf = window.innerWidth / 2;
const middlePos = windowHalf - img.width / 2;
function step(img, size) {
leftPos += size;
return img.style.marginLeft = leftPos + 'px';
}
function start() {
interval = setInterval(() => {
if (leftPos < window.innerWidth) {
if (leftPos < middlePos || stopped) {
return step(img, 5);
} else {
clearInterval(interval);
return stop();
}
} else {
// restart variables when cat overflows window area
leftPos = 0;
stopped = 0;
}
}, 50)
}
function stop() {
img.src = 'https://tenor.com/StFI.gif';
stopped++
setTimeout(() => {
img.src = 'http://www.anniemation.com/clip_art/images/cat-walk.gif';
start()
}, 5000)
}
start();
</script>
</body>
</html>

How do I separate two svgs using raphaël?

I'm a beginner beginner. I can get the behavior that I want to occur, but instead of occurring in two separate SVGs, all the behavior is occurring in 'svg2' although I have selected the respective ids for 'svg1' and 'svg2' (or at least I think I did)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.0/raphael-min.js"></script>
<script src="logic.js"></script>
<title>Forms and Concentric Circles</title>
</head>
<body>
<h1>Forms and Concentric Circles</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany" />
<button id="more">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
var paper;
disappear = function() {
this.remove();
}
spin = function(r) {
angle = Math.random()*1440 - 720;
initial = { 'transform': 'r0' }
final = { 'transform': 'r' + angle}
r.attr(initial);
r.animate(final, 2000);
}
addMore = function() {
rectNum = $('#howmany').val();
for (step = 0; step < rectNum; step += 1) {
x = Math.random() * 180;
y = Math.random() * 180;
r = paper.rect(x, y, 20, 20);
filled = {
'fill': '#ddf'
}
r.attr(filled);
r.click(disappear);
spin(r);
}
}
radius = 10
morecircles = function() {
paper.circle(100, 100, radius);
radius = radius + 10;
}
setup = function() {
paper = Raphael('svg1', 200, 200);
$('#more').click(addMore);
paper = Raphael('svg2', 200, 200);
$('#another').click(morecircles);
}
$(document).ready(setup);
change the name for the second svg for example
paper2.circle
and in your setup function it should be
paper2.Raphael('svg2',200,200)

Categories