Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <title>EcoSnake</title>
- <style>
- html, body {
- height: 100%;
- margin: 0;
- }
- body {
- background: white;
- display: flex;
- align-items: center;
- justify-content: center;
- text-align: center;
- color: black;
- }
- canvas {
- border: 2px solid black;
- }
- #game {
- background-image: url("https://ae01.alicdn.com/kf/HTB1jjG0a7CWBuNjy0Faq6xUlXXaT/Artificial-fake-green-grass-Background-Vinyl-cloth-High-quality-Computer-print-wall-photo-backdrop.jpg");
- }
- </style>
- </head>
- <body>
- <!-- title -->
- <img src= "ecosnake.png" style="width:450px">
- <canvas width="720" height="720" id="game"></canvas>
- <script>
- // id of game is canvas defined above - 720x720
- var canvas = document.getElementById('game'),
- // returns drawing context on the canvas
- context = canvas.getContext('2d');
- make_base = () =>
- {
- // snake chases image of soda - create at (x,y) points
- // can.x and can.y will be determined later
- var soda = new Image();
- soda.src = 'soda.jpg';
- soda.onload = () => {
- context.drawImage(soda, can.x, can.y);
- }
- return soda;
- }
- // img will be soda, (x,y) are points, and size
- drawImgCoord = (img, x, y, size) => {
- const centerX = x - size/6;
- const centerY = y - size/6;
- context.drawImage(img, centerX, centerY, size, size);
- }
- var soda = make_base();
- var block = 16,
- count = 0,
- snake = {
- x: 160,
- y: 160,
- //by default, x val of snake moves one block per frame (speed), y doesn't move
- dx: block,
- dy: 0,
- // array showing blocks covered by snakes
- snakeBlocks: [],
- // initial length of snake
- startSnakeBlocks: 6
- };
- var can = {
- x: 320,
- y: 320
- };
- // get random whole numbers in a specific range
- randNum = (min, max) => {
- return Math.floor(Math.random() * (max - min)) + min;
- }
- let isGameOver = false;
- // game loop
- loop = () => {
- requestAnimationFrame(loop);
- if (isGameOver) {
- gameOverLoop();
- } else {
- gameLoop();
- }
- }
- gameOverLoop = () => {
- var randFactNum = Math.floor((Math.random() * 7));
- var randFacts =
- [ "About 2.8 million tonnes of plastic waste ends up in Canadian landfills every year, equivalent to the weight of 24 CN towers: In order to do your part to reduce the amount of waste, you can follow the three R's, Reduce, Reuse and Recycle. In this way, we can save natural resources and free landscape",
- "On average 9 billion tonnes of litter will find its way into our oceans. You can do your part by volunteering in your community and picking up all the litter. Remember - our environment is everyone's environment.",
- "Only 61% of people on Earth are aware of Climate Change (roughly 2.4 billion people). You can do your part by informing friends and family about climate change and the importance of keeping our Earth clean and green. The more the better :)",
- "Only 0.4% of the world's water supply can actually be used as drinking water for us, yet we waste 680 liters per week in the average household. That is roughly 35,000 liters of water wasted per year! In order to do your part, you can take small actions that will have a large impact,such as turning the tap off when brushing your teeth or even taking shorter showers rather than taking long baths.",
- "33 billion tonnes of carbon emissions enter the atmosphere every year. These are not good for our Earth as they make our planet much hotter and also paves the way to frequent natural disasters. In order to do your part you can simply plant a few trees because trees take in carbon emissions and let out clean breathable air for us all. You can save the world and have a little plant buddy as well.",
- "Around 8 million tonnes of plastic items are sent into our oceans every year, making sea animals very sick. You can save the lives of your ocean buddies by simply asking your parents to use reusable shopping bags or even using reusable water bottles.",
- "Each car you see on the road emits around 4.6 tons of carbon emissions every year, which is roughly 157 million tons of carbon emissions each year in Canada alone. In order to help reduce this number you can take simple actions such as riding a bike to where you want to go or taking the bus for a change. It may not feel like it but everytime you avoid riding in a car you are helping to save the planet.",
- "Global warming is destroying the beautiful coral reefs in the ocean and The use of electricity has a big role since carbon emissions are emitted in the process of making electricity. Small actions such as turning off the lights when you are not in a room or telling your parents to change to energy efficient LED light bulbs can go a very long way."
- ]
- var randFact = randFacts[randFactNum]
- if(isGameOver){
- alert("GAME OVER! Did you know: " + randFact);
- }
- isGameOver = false;
- }
- gameLoop = () => {
- // frames per second
- if (++count < 2.5) {
- return;
- }
- count = 0;
- // clear rectangle where canvas is
- context.clearRect(0, 0, canvas.width, canvas.height);
- // snake moves at the speed it is at
- snake.x += snake.dx;
- snake.y += snake.dy;
- if (snake.x < 0) {
- snake.x = canvas.width - block;
- }
- else if (snake.x >= canvas.width) {
- snake.x = 0;
- }
- // wrapping:
- if (snake.y < 0) {
- snake.y = canvas.height - block;
- }
- else if (snake.y >= canvas.height) {
- snake.y = 0;
- }
- // tracks snake's location
- snake.snakeBlocks.unshift({x: snake.x, y: snake.y});
- // as snake moves away snake blocks, remove them using .pop()
- if (snake.snakeBlocks.length > snake.startSnakeBlocks) {
- snake.snakeBlocks.pop();
- }
- // draw can
- drawImgCoord(soda, can.x, can.y, block+10);
- // cells of snake must be drawn individually
- context.fillStyle = 'yellow';
- snake.snakeBlocks.forEach((cell, index) => {
- // creates block effect
- context.fillRect(cell.x, cell.y, block-1, block-1);
- // can eaten by snake
- if (cell.x === can.x && cell.y === can.y) {
- snake.startSnakeBlocks++;
- // canvas is 720x720 which is 45x\45 blocks
- can.x = randNum(0, 45) * block;
- can.y = randNum(0, 45) * block;
- }
- // check if the cells of the snake are colliding with itself
- for (var i = index + 1; i < snake.snakeBlocks.length; i++) {
- // if the snake occupies same space as a body part then reset game
- if (cell.x === snake.snakeBlocks[i].x && cell.y === snake.snakeBlocks[i].y) {
- snake.x = 160;
- snake.y = 160;
- snake.snakeBlocks = [];
- snake.startSnakeBlocks = 6;
- snake.dx = block;
- snake.dy = 0;
- can.x = randNum(0, 25) * block;
- can.y = randNum(0, 25) * block;
- isGameOver = true;
- }
- }
- });
- }
- // listen to keyboard events to move the snake
- document.addEventListener('keydown', function(e) {
- // prevent snake from backtracking on itself by checking that it's
- //not already moving on the same axis (pressing left while moving
- // left won't do anything, and pressing right while moving left
- // shouldn't let you collide with your own body)
- //checks the direction of movement and dissallows backtracking
- // left arrow key
- if (e.which === 37 && snake.dx === 0) {
- snake.dx = -block;
- snake.dy = 0;
- }
- // up arrow key
- else if (e.which === 38 && snake.dy === 0) {
- snake.dy = -block;
- snake.dx = 0;
- }
- // right arrow key
- else if (e.which === 39 && snake.dx === 0) {
- snake.dx = block;
- snake.dy = 0;
- }
- // down arrow key
- else if (e.which === 40 && snake.dy === 0) {
- snake.dy = block;
- snake.dx = 0;
- }
- });
- // restart the game
- requestAnimationFrame(loop);
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment