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.
Related
On the press of the button 'leave' I want 10 new 'leave' buttons to be displayed on the screen. Each one of these buttons needs to display 10 new buttons on the screen when clicked.
But only the original 'leave' button displays 10 new buttons, the newly cloned ones don't.
Javascript code:
const container = document.querySelector('.container');
const leaveButton = document.querySelector('#leave');
leaveButton.addEventListener('click', () => {
for (let i = 0; i < 10; i++) {
const newButton = document.createElement('button');
newButton.innerHTML = leaveButton.innerHTML;
newButton.style.top = Math.random() * window.innerHeight + 'px';
newButton.style.left = Math.random() * window.innerWidth + 'px';
newButton.setAttribute("id", "leave");
container.appendChild(newButton);
}
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PressTheButton</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<button id="leave">Leave</button>
<h1>It's simple</h1>
<p>Just click the buttons</p>
</div>
<script src="script.js"></script>
</body>
</html>
Instead of adding the event listener to a fixed button you should work with delegated event listening. In the snippet below I added the click event to the parent container. Inside the event listener callback function I briefly check, wether the .textContent of the clicked element is equal to "Leave" and, if not, I return immediately without carrying out any action.
const container = document.querySelector('.container');
const leaveButton = document.querySelector('#leave');
container.addEventListener('click', ev => {
if (ev.target.textContent!=="Leave") return;
for (let i = 0; i < 10; i++) {
const newButton = document.createElement('button');
newButton.innerHTML = leaveButton.innerHTML;
newButton.style.top = Math.random() * window.innerHeight + 'px';
newButton.style.left = Math.random() * window.innerWidth + 'px';
newButton.setAttribute("id", "leave");
container.appendChild(newButton);
}
});
button {position:absolute}
<head>
<meta charset="UTF-8">
<title>PressTheButton</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<button id="leave">Leave</button>
<h1>It's simple</h1>
<p>Just click the buttons</p>
</div>
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';
So what I am trying to do is make a clicker game, yet when I use the standard:
let Coins = 0;
function setup() {
createCanvas(400, 400)
}
//draws the circle
function draw() {
background(100)
circle(200, 200, 50)
//creates the text to show the amount of coins
text(Coins, 200 - (textWidth(Coins) / 2), 150)
}
//detects when the mouse is pressed
function mouseClicked() {
//changes the number of coins
Coins = Coins + 1
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
I can click anywhere and it will count up the Coins, but I want it so that if the mouse is On the shape/element it will then count.
I don't want to use the "If (mouseX => width / 2)" but just know when the mouse is over/hovering over the element.
In p5js you need to implement "hit testing" yourself. In this case you can do so by checking if the distance between the mouse and the center of the coin is less than the radius of the coin.
let Coins = 0;
function setup() {
createCanvas(400, 400)
}
let coinPosition = new p5.Vector(200, 200);
let coinRadius = 25;
//draws the circle
function draw() {
background(100)
push()
if (dist(mouseX, mouseY, coinPosition.x, coinPosition.y) <= coinRadius) {
fill('gold')
}
circle(coinPosition.x, coinPosition.y, coinRadius * 2)
// restore the previous fill value
pop()
//creates the text to show the amount of coins
text(Coins, 200 - (textWidth(Coins) / 2), 150)
}
//detects when the mouse is pressed
function mouseClicked() {
if (dist(mouseX, mouseY, coinPosition.x, coinPosition.y) <= coinRadius) {
//changes the number of coins
Coins = Coins + 1
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
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
I'm trying to create a timer within an object - however when trying to increment the counter by the time that's passed I'm getting a NaN error. The error stops if I replace the deltaTime argument with a constant, but then the jump time would vary depending upon the end users machine and work load.
class Actor {
constructor() {
this.jumpCounter = 0
this.jumpTimer = function (deltaTime) {
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}
}
}
let canvas = document.getElementById('gameScreen');
let ctx = canvas.getContext("2d");
var lastTime = 0;
const GAME_WIDTH = 600;
const GAME_HEIGHT = 600;
actor = new Actor;
function gameLoop(timestamp) {
let deltaTime = timestamp - lastTime;
lastTime = timestamp;
ctx.fillStyle = 'rgba(155, 200, 155, 0.3)'
ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
actor.jumpTimer(deltaTime)
requestAnimationFrame(gameLoop);
}
gameLoop();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Sandbox</title>
<style>
#gameScreen {
border: 1px solid;
}
</style>
</head>
<body>
<canvas id="gameScreen" width="600" height="600"></canvas>
<script></script>
</body>
</html>
As the error resulted from there being on timestamp on the first run through of the code this fixed the issue:
this.jumpTimer = function (deltaTime) {
if (!deltaTime) return;
console.log(this.jumpCounter);
this.jumpCounter += deltaTime;
console.log(deltaTime)
}