首页 > 编程语言 >Building a Dice Game using JavaScript Javascript构建一个dice game 项目

Building a Dice Game using JavaScript Javascript构建一个dice game 项目

时间:2023-06-27 14:57:30浏览次数:72  
标签:Building Dice button Javascript div document class dice

We will be building a Dice Game Project using HTML, CSS, and JavaScript. The Dice Game is based on a two-player. Both players roll the dice and the player who gets the highest phase value will win the game.

Images of Dice Phases: The list of dice phases images are given below. Save all the images in a folder where you save your HTML, CSS, and JavaScript files. You can save all HTML, CSS, and JavaScript files separately and link CSS and JavaScript files to the HTML file or combine all codes (HTML, CSS and JavaScript) in a single file and execute it.

 

HTML Code: HTML code is used to design the basic structure of the project. The HTML code contains the container class that holds the player’s name and initial dice phase. Another bottom div contains the two buttons (one button for roll the dice and another button for rename the player name).

 
<!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 Code: In this section, we will use some CSS property to style the Dice Game.

     
<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>

JavaScript Code: The JavaScript code contains the functionality of Dice Game. The first functionality is to rename the player name after clicking the button. Another functionality is to roll the dice after clicking the button. After rolling the dice by both the player, anyone player will win who get the highest phase value. If both players get the same phase value then the game will draw.

 
       // 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);     }

Complete Code: After combining the above three sections (HTML, CSS, and JavaScript) code, we will get the complete Dice Game.

 
<!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 {                          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>

Output:

标签:Building,Dice,button,Javascript,div,document,class,dice
From: https://www.cnblogs.com/weifeng1463/p/17508854.html

相关文章

  • Selenium基础:cookie javascript调用 屏幕截图 09
    1、cookie操作 绕过登录get_cookies():以字典形式返回cookie所有信息get_cookies(name):返回cookie字典中key为name的值add_cookie(cookie_dict):手动添加cookie。cookie_dict为字典数据格式,cookie_dict中必须有name和value值delete_cookie(name):删除cookie字典中key为name的......
  • Excel JavaScript API for PivotTables
    WorkwithPivotTablesusingtheExcelJavaScriptAPI-OfficeAdd-ins|MicrosoftLearnPivotTablesstreamlinelargerdatasets.Theyallowthequickmanipulationofgroupeddata.TheExcelJavaScriptAPIletsyouradd-increatePivotTablesandinteractw......
  • Design a Drum-kit web app using JavaScript Javascript设计drum-kit项目
    Weallmusthaveseenadrumkitinsomeconcertorelsewhere,itisacollectionofdrums,cymbalsandotherpercussioninstruments.Buthaveyoueverimaginedmakingthatdrumkitonyourownvirtuallywiththehelpofsomescriptinglanguage?Well,so......
  • javascript连接MySQL
    varmysql =require('mysql');varconnection=mysql.createConnection({  host  :'localhost',  user  :'root',  password:'password',  port:'3306',  database:'nufix'});connecti......
  • JavaScript Framework Unpoly 框架介绍
    作为一种创建Web应用程序的更直接的方式,无需使用太多JavaScript,HTML在线技术一直在蓬勃发展。它的工作原理是通过网络发送HTML,而不是JSON。现在,一种名为Unpoly的新JavaScript框架已经成为Basecamp的HTML在线框架Hotwire的竞争者。Unpoly承诺“为服务器渲染的H......
  • JavaScript 一些简写代码的例子
    在使用UglifyJS对javascript进行压缩和美化时,我在其中发现了一些关于ifelse的语法简写,顺便说说平时有哪些JavaScript代码可以进行简写,同时不会影响可读性和性能。javascript简写(JavaScriptshorthand)是每一个javascript开发者必须掌握的技术,最少的代码获得最大的性能! 1.判断......
  • javascript:return confirm('您确定要删除吗?')
    javascript:returnconfirm('您确定要删除吗?')οnclick="javascript:returnconfirm('您确定要删除吗?')" 用在<a>和<input>标签里都可以 例如:<ahref="?id=XXX"οnclick="javascript:returnconfirm('您确定要删除该条数据吗?')"......
  • 【JavaScript】将用户复制的转码后网页链接进行解码
    decodeURIComponent()方法用于解码由encodeURIComponent方法或者其他类似方法编码的部分统一资源标识符(URI)。decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");//"JavaScript_шеллы"......
  • JavaScript 常用 API 集合
     一、节点1.1节点属性Node.nodeName//返回节点名称,只读Node.nodeType//返回节点类型的常数值,只读Node.nodeValue//返回Text或Comment节点的文本值,只读Node.textContent//返回当前节点和它的所有后代节点的文本内容,可读写Node.baseURI//返回当前网页的绝对路径......
  • JavaScript http大文件断点续传上传
    ​ 以ASP.NETCoreWebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API,包括文件的上传和下载。 准备文件上传的API #region 文件上传  可以带参数        [HttpPost("upload")]        publicJsonResultuploadProject(I......