Skip to content

Instantly share code, notes, and snippets.

@bjblock
Created May 29, 2019 16:40
Show Gist options
  • Save bjblock/821d8d0b5461176e4548521cea1d19a0 to your computer and use it in GitHub Desktop.
Save bjblock/821d8d0b5461176e4548521cea1d19a0 to your computer and use it in GitHub Desktop.
Challenge #1 - Jonathan Ebbers
.center {
margin: auto;
padding: 70px 0;
}
.center h1 {
margin: auto;
width: 50%;
vertical-align: middle;
}
div.snake-world {
margin: auto;
width: 100%;
vertical-align: middle;
border: 3px solid purple;
height: 100%;
}
div.snake {
background-color: gray;
width: 10px;
height: 10px;
position: absolute;
}
div.apple {
background-color: red;
width: 10px;
height: 10px;
position: absolute;
}
<!DOCTYPE html>
<html>
<title>Snake!</title>
<head>
<link rel="stylesheet" href="snake.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body class="center">
<h1>Snake!</h1>
<div class="snake-world">
</div>
<script src="snake.js"></script>
</body>
</html>
// set grid size at random
var gridSize = getRandomInt(40) + 10;
var edgeLength = (gridSize * 10) + 'px';
$('.center').css('height', edgeLength);
$('.center').css('width', edgeLength);
// insert the snake starting position
var snakeX = getRandomInt(gridSize);
var snakeY = getRandomInt(gridSize);
var snake = $('<div></div>').addClass('snake');
snake.css('margin-left', (snakeX * 10) + 'px');
snake.css('margin-top', (snakeY * 10) + 'px');
$('.snake-world').append(snake);
// insert the apple initially
insertApple();
$('.center').keypress(function(e) {
console.log(e);
switch (e.charCode) {
case 38:
console.log('up');
case 39:
console.log('right');
case 40:
console.log('down');
case 37:
console.log('left');
}
})
// to get a random coordinate
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
// insert the apple
function insertApple() {
var appleX = getRandomInt(gridSize);
var appleY = getRandomInt(gridSize);
var apple = $('<div></div>').addClass('apple');
apple.css('margin-left', (appleX * 10) + 'px');
apple.css('margin-top', (appleY * 10) + 'px');
$('.snake-world').append(apple);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment