Создание игры в кости с использованием JavaScript

Опубликовано: 5 Января, 2022

Мы будем создавать проект игры в кости, используя HTML, CSS и JavaScript. Игра в кости основана на игре двух игроков. Оба игрока бросают кости, и игрок, набравший наибольшее значение фазы, выигрывает игру.

Изображения фаз игры в кости: Список изображений фаз игры в кости приведен ниже. Сохраните все изображения в папке, в которой вы сохраняете файлы HTML, CSS и JavaScript. Вы можете сохранить все файлы HTML, CSS и JavaScript отдельно и связать файлы CSS и JavaScript с файлом HTML или объединить все коды (HTML, CSS и JavaScript) в один файл и выполнить его.

  • Кости 1
  • Игральные кости 2
  • Кости 3
  • Игральные кости 4
  • Кости 5
  • Игральные кости 6

HTML-код: HTML-код используется для разработки базовой структуры проекта. Код HTML содержит класс контейнера, который содержит имя игрока и начальную фазу игры в кости. Другой нижний div содержит две кнопки (одна кнопка для броска кубика, а другая кнопка для переименования имени игрока).

<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" >
< title >Dice Game</ title >
</ head >
< body >
< div class = "container" >
< h1 >Let's Play</ h1 >
< div class = "dice" >
< p class = "Player1" >Player 1</ p >
< img class = "img1" src = "dice6.png" >
</ div >
< div class = "dice" >
< p class = "Player2" >Player 2</ p >
< img class = "img2" src = "dice6.png" >
</ div >
</ div >
< div class = "container bottom" >
< button type = "button" class = "butn"
onClick = "rollTheDice()" >
Roll the Dice
</ button >
</ div >
< div class = "container bottom" >
< button type = "button" class = "butn"
onClick = "editNames()" >
Edit Names
</ button >
</ div >
</ body >
</ html >

Код CSS: в этом разделе мы будем использовать некоторые свойства CSS для стилизации игры в кости.

<style>
.container {
width : 70% ;
margin : auto ;
text-align : center ;
}
.dice {
text-align : center ;
display : inline- block ;
margin : 10px ;
}
body {
background-color : #042f4b ;
margin : 0 ;
}
h 1 {
margin : 30px ;
font-family : "Lobster" , cursive ;
text-shadow : 5px 0 #232931 ;
font-size : 4.5 rem;
color : #4ecca3 ;
text-align : center ;
}
p {
font-size : 2 rem;
color : #4ecca3 ;
font-family : "Indie Flower" , cursive ;
}
img {
width : 100% ;
}
. bottom {
padding-top : 30px ;
}
.butn {
background : #4ecca3 ;
font-family : "Indie Flower" , cursive ;
border-radius: 7px ;
color : #ffff ;
font-size : 30px ;
padding : 16px 25px 16px 25px ;
text-decoration : none ;
}
.butn:hover {
background : #232931 ;
text-decoration : none ;
}
</style>

Код JavaScript: Код JavaScript содержит функции игры в кости. Первая функция - переименовать имя игрока после нажатия кнопки. Еще одна функция - бросить кости после нажатия кнопки. После броска кубиков обоими игроками выиграет любой игрок, получивший наибольшее значение фазы. Если оба игрока получат одинаковое значение фазы, игра будет проведена вничью.

<script>
// Player name
var player1 = "Player 1" ;
var player2 = "Player 2" ;
// Function to change the player name
function editNames() {
player1 = prompt( "Change Player1 name" );
player2 = prompt( "Change player2 name" );
document.querySelector( "p.Player1" ).innerHTML = player1;
document.querySelector( "p.Player2" ).innerHTML = player2;
}
// Function to roll the dice
function rollTheDice() {
setTimeout( function () {
var randomNumber1 = Math.floor(Math.random() * 6) + 1;
var randomNumber2 = Math.floor(Math.random() * 6) + 1;
document.querySelector( ".img1" ).setAttribute( "src" ,
"dice" + randomNumber1 + ".png" );
document.querySelector( ".img2" ).setAttribute( "src" ,
"dice" + randomNumber2 + ".png" );
if (randomNumber1 === randomNumber2) {
document.querySelector( "h1" ).innerHTML = "Draw!" ;
}
else if (randomNumber1 < randomNumber2) {
document.querySelector( "h1" ).innerHTML
= (player2 + " WINS!" );
}
else {
document.querySelector( "h1" ).innerHTML
= (player1 + " WINS!" );
}
}, 2500);
}
</script>

Полный код: объединив код трех вышеуказанных разделов (HTML, CSS и JavaScript), мы получим полную игру в кости.

<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content
= "width=device-width, initial-scale=1.0" >
< title >Dice Game</ title >
< style >
.container {
width: 70%;
margin: auto;
text-align: center;
}
.dice {
text-align: center;
display: inline-block;
margin: 10px;
}
body {
background-color: #042f4b;
margin: 0;
}
h1 {
margin: 30px;
font-family: "Lobster", cursive;
text-shadow: 5px 0 #232931;
font-size: 4.5rem;
color: #4ecca3;
text-align: center;
}
p {
font-size: 2rem;
color: #4ecca3;
font-family: "Indie Flower", cursive;
}
img {
width: 100%;
}
.bottom {
padding-top: 30px;
}
.butn {
background: #4ecca3;
font-family: "Indie Flower", cursive;
border-radius: 7px;
color: #ffff;
font-size: 30px;
padding: 16px 25px 16px 25px;
text-decoration: none;
}
.butn:hover {
background: #232931;
text-decoration: none;
}
</ style >
</ head >
< body >
< div class = "container" >
< h1 >Let's Play</ h1 >
< div class = "dice" >
< p class = "Player1" >Player 1</ p >
< img class = "img1" src = "dice6.png" >
</ div >
< div class = "dice" >
< p class = "Player2" >Player 2</ p >
< img class = "img2" src = "dice6.png" >
</ div >
</ div >
< div class = "container bottom" >
< button type = "button" class = "butn"
onClick = "rollTheDice()" >
Roll the Dice
</ button >
</ div >
< div class = "container bottom" >
< button type = "button" class = "butn"
onClick = "editNames()" >
Edit Names
</ button >
</ div >
< script >
// Player name
var player1 = "Player 1";
var player2 = "Player 2";
// Function to change the player name
function editNames() {
player1 = prompt("Change Player1 name");
player2 = prompt("Change player2 name");
document.querySelector("p.Player1")
.innerHTML = player1;
document.querySelector("p.Player2")
.innerHTML = player2;
}
// Function to roll the dice
function rollTheDice() {
setTimeout(function () {
var randomNumber1 = Math.floor(Math.random() * 6) + 1;
var randomNumber2 = Math.floor(Math.random() * 6) + 1;
document.querySelector(".img1").setAttribute("src",
"dice" + randomNumber1 + ".png");
document.querySelector(".img2").setAttribute("src",
"dice" + randomNumber2 + ".png");
if (randomNumber1 === randomNumber2) {
document.querySelector("h1").innerHTML = "Draw!";
}
else if (randomNumber1 < randomNumber2 ) {
document.querySelector("h1").innerHTML
= (player2 + " WINS!");
}
else {
document.querySelector("h1").innerHTML
= (player1 + " WINS!");
}
}, 2500);
}
</script>
</ body >
</ html >

Выход: