Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<link href="https://fonts.googleapis.com/css?family=Cabin+Sketch&display=swap" rel="stylesheet">
	<link href="https://emoji-css.afeld.me/emoji.css" rel="stylesheet">
	<title>Snake</title>
</head>

<div>
	<div class="wrapper">
		<header>
			<h1>Snake</h1>
		</header>

		<main>
			<section>
				<div class="game-wrapper">
					<div id="info" class="info">
						<span class="score"><i class="em em-mask" aria-role="presentation" aria-label="FACE WITH MEDICAL MASK"></i> Score : <span id="score">0</span></span>
						<span class="speed"><i class="em em-roll_of_paper" aria-role="presentation" aria-label="ROLL OF PAPER"></i> Speed : <span id="speed">1</span></span>
					</div>

					<div id="game" class="game">

						<!-- 			Snake Field			 -->

					</div>
				</div>

			</section>

			<aside>
				<button class="pause" id="pause"> Pause</button>
				<button class="play" id="play"> Play</button>
				<button class="new" id="new"> New Game</button>
			</aside>

		</main>

		<footer>
			<div class="copyrigth"> © 2020 <a href="https://twitter.com/TitiZavr" target="_blank">@Nihirashka</a>
			</div>

			<div class="share">
				<a href="#" id="vk" target="_blank">vk</a>
				<a href="#" id="fb" target="_blank">fb</a>
				<a href="#" id="tw" target="_blank">tw</a>
			</div>

		</footer>
	</div>
	</body>

</html>
              
            
!

CSS

              
                html {
	font-family: "Cabin Sketch", cursive;
	height: 100%;

	/* 	colors */
	--blue:  #b2dffb;
	--grass:  #fff;
	--green:  #d1f5d3;
	--purp:  #be8abf;
	--red:  #fea5ad;
}

body {
	height: 100%;
	background: #ddd;
}

.wrapper {
	heigth: 100%;
	display: flex;
	flex-direction: column;
	max_width: 1200px;
	margin: 0 auto;
}

header {
	width: 100%;
	background: #fff;
}

h1 {
	text-align: center;
	padding: 20px;
	font-size: 200%;
	font-weight: bold;
}

main {
	display: flex;
	flex: 2;
}

section, aside {
	min-height: 100px;
}

section {
	flex: 3;
	background: #fff;
	padding: 20px;
}

aside {
	flex: 2;
	background: var(--blue);
	padding: 20px;
}

aside button {
	font-family: cursive;
	border-radius: 100px;
	border: 0;
	padding: 0 20px;
	display: inline-block;
	margin: 0 20px 20px 0 ;
	background: #fff;
	font-size: 100%;
	cursor: pointer;
	box-shadow: 0 9px 18px rgba(0,0,0,0.2);
	transition: all 0.2s ease-in-out;
	height: 40px;
	line-height: 40px;
	outline: none;
}

aside button:hover {
	box-shadow: 0 3px 7px rgba(0,0,0,0.2);
}

aside button:active {
	box-shadow: 0 0 5px 2px rgba(0,0,0,0.25);
}

aside button.pause, 
aside button.play {
	display: none;
} 

.info {
	line-height: 30px;
	margin: 0 auto 30px;
	display: flex;
	justify-content: center;
	font-size: 100%;
	
& .score,
& .speed {
	display: inline-block;
	font-family: cursive;
	padding: 0 20px;
	background: var(--blue);
	border-radius: 4px;
	margin: auto 10px;
	border-radius: 100px;
	height: 40px;
	line-height: 40px;
	outline: none;
	
		i {
			padding: 3px 10px;
			border-radius: 4px;
			margin-right: 5px;
			color: #fff;
		}

		span {
			font-family: monospace;
			font-size: 150%;
		}
	}
	
	& .score {
		span {
			color: var(--purp);
		}
	}
	
	& .speed {
		span {
			color: var(--purp);
		}
	}
}

.game {
  width: auto;
  height: auto;
	margin: 0 auto;
  padding: 20px;
}

footer {
	background: #fff;
	padding: 20px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-weight: bold;
}

.copyrigth {
	opacity: 0.75;
}

.copyrigth a {
	color: var(--purp);
	margin-left: 20px;
}

.copyrigth a:before {
	content: "Author: ";
	text-decoration: none;
	display: inline-block;
	margin-right: 10px;
	color: black;
	opacity: 0.5;
}

.share a {
	display: inline-block;
	color: #fff;
	padding: 5px 10px;
	border-radius: 70px;
	margin: 0 0 0 10px;
	background: var(--purp);
}

.share::before {
	content: "Share:";
	font-weight: bold;
	opacity: 0.5;
}


// Game field elements

.field {
  display: flex;
  flex-wrap: wrap;
  margin: 0 auto;
  background: var(--green);
}

.cell {
  position: relative;
  display: block;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  border-style: inset;
  border: 1px solid rgba(255,255,255,0.1);
  background: rgba(0,0,0,0.1);
  
  &.snake {
    background: var(--blue);
  }
  
  &.food {
    background: var(--red);
  }
}

              
            
!

JS

              
                /**
 * Snake v0.1.0
 */

// set share btns urls
const shareBtns = function() {
	const currentPageLink = location.href;
	const vkEl = document.getElementById("vk");
	vkEl.setAttribute("href", `https://vk.com/share.php?url=${currentPageLink}`);

	const fbEl = document.getElementById("fb");
	fbEl.setAttribute(
		"href",
		`https://www.facebook.com/sharer/sharer.php?u=${currentPageLink}`
	);

	const twEl = document.getElementById("tw");
	twEl.setAttribute(
		"href",
		`http://twitter.com/share?text=WebSnake!&url=${currentPageLink}`
	);
};

const config = {
	initialLength: 10,
	stepDuration: 300,
	speedMult: 0.8,
	foodScore: 25,
	speedUpScoreN: 50,
	fieldWidth: 20,
	fieldHeight: 20,
	cellSize: 20
};

let gameStatus = "new"; // "new" | "play" | "stopped"
let score = 0;
let speed = 1;
let currentSpeedDuration = config.stepDuration;
let food = {};
let snake = [];
let snakeDirection = "right"; // "up" | "right" | "down" | "left"
let tickId = null;
let currentStepDuration = config.stepDuration;

// елементы DOM-дерева
const gameEl = document.getElementById("game");
const scoreEl = document.getElementById("score");
const speedEl = document.getElementById("speed");

const newGameEl = document.getElementById("new");
const playGameEl = document.getElementById("play");

const makeMapElement = (x, y) => {
	return { x: x, y: y };
};

// создание поля игры
function initField() {
	const fieldEl = document.createElement("div");
	fieldEl.classList.add("field");
	fieldEl.setAttribute(
		"style",
		`width: ${config.cellSize * config.fieldWidth}px; height: ${config.cellSize *
			config.fieldHeight}px;`
	);

	for (i = 0; i < config.fieldWidth; i++) {
		for (j = 0; j < config.fieldHeight; j++) {
			const cellEl = document.createElement("div");
			cellEl.classList.add("cell");
			cellEl.setAttribute("id", `${i}.${j}`);
			cellEl.setAttribute(
				"style",
				`width: ${config.cellSize}px; height: ${config.cellSize}px;`
			);
			fieldEl.append(cellEl);
		}
	}

	gameEl.innerHTML = "";
	gameEl.append(fieldEl);
}

// инициализация змейки
function initSnake() {
	const newSnake = [];

	const initialY = Math.floor(config.fieldHeight / 2);
	const initialX = 1;

	for (i = 0; i < config.initialLength; i++) {
		newSnake.push(makeMapElement(initialX + i, initialY));
	}

	snake = newSnake.slice().reverse();
	snakeDirection = "right";
}

// проверка координат на совпадение со змейкой
const checkIfOnSnake = coords => {
	for (i = 0; i < snake.length; i++) {
		const chunk = snake[i];
		if (coords.x === chunk.x && coords.y === chunk.y) {
			return true;
		}
	}
};

// создаем еду
function createFood() {
	let x;
	let y;
	let notOnSnake = true;
	while (notOnSnake) {
		x = Math.floor(Math.random() * config.fieldWidth);
		y = Math.floor(Math.random() * config.fieldHeight);
		notOnSnake = checkIfOnSnake(makeMapElement(x, y));
	}
	if (food !== {}) {
		clearFood();
	}

	food = makeMapElement(x, y);
	drawFood();
}

// удаление еды
function clearFood() {
	const foodCellEls = document.querySelectorAll("div.em-roll_of_paper");
	for (element of foodCellEls) {
		if (element) {
			element.classList.remove("em-roll_of_paper");
		}
	}
}

// рисование еды
function drawFood() {
	clearFood();
	const cellFoodEl = document.getElementById(`${food.y}.${food.x}`);
	if (cellFoodEl) {
		cellFoodEl.classList.add("em-roll_of_paper");
		cellFoodEl.classList.add("em");
	}
}

// стирание змейки
function clearSnake() {
	const snakeCellEls = document.querySelectorAll("div.em-mask");
	for (chunk of snakeCellEls) {
		if (chunk) {
			chunk.classList.remove("em-mask");
		}
	}
}

// рендеринг змейки
function drawSnake() {
	const drawingSnake = snake.slice();
	if (
		drawingSnake[0].x > config.fieldWidth ||
		drawingSnake[0].y > config.fieldHeight
	) {
		return false;
	}
	clearSnake();

	for (i = 0; i < drawingSnake.length; i++) {
		const x = drawingSnake[i].x;
		const y = drawingSnake[i].y;
		const snakeCellEl = document.getElementById(`${y}.${x}`);
		if (snakeCellEl) {
			snakeCellEl.classList.add("em");
			snakeCellEl.classList.add("em-mask");
		}
	}
}

// сдвиг змейки
function moveSnake() {
	let movedSnake = snake.slice();
	let head = Object.assign(movedSnake[0]);

	for (i = movedSnake.length - 1; i > 0; i--) {
		movedSnake[i].x = movedSnake[i - 1].x;
		movedSnake[i].y = movedSnake[i - 1].y;
	}

	switch (snakeDirection) {
		case "left":
			head.x--;
			break;
		case "right":
			head.x++;
			break;
		case "up":
			head.y--;
			break;
		default:
			head.y++;
	}

	movedSnake[0] = head;
	snake = movedSnake.slice();
}

// поедание еды
function eatFood() {
	score = score + config.foodScore;
	createFood();
	scoreEl.innerHTML = score;

	const tail = Object.assign(snake.slice().pop());
	moveSnake();
	const newSnake = snake.slice();
	newSnake.push(makeMapElement(tail.x, tail.y));
	snake = newSnake;

	if (score > 0 && score % config.speedUpScoreN === 0) {
		speed++;
		speedEl.innerHTML = speed;
		clearInterval(tickId);
		tickId = null;
		currentStepDuration = currentStepDuration * config.speedMult;
		tick();
	}
}

function isDead() {
	const head = snake.slice(0, 1)[0];
	const tail = snake.slice(3);

	const isWalls =
		head.x < 0 ||
		head.y < 0 ||
		head.x > config.fieldWidth - 1 ||
		head.y > config.fieldHeight - 1;

	let selfKill = false;

	tail.forEach(chunk => {
		if (head.x == chunk.x && head.y == chunk.y) selfKill = true;
	});

	return isWalls || selfKill;
}

function foodCollision() {
	const head = snake.slice(0, 1)[0];
	if (head.x == food.x && head.y == food.y) {
		eatFood();
	}
}

// очистка tick
function stopTick() {
	if (tickId) {
		clearInterval(tickId);
		tickId = null;
	}
}

// tick
function tick() {
	if (!tickId) {
		tickId = setInterval(() => {
			moveSnake();
			if (isDead()) {
				stopTick();
				alert("Collision");
				newGameEl.setAttribute("style", "display: block");
			} else {
				foodCollision();
				drawSnake();
			}
		}, currentStepDuration);
	}
}

// события клавиатуры
function setListeners() {
	newGameEl.addEventListener("click", event => {
		setDefaults();
		initField();
		initSnake();
		drawSnake();

		newGameEl.setAttribute("style", "display: none");
		playGameEl.setAttribute("style", "display: block");
	});

	playGameEl.addEventListener("click", event => {
		startGame();
		tick();
		playGameEl.setAttribute("style", "display: none");
	});

	document.addEventListener("keydown", event => {
		const keyCode = event.keyCode;
		const directions = {
			38: "up",
			87: "up",
			39: "right",
			68: "right",
			40: "down",
			83: "down",
			37: "left",
			65: "left"
		};

		if (directions[keyCode]) {
			event.preventDefault();
			if (canTurn(directions[keyCode])) {
				snakeDirection = directions[keyCode];
			}
		}
	});
}

// можно ли повернуть
function canTurn(direction) {
	if (snakeDirection === direction) {
		return false;
	}

	if (snakeDirection === "right") {
		if (direction === "left") {
			return false;
		}
	}

	if (snakeDirection === "left") {
		if (direction === "right") {
			return false;
		}
	}

	if (snakeDirection === "up") {
		if (direction === "down") {
			return false;
		}
	}

	if (snakeDirection === "down") {
		if (direction === "up") {
			return false;
		}
	}

	return true;
}

function setDefaults() {
	score = 0;
	speed = 1;
	currentSpeedDuration = config.stepDuration;
	food = [];
	snake = [];
	snakeDirection = "right";
	snakeChunksDirections = [];
	tickId = null;
	currentStepDuration = config.stepDuration;
	scoreEl.innerHTML = score;
	speedEl.innerHTML = speed;
}

function startGame() {
	setDefaults();
	initField();
	initSnake();
	drawSnake();
	createFood();
}

// Main function
const main = function() {
	shareBtns();

	initField();
	setListeners();
};

window.onload = main();

              
            
!
999px

Console