BattleShip

In this example below you will see how to do a BattleShip with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Archezi, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Archezi ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>BattleShip</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <body>
	
	<div id="wrapper">
		
		<div id="marker"></div>
		<div id="board"></div>
		
	</div>




 
</body>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/Archezi/battleship-aBBVQz */
body {
	

	width: 1010px;
	margin:0 auto;
	background-color: #000;
	color: #fff;
}


#board {
	min-width: 800px;
	min-height: 800px;
	padding: 100px;
	
}
.box {
	width: 98px;
	height: 98px;
	border:1px solid gray;
	text-align: center;
	cursor: pointer;
	float: left;
	line-height: 98px;
}
.box:hover {
	border:1px solid #fff;
}

/*Downloaded from https://www.codeseek.co/Archezi/battleship-aBBVQz */
 window.onload = start;

//setting array with 64 elements
var fild = new Array(64);
// setting number in every single box
for ( i = 0; i < fild.length; i++) {
	fild[i] = i + 1;
}
 

function start()
{
	//we define a box content in every single div, 
	
	var tresc_diva = "";
	//
	for ( i = 0; i <=63; i++) 
	{
    var element = "boxFild" + i;
		tresc_diva = tresc_diva +'<div class="box" onclick="check('+i+')" id="'+element+'">'+fild[i]+'</div>';
		// ( (i+1) % 8 == 0) jest to dzielenie bez reszty zeby 
		if ((i+1) % 8 == 0) tresc_diva = tresc_diva + '<div style="clear:both;"></div>';
	}
	document.getElementById("board").innerHTML = tresc_diva;
}


//RANDOM LOCATION


 var  randomLoc = fild[Math.floor(Math.random() * i)];

 var  location1 = randomLoc;
 var  location2 = location1 + 1;
 var  location3 = location2 + 1;

function check(nr) {
    
    var  hit = false;
    
    for( i=0; i<fild.length; i++) {
        if ( fild[nr] == location1 || fild[nr] == location2 || fild[nr] == location3) 
          hit = true;
    }
  if (hit == true)
     {
       var element = "boxFild" + nr;
       document.getElementById(element).style.background = "#003300";
 		document.getElementById(element).style.color = "#00C000";
 		document.getElementById(element).style.border = "1px solid #00C000";
 		document.getElementById(element).style.cursor = "default";
     }
   else 
     {
       var element = "boxFild" + nr;
 		document.getElementById(element).style.background = "#330000";
 		document.getElementById(element).style.color = "#C00000";
 		document.getElementById(element).style.border = "1px solid #C00000";
 		document.getElementById(element).style.cursor = "default";	
 		document.getElementById(element).setAttribute("onclick",";");
     }
}

Comments