How can I make different levels for a game? Would I have to make different classes? - javascript

I already have a sketch.js file with some gameStates.
var gameState = "wait";
I added conditional statements such as:
if(gameState == "wait"){
background(backgroundImg);
textSize(50);
fill("blue");
text("Project42 Own",250,400);
startButton.visible = true;
gun.visible = false;
backBoard.visible = false;
}
Below is the code that has level 1, wait, play and end gameState:
function draw() {
if(gameState == "wait"){
background(backgroundImg);
textSize(50);
fill("blue");
text("Project42 Own",250,400);
startButton.visible = true;
gun.visible = false;
backBoard.visible = false;
}
if(mousePressedOver(startButton)&& gameState == "wait"){
gunSound.play();
gunSound.setVolume(0)
gameState = "play";
}
if(gameState == "play"){
background("#BDA297")
fill("red");
textSize(30);
text("Score:" + score + " ",300,100);
fill("green");
text("Life:" + life + " ",800,100)
gun.y=mouseY
startButton.visible = false;
gun.visible = true;
backBoard.visible = true;
if(keyDown("SHIFT")){
shootBullets();
}
if (frameCount % 80 === 0) {
drawBlueBubble();
}
if (frameCount % 100 === 0) {
drawRedBubble();
}
if(blueBubbleGroup.collide(bulletGroup)){
handleBubbleCollision(blueBubbleGroup);
score +=5;
}
if(redBubbleGroup.collide(bulletGroup)){
handleBubbleCollision(redBubbleGroup);
score += 10;
}
if (blueBubbleGroup.collide(backBoard)){
handleGameover(blueBubbleGroup);
}
if (redBubbleGroup.collide(backBoard)) {
handleGameover(redBubbleGroup);
}
}
if (life == 0) {
gameState == "end"
}
if(gameState == "end"){
background(gameOverImg)
redBubbleGroup.hideEverything()
blueBubbleGroup.hideEverything();
}
drawSprites();
}
However, I now want to make level 2 in which there will be more obstacles. Also, I'm not a professional coder so please be clear in your answer.

Related

How can I get setInterval() to increase by 1 instead of 12?

My game has two players that get random numbers, and the person who has the bigger number gets 1 "win". My while loop is for the "auto-roll" button, and instead of clicking "roll dice" each time, auto-roll will do it for you until one player has wins == game limit # (bestof.value). No matter where I put my setInterval it increases by a bunch at a time. If bestof.value = 10 then each interval displays at least 10 wins for one player at a time.
checkBox.checked = input checkmark that enables auto-roll feature. So this setInterval will only be active while the auto-roll loop is active.
Anyways, what am I doing wrong?
button.addEventListener("click", myFunction);
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
screenID.innerHTML = random;
screenIDD.innerHTML = random2;
if (random > random2){
winNumber.innerHTML = ++a;
} else if(random2 > random){
winNumba1.innerHTML = ++b;
} else {
console.log("Draw");
}
if (a > b){
winNumber.style.color = 'white';
winNumba1.style.color = 'black';
} else if(b > a){
winNumba1.style.color = 'white';
winNumber.style.color = 'black';
} else {
winNumber.style.color = 'black';
winNumba1.style.color = 'black';
}
if (checkBox.checked){
setInterval(myFunction, 2000)
while(a < bestof.value && b < bestof.value){
myFunction();
}};
if (winNumba1.innerHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumba1 wins!');
} else if (winNumber.innterHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumber wins!');
} else {}
};
I wrote a simplified js only version of your game here since I don't have html at hand, but I am sure you can adjust it to your environment.
Main difference: I check if someone won and use return to stop the function
If no one won and autoplay is activated I autoplay after 500ms again.
let playerA = 0
let playerB = 0
let autoPlay = true
let bestOf = 3
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
console.log("New Round " + random + " vs " + random2)
if (random > random2) {
playerA++
} else if (random2 > random) {
playerB++
} else {
console.log("Draw");
}
if (playerA > playerB) {
console.log("a is winning")
} else if (playerB > playerA) {
console.log("b is winning")
} else {
console.log("There has been a draw")
}
if (playerA == bestOf) {
console.log('A won');
return
} else if (playerB == bestOf) {
console.log('B won');
return
}
if (autoPlay) {
setTimeout(myFunction, 500)
};
};
myFunction()

refactoring: How can I improve this as a clean code

I am currently studying JS myself.And make the pig-game which is project of the course that I watched. I'm always curious how can I improve my code but I got no idea where do I begin.
Is there some principle that I can improve any code?
If there's a way, Could you let me know? Thanks!
https://github.com/wonkooklee/pig-game
result : https://wonkooklee.github.io/pig-game/
below is main functions
document.querySelector('.btn-roll').addEventListener('click', function() {
if (gamePlaying) {
dice = Math.floor(Math.random() * 6) + 1;
diceDOM.style.display = 'block';
diceDOM.src = `dice-${dice}.png`;
if (dice === 6 && lastDice === 6) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
} else if (dice !== 1 && dice !== 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = 0;
} else if (dice === 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = dice;
} else {
nextPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
scores[activePlayer] += roundScore;
document.getElementById(`score-${activePlayer}`).textContent = scores[activePlayer];
let input = document.getElementById('scoreSet').value;
let winningScore;
if (isNaN(input) === false) {
winningScore = input;
} else {
document.getElementById('scoreSet').value = '100';
}
if (scores[activePlayer] >= winningScore) {
document.getElementById(`name-${activePlayer}`).textContent = 'WINNER!';
document.querySelector(`.player-${activePlayer}-panel`).classList.add('winner');
document.querySelector(`.player-${activePlayer}-panel`).classList.remove('active');
diceDOM.style.display = 'none';
gamePlaying = false;
} else {
nextPlayer();
}
}
});
Martin Fowler wrote a great book "Refactoring". Besides, Fowler has a great blog Refactoring.com, where you can find a lot of information about refactoring with examples in Javascript.
I'm not strong in Javascript, but can let you some advices about your code.
1.Simplify Conditional Logic
For example like this:
if (dice === 6 && lastDice === 6) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
return;
}
if (dice !== 1 && dice !== 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = 0;
return;
}
if (dice === 6) {
roundScore += dice;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = dice;
return;
}
nextPlayer();
2.Delete duplicated code and extract function
For example
function someFunctionName(diffRoundScore, lastDiceValue){
roundScore += diffRoundScore;
document.getElementById(`current-${activePlayer}`).textContent = roundScore;
lastDice = lastDiceValue;
}
if (dice !== 1 && dice !== 6) {
someFunctionName(dice, 0);
return;
}
if (dice === 6) {
someFunctionName(dice, dice);
return;
}
3.Change check "dice for 6" to function
function isDiceEqualsSix { return dice === 6};
if (isDiceEqualsSix && lastDice === 6) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
return;
}
if (dice !== 1 && !isDiceEqualsSix) {
someFunctionName(dice, 0);
return;
}
if (isDiceEqualsSix) {
someFunctionName(dice, dice);
return;
}
4.Change "6" to a constant variable or a function
const LIMIT_SCORE = 6;
function isDiceEqualsSix { return dice === LIMIT_SCORE};
if (isDiceEqualsSix && lastDice === LIMIT_SCORE) {
// Player looses score
scores[activePlayer] = 0;
document.getElementById(`score-${activePlayer}`).textContent = '0';
nextPlayer();
return;
}
I hope I helped you.

Function used for calculating not functioning, and a snake that can't be longer than 2?

I'm making a snake clone, and I've got the head to the second segment working. The rest of the body checks should run through automatically, but it cuts off the body at the second segment without going through the rest of the segments, despite the fact that it should. My code is as follows:
var pixels = document.getElementsByClassName('pixel'); // 0 to 95
var dir = 'right';
var foodEat = true;
var dead = true;
var snakeLong = 1;
var headPos;
var foodPix;
var foodMake = function(){ // Create Food pixel (Not On Snake)
var tempnum = Math.ceil(Math.random() * (95 - 5) + 5);
var pixstate = window.getComputedStyle(pixels[tempnum]).getPropertyValue('--state');
if (pixstate == 'snake' || pixstate == 'snakeHead' || pixstate == 'snakeEnd'){
console.log('Repeating');
foodMake();
} else {
console.log('Food Made!');
$(pixels[tempnum]).css('--state','food');
}
}
var directSend = function(reference,direction){
if (direction == 'left'){
reference -=1;
return reference;
} else if (direction == 'up'){
reference -=12;
return reference;
} else if (direction == 'right'){
reference +=1;
return reference;
} else if (direction == 'down'){
reference +=12;
return reference;
}
}
var snakeMake = function(refer,tsnakel){ // Continue To Form Snake
if (tsnakel > 0){
var tempdir = $(pixels[refer]).css('--goFrom');
console.log(directSend(refer,tempdir));
if (tsnakel = 1){
$(pixels[directSend(refer,tempdir)]).css('--state','empty');
} else {
refer = directSend(refer,tempdir);
}
tsnakel -= 1;
snakeMake(refer,tsnakel);
}
}
var snakeHEF = function(){ // Form First Sections of Snake
var Pheadpos;
var tdir;
if (dir == 'left'){ // Previous Segment Position
Pheadpos = 1;
tdir = 'right';
} else if (dir == 'up'){
Pheadpos = 12;
tdir = 'down';
} else if (dir == 'right'){
Pheadpos = -1;
tdir = 'left';
} else if (dir == 'down'){
Pheadpos = -12;
tdir = 'up';
}
$(pixels[headPos]).css('--state','snakeHead');
$(pixels[headPos]).css('--snakePos','1');
$(pixels[headPos]).css('--goFrom',tdir);
if (snakeLong == 1){ // No Food Eaten
$(pixels[headPos+Pheadpos]).css('--state','empty');
}
if (snakeLong >= 2){ // One Food Eaten
var send;
$(pixels[headPos+Pheadpos]).css('--state','snake');
$(pixels[headPos+Pheadpos]).css('--snakePos','2');
var temppos = $(pixels[headPos+Pheadpos]).css('--goFrom');
if (temppos == 'left'){
$(pixels[headPos+Pheadpos-1]).css('--state','empty');
send = headPos+Pheadpos-1;
} else if (temppos == 'up'){
$(pixels[headPos+Pheadpos-12]).css('--state','empty');
send = headPos+Pheadpos-12;
} else if (temppos == 'right'){
$(pixels[headPos+Pheadpos+1]).css('--state','empty');
send = headPos+Pheadpos+1;
} else if (temppos == 'down'){
$(pixels[headPos+Pheadpos+12]).css('--state','empty');
send = headPos+Pheadpos+12;
}
if (snakeLong > 2){ // More Than 1 Food Eaten
snakeMake(send,snakeLong-2);
}
}
}
var Game = setInterval(function(){
$(document).keydown(function(keyPressed){
if (keyPressed.keyCode == 88){ // Reset Game [x]
for (s = 0; s < 96; s++){
var pixstate = $(pixels[s]).css('--state');
if (pixstate == 'food'){
$(pixels[s]).css('--state','empty');
}
if (pixstate == 'snake' || pixstate == 'snakeHead' || pixstate == 'snakeEnd'){
$(pixels[s]).css('--state','empty');
$(pixels[s]).css('--snakePos','not');
$(pixels[s]).css('--goFrom','none');
}
}
foodEat = true;
$(pixels[0]).css('--state','snakeHead');
$(pixels[0]).css('--snakePos','1');
$(pixels[0]).css('--goFrom','left');
dead = false;
snakeLong = 1;
headPos = 0;
dir = 'right';
} // Movement Set
if (keyPressed.keyCode == 37 && dir !== 'right'){ // [<-]
dir = 'left';
} else if (keyPressed.keyCode == 38 && dir !== 'down'){ // [^^]
dir = 'up';
} else if (keyPressed.keyCode == 39 && dir !== 'left'){ // [->]
dir = 'right';
} else if (keyPressed.keyCode == 40 && dir !== 'up'){ // [vv]
dir = 'down';
}
});
if (dead == false){ //Dead Check Then Do Game Calculations
if (dir == 'left'){ // Move Head
for (s = 0; s < 8; s++){
if (headPos == 0+(12*s)){
dead = true;
}
}
if (dead == false){
headPos -= 1;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
} else if (dir == 'up'){
if (headPos < 12){
dead = true;
}
if (dead == false){
headPos -= 12;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
} else if (dir == 'right'){
for (s = 0; s < 8; s++){
if (headPos == 11+(12*s)){
dead = true;
}
}
if (dead == false){
headPos += 1;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
} else if (dir == 'down'){
if (headPos > 83){
dead = true;
}
if (dead == false){
headPos += 12;
if (foodPix == headPos){
snakeLong += 1;
foodEat = true;
}
snakeHEF();
}
}
if (foodEat == true){ // Food generator
foodMake();
foodEat = false;
}
for (s = 0; s < 96; s++){
var tpixstate = $(pixels[s]).css('--state');
if (tpixstate == 'food'){
foodPix = s;
}
}
}
for (s = 0; s < 96; s++){ // Pixel Update
var pixstate = $(pixels[s]).css('--state');
if (pixstate == 'snake' || pixstate == 'snakeHead' || pixstate == 'snakeEnd'){
$(pixels[s]).css('background-color','rgb(0,170,0)');
} else if (pixstate == 'food'){
$(pixels[s]).css('background-color','rgb(270,0,0)');
} else if (pixstate == 'empty'){
$(pixels[s]).css('background-color','rgb(68,68,68)');
}
}
},750);
Edit: To reduce confusion, I have now given the entire code.
As it turns out, I was calling the code to remove the third body segment every time, (lines 76 thru 88) even when the body was supposed to be longer.(I changed it to one '--state' changer, in an if statement checking for a body length of 2) Additionally, an if statement (line 40) was using = instead of ==, causing it to count as true each time, cutting off the fourth body segment.

How do i randomize a quiz in javascript while recording right and wrong answers?

I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}

Tell Unity that an Axis isn't being pressed when it is

Hello fellow programmers.
I'm here to ask you a very unusual question. I have created a game and in it when you hit a wall you bounce back but if you are still holding the key to go the direction you were going when you hit it it will just stay still, so I need to tell Unity that an Axis isn't being used anymore, is there a way to do this? Please note that I am using JavaScript and I am aware that it will be removed from Unity and that C# is better so don't comment that I should write code in C# please.
Code--
The movement:
if(Input.GetAxis("Forward") && isMovingBackward == false) {
if(lastDir == "backward") {
deaccelerate();
brake();
braking = true;
canRotLeft = false;
canRotRight = false;
} if(!(lastDir == "backward") && canMoveForw == true) {
accelerate();
isMoving = true;
isMovingForward = true;
isMovingBackward = false;
canRotLeft = true;
canRotRight = true;
lastDirForw();
transform.Translate(Vector3(1, 0, 0) * speed * Time.deltaTime);
}
}
if(!(Input.GetAxis("Forward"))) {
isMovingForward = false;
}
if(!(Input.GetAxis("Backward"))) {
isMovingBackward = false;
}
if(Input.GetAxis("Backward") && isMovingForward == false) {
if(lastDir == "forward") {
deaccelerate();
brake();
braking = true;
canRotLeft = false;
canRotRight = false;
} if(!(lastDir == "forward") && canMoveBack == true) {
accelerate();
isMoving = true;
isMovingBackward = true;
ifMovingForward = false;
breakingBack = false;
canRotLeft = true;
canRotRight = true;
lastDirBack();
transform.Translate(Vector3(1, 0, 0) * -speed * Time.deltaTime);
}
}
The lastDir functions:
function lastDirForw() {
if(collided == true) {
brake();
canMoveBack = false;
lastDir = "backward";
} else {
canMoveBack = true;
lastDir = "forward";
}
}
function lastDirBack() {
if(collided == true) {
brake();
canMoveForw = false;
lastDir = "forward";
} else {
canMoveForw = true;
lastDir = "backward";
}
}

Categories