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

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.

Related

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

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.

why I'm getting "max call stack size exceeded" error

I'm working on minimax part of a tic tac toe game, and I keep getting "max call stack size exceeded" error. I isolated the bug to line # 110 which is emptyIndexies(board) function. But I don't see anything wrong with the function. I tested it on the console, and the board seems to update when I click on it; however, the computer turn don't work. Here's the code
var board = [0, 1, 2, 3, 4, 5, 6, 7, 8];
var player, sqrId, user, computer, row, col;
const ARR_LENGTH = 9;
$(document).ready(function() {
//1 checkbox event listener
$(".checkBox").click(function() {
if($(this).is(":checked")) {
user = $(this).val();
player = user;
computer = (user == 'X') ? 'O' : 'X';
}
});
//2 square even listener
$(".square").click(function() {
sqrId = $(this).attr("id");
playerMove();
minimax(board);
if(checkWinner(board, turn)) {
alert(turn+" Wins the game!");
resetBoard();
}
if(!checkDraw()) {
alert("It's a draw!");
}
player = (player == user) ? computer : user;
});
//reset board
$(".reset").click(function() {
resetBoard();
})
});
//player move
function playerMove() {
if($("#"+sqrId).text() == "") {
$("#"+sqrId).text(player);
board[sqrId] = player;
console.log(board);
}
else {
alert("Wrong move");
}
}
/* computer AI generate random number between 0 - 8 */
function computerAI() {
var random;
var min = 0, max = 8;
do {
random = Math.floor(Math.random() * (max + min));
}while($("#"+random).text() != "")
$("#"+random).text(computer);
row = getRow();
col = getCol();
board[row][col] = computer;
}
//getting row number
function getRow() {
return Math.floor(sqrId / ARR_LENGTH);
}
//getting col number
function getCol() {
return sqrId % ARR_LENGTH;
}
/* checking for winner */
// winning combinations using the board indexies
function winning(board){
if (
(board[0] == player && board[1] == player && board[2] == player) ||
(board[3] == player && board[4] == player && board[5] == player) ||
(board[6] == player && board[7] == player && board[8] == player) ||
(board[0] == player && board[3] == player && board[6] == player) ||
(board[1] == player && board[4] == player && board[7] == player) ||
(board[2] == player && board[5] == player && board[8] == player) ||
(board[0] == player && board[4] == player && board[8] == player) ||
(board[2] == player && board[4] == player && board[6] == player)
) {
return true;
} else {
return false;
}
}
function resetBoard() {
$(".square").text("");
$(".checkBox").prop("checked", false);
user = "";
turn = "";
computer = "";
for(var i = 0; i < ARR_LENGTH; i++) {
board[i] = "";
}
}
// returns list of the indexes of empty spots on the board
function emptyIndexies(board){
return board.filter(s => s != "O" && s != "X");
}
// the main minimax function
function minimax(newBoard, player){
//available spots
var availSpots = emptyIndexies(newBoard);
// checks for the terminal states such as win, lose, and tie
//and returning a value accordingly
if (winning(newBoard, user)){
return {score:-10};
}
else if (winning(newBoard, computer)){
return {score:10};
}
else if (availSpots.length === 0){
return {score:0};
}
// an array to collect all the objects
var moves = [];
// loop through available spots
for (var i = 0; i < availSpots.length; i++){
//create an object for each and store the index of that spot
var move = {};
move.index = newBoard[availSpots[i]];
// set the empty spot to the current player
newBoard[availSpots[i]] = player;
/*collect the score resulted from calling minimax
on the opponent of the current player*/
if (player == computer){
var result = minimax(newBoard, user);
move.score = result.score;
}
else{
var result = minimax(newBoard, computer);
move.score = result.score;
}
// reset the spot to empty
newBoard[availSpots[i]] = move.index;
// push the object to the array
moves.push(move);
}
// if it is the computer's turn loop over the moves and choose the move with the highest score
var bestMove;
if(player === computer){
var bestScore = -10000;
for(var i = 0; i < moves.length; i++){
if(moves[i].score > bestScore){
bestScore = moves[i].score;
bestMove = i;
}
}
}else{
// else loop over the moves and choose the move with the lowest score
var bestScore = 10000;
for(var i = 0; i < moves.length; i++){
if(moves[i].score < bestScore){
bestScore = moves[i].score;
bestMove = i;
}
}
}
// return the chosen move (object) from the moves array
return moves[bestMove];
}

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();
}

How to compare two variables in javascript

I want to match two variables.
var this_roll;
and
var last_roll;
I have this code, that i want the output of "win" or "losse". The output should be "win" if last_roll and this_roll have the same value and "lose" if not
"use strict";
var x;
var win_losse = 'losse';
var last_roll;
var last_bet;
var this_roll = $('#past')[0].childNodes[9].textContent;
var bet_input = document.getElementById('betAmount').value=x;
var roll_time = $('#banner')[0].childNodes[0].textContent;
var base_bet = 5;
function thisRoll() {
console.log(this_roll);
if (this_roll == 0) {
this_roll = 'green';
} else if ((this_roll >= 1) && (this_roll <= 7)) {
this_roll = 'red';
} else if ((this_roll >= 8) && (this_roll <= 14)) {
this_roll = 'black';
}
}
function compare() {
if (this_roll == last_roll) {
win_losse = 'win';
} else {
win_losse = 'losse';
}
console.log(win_lose);
}
function lastRoll() {
console.log(this_roll);
if (this_roll == 0) {
last_roll = 'green';
} else if ((this_roll >= 1) && (this_roll <= 7)) {
last_roll = 'red';
} else if ((this_roll >= 8) && (this_roll <= 14)) {
last_roll = 'black';
}
}
function bet() {
if (win_losse == 'win') {
x = base_bet;
} else if (win_losse == 'losse') {
x = last_bet * 2;
}
}
console.log(x);
This works for sure
"use strict";
//Removed the global x variable
//Removed the global win_lose variable
var last_roll = $('#past')[0].childNodes[8].textContent;
var last_bet;
var this_roll = $('#past')[0].childNodes[9].textContent;
var bet_input = document.getElementById('betAmount').value=x;
//Removede the Roll_time variable because it wasn't used
var base_bet = 5;
function ThisRoll(this_roll) {
var rollhisThis; //Added a local variable
if (this_roll === 0) {
rollhisThis = 'green';
} else if ((this_roll >= 1) && (this_roll <= 7)) {
rollhisThis = 'red';
} else if ((this_roll >= 8) && (this_roll <= 14)) {
rollhisThis = 'black';
}
return rollhisThis; //Added return
}
var thisRoll = ThisRoll(this_roll); //Added a new global variable
console.log(thisRoll);
function LastRoll(last_roll) {
var rollhisLast; //Added a local variable
if (last_roll === 0) {
rollhisLast = 'green';
} else if ((last_roll >= 1) && (last_roll <= 7)) {
rollhisLast = 'red';
} else if ((last_roll >= 8) && (last_roll <= 14)) {
rollhisLast = 'black';
}
return rollhisLast; //Added return
}
var lastRoll = LastRoll(last_roll); //Added a new global variable
console.log(LastRoll);
function compare(thisRoll, lastRoll) {
var win_lose; //Added a local win_lose variable
if (thisRoll !== lastRoll) {
win_lose = 'lose';
} else {
win_lose = 'win';
}
return win_lose; //Added return
}
var winLose = compare(thisRoll, lastRoll); //Added a gloabl variable
console.log(winLose);
function bet() {
if (win_losse == 'win') {
x = base_bet;
} else if (win_losse == 'losse') {
x = last_bet * 2;
}
}
console.log(x);

rps function not working (javascript)

Rps game code isn't working. My battle function is supposed to set win to a 1,2, or 3 but it always stays at the default 0. I've checked the other values through the console, and they all seem to be working. here is my code.
function Player(number) {
this.number = number;
this.choice = 0;
}
var player1 = new Player(1);
var player2 = new Player(2);
var win = 0;
var battle = function() {
if (player1.choice === player2.choice) {
win = 3;
} else if (player1.choice + 2 === player2.choice && player1.choice === 1){
win = 2;
} else if (player1.choice + 1 === player2.choice && player1.choice === 1) {
win = 1;
} else if (player1.choice + 1 === player2.choice && player1.choice === 2) {
win = 1;
} else if (player1.choice - 1 === player2.choice && player1.choice === 2) {
win = 2;
} else if (player1.choice - 1 === player2.choice && player1.choice === 3) {
win = 2;
} else if (player1.choice - 2 === player2.choice && player1.choice === 3) {
win = 1;
} else {
alert ('someone pressed the wrong button')
}
}
var Reset = function () {
win = 0;
player1.choice = 0;
player2.choice = 0;
}
$(document).ready(function() {
$(document).keydown(function(event) {
if (event.which === 81) {
player1.choice = 1;
} else if (event.which === 87){
player1.choice = 2;
} else if (event.which === 69){
player1.choice = 3;
} else if (event.which === 37){
player2.choice = 1;
} else if (event.which === 40){
player2.choice = 2;
} else if (event.which === 39){
player2.choice = 3;
}
})
if (player1.choice > 0 && player2.choice > 0) {
battle();
if (win === 1) {
$('.winner').append('<p>player1 wins!</p>')
} else if (win === 2) {
$('.winner').append('<p>player2 wins!</p>')
} else if (win === 3) {
$('.winner').append('<p>It is a draw!</p>')
}
}
})
My html has the div with class 'winner' in it.
Additional question
How do I cancel the keydown function after both players have chosen their options.
Are you giving your player a choice in the Player class you created? It should look like this:
function Player(number, choice) {
this.number = number;
this.choice = choice;
}

Categories