Battleship game help

Ok This is the first time I’m using this website and I am not sure if I’m gonna do this properly. I’m fairly new in the javascript world and I am currently stuck.

So the point of the battleship game is eventually, when someone will click on the hidden boat on the map, a red X imgage will show up in the td/button element.

I wanted to challenge myself by letting the user generate the size of the board before playing. But now, while I generate the table with buttons inside tds, I just want to simulate a “hit” on a boat. Which would result of showing an image with a red “X” on CLICK.

Here’s my project :

I hope someone can lead me in the right direction…

Let me know! Thank you very much in advance!

1 Like

Hello and welcome to the forum :partying_face:!

What have you tried :slight_smile:?

Think about what’s needed for your game to work. For example, wouldn’t it need to, somehow, generate the position of the ships? How would you handle that problem?

There’s a saying most programmers know: divide and conquer. This means, divide the problem into smaller pieces and it will be easier to solve :slight_smile:.

1 Like

Welcome the forum.

This is challenging project, but the best way to learn is to do it!

What you have currently is really nice and a good layout too! But from what I see, everything is just about making the board?

If i click a square nothing happens? … like @skaparate mentions above, make any square a red X when clicked.

Once you got that down, build a predefined 'ship; & only allow those square to be red. What happens if it’s a miss?

… Good luck & happy coding!

2 Likes

@skaparate Thank you for your reply. I think I posted in the wrong place since I need more help with javascript than the programming part which I already did.

This is the only piece of the puzzle that I need to make it work exactly how I want it to. Once I know how to set an “X” image in the “td” then, I will code the logic behind it all and it will be pretty much done.

Just to give you an idea how this is going to work. This was only a very basic concept with predefined random numbers as “the boat” but the logic behind would be pretty similar to that…

var boat = [5,3,2]
var counter = 0; 
var guesses = 0; 
var guess = -1;
isSunk = false; 
while(isSunk != true)
{
    guess = prompt("Ready, aim, shoot! Please enter a number between 0 to 6");
    guesses += 1; 
    while(guess < 0 || guess > 6)
    {
        guess = prompt("Please enter a valid number between 0 to 6");
        guesses += 1; 
    }
    if(boat[guess] == "HIT")
    {
        alert("You already shot this boat position")
    }
    else
    {
        if(guess == boat[0] || guess == boat[1] || guess == boat[2])
        {
            boat[guess] = "HIT";
            console.log("HIT!")
            counter++; 
            console.log(counter);
            if(counter == 3)
            {
                console.log("YOU SANK MY BOAT :(!")
                isSunk = true;
            }
        }
        else {
            console.log("YOU MISSED! HAHA")
        }
    }
}

@pjonp, Thanks! It is indeed a challenging project but I thought I would learn better if I build stuff instead of listening to tutorials.

The boat locations would be predefined in the system randomly and the logic behind the squares would be if click == Hit, then show X image on the square.

If it’s a miss, it doesn’t do anything but it would show a message to the user he missed it…

If you just want to set an image inside a td, you could write this:

 // Assuming you already know the td id or class where
// where you want to add the image
const td = document.querySelector(classOrId);
td.innerHTML = '<img src="https://domain.something/path/to/image.something" />';

Live test here: https://jsfiddle.net/skaparate/L8af0wjt/4/

1 Like

Oops, I didn’t ask properly.

IT’s a table, generating buttons inside of each tds, but I want that when the user “click” on the button, if it’s a boat, it will show the image inside the td.

I hope i explained myself better.! :slight_smile:

I understand, but I don’t want to spoil your effort :sweat_smile:, that’s why my answer was so vague.

You have a button inside a td, so, the first thing you need to do is add an event listener to handle a click for each button (you could add one to every button on the table, but that should be an exercise for you :stuck_out_tongue:). If you don’t know how to add a listener:

function handleButtonClick(e) {
  const button = e.target;
  let imgSrc = '';

  if (shipHit) {
    // add the X, right?
    imgSrc = 'path_to_X_image';
  } else {
    // Miss!
    // Nothing? Add a black hole, maybe?
    imgSrc = 'path_to_black_hole_image';
  }

  button.removeEventListener('click', handleButtonClick);
  // The following will replace the contents of the td!
  button.parentNode.innerHTML = `<img src="${imgSrc}" />`;
}

// Extracted from your own code (though incomplete):
button.style.width = "50px";
button.style.height = "50px";
button.addEventListener('click', handleButtonClick);

I think that should solve some of your problems :grin:.

1 Like

I can’t wait to test it tonight you are an awesome person !

1 Like

Those 2 lines are confusing me a lot and I would never ever found how to do this on my own :frowning:
But I get the idea, I’ll test it and see the results! :stuck_out_tongue: Again, thank you so much. I just can’t believe how great this world is sometimes!

const button = e.target;
button.parentNode.innerHTML = `<img src="${imgSrc}" />`;
1 Like

@skaparate It’s working just fine with your solution!!! I can’t thank you enough… I LOVE YOU ! :slight_smile: haha

1 Like

@skaparate Here’s a final version of mine, not perfect but the result is pretty close to what I was looking for! : https://zealous-banach-39e90e.netlify.com/

I couldn’t find how to fix an issue I had other than “bypassing” the problem. Instead of “missed” as an image, I wanted to simply use .innerHTML as “MISSED!”. But when the user would hit a miss shot on the same row, all the cells of that row would collapse to the same height as my text “missed”… I couldn’t figure it out myself so I decided to create an image instead but I think it’s ugly because of the bad resolution of the image when it’s small like that the fonts blurs a lot…
I tried to set the TD / button to min/max height and width but it wouldn’T work at all…

I wanted to let you know again, that I really appreciated your help! :slight_smile:

@skaparate Here’s the final code : https://codepen.io/MarcAndreYelle/pen/QWwreVv

Awesome! Congratulations on your initiative and willingness to learn :clap::partying_face:!

The problem you have with text is simply that you’re no appending the elements in the right order. You’re appending the tds directly to the tbody instead of the tr. The correct order (I’ll let you figure it out on the code :stuck_out_tongue:):

  1. Create the tr. This is fine on your code right now
  2. Create the td element and the children. This is fine on your code too.
  3. After the iteration, append the td to the tr.
  4. Append the tr to the table body.

That way you don’t need to set the width/height for each td.