Home Web Front-end JS Tutorial Implementing backgammon game based on JavaScript

Implementing backgammon game based on JavaScript

Jan 16, 2018 am 11:13 AM
javascript js backgammon

This article mainly introduces in detail the implementation of the backgammon game based on JavaScript. It has certain reference and value for learning JavaScript. Friends who are interested in JavaScript can refer to this article.

The example in this article shares the specific code for implementing backgammon in js for your reference. The specific content is as follows

Thinking:

##1 , first use canvas to draw the backgammon board

2. Get the position of the mouse click
3. Judge based on the position of the mouse click and draw the chess pieces
4. Judge whether you have won based on the chess pieces placed

Code:

<!DOCTYPE html> 
<html> 
<head lang="en"> 
 <meta charset="UTF-8"> 
 <title></title> 
 <style> 
  * { 
   padding: 0; 
   margin: 0; 
  } 
  canvas { 
   margin: 10px; 
   border: 2px solid #000; 
  } 
  #box { 
   display: inline-block; 
   position: absolute; 
   margin-top: 200px; 
   margin-left: 100px; 
  } 
  span { 
   font: 24px "微软雅黑"; 
   display: inline-block; 
   height: 50px; 
  } 
  input { 
   margin-top: 30px; 
   display: block; 
   width: 100px; 
   height: 50px; 
   font: 16px "微软雅黑"; 
   color: #fff; 
   background-color: #0099cc; 
  } 
 </style> 
</head> 
<body> 
<canvas width="640" height="640" id="cas"> 
 您的浏览器不支持canvas,请升级到最新的浏览器 
</canvas> 
<p id="box"> 
 <span id="txt"></span> 
 <input type="button" id="btn" value="重新开始"/> 
 
</p> 
 
<script> 
 var flag = true; //true代表白棋下的棋子,false代表黑棋下的棋子 
 var isWin = false; //判断是否结束,true结束,false没有结束 
 var step = 40; //设置每个格子的宽高都是40 
 
 var txt = document.getElementById("txt"); 
 var btn = document.getElementById("btn"); 
 var cas = document.getElementById("cas");// 获取画布对象 
 var ctx = cas.getContext("2d"); //画布上下文 
 
// 创建图片对象 
 var img_b = new Image(); 
 img_b.src = "imgs/b.png";//设置黑棋图片路径 
 var img_w = new Image(); 
 img_w.src = "imgs/w.png";//设置白棋图片路径 
 
// 用二维数组来保存棋盘,0代表没有走过,1为白棋走过,2为黑棋走过 
 var arr = new Array(15); //声明一个一维数组 
 for (var i = 0; i < 15; i++) { 
  arr[i] = new Array(15); //每个值再声明一个一维数组,这样就组成了一个二维数组 
  for (var j = 0; j < 15; j++) { 
   arr[i][j] = 0; 
  } 
 } 
 
 //绘制棋盘 
 function drawLine() { 
  for (var i = 0; i < cas.width / step; i++) { 
   // 画竖线 
   ctx.moveTo((i + 1) * step, 0); 
   ctx.lineTo((i + 1) * step, cas.height); 
   // 画横线 
   ctx.moveTo(0, (i + 1) * step); 
   ctx.lineTo(cas.width, (i + 1) * step); 
   ctx.stroke(); 
  } 
 } 
 //获取鼠标点击的位置 
 cas.onclick = function (e) { 
  // 先判断游戏是否结束 
  if (isWin) { 
   alert("游戏已经结束,请刷新重新开始!"); 
   return 0; 
  } 
  //判断棋子显示的地方,四条边上不显示棋子, 
  //鼠标点击的位置减去边框距离页面的上和左的距离(10),减去一个格子宽高的一半(20) 
  var x = (e.clientX - 10 - 20) / 40; 
  var y = (e.clientY - 10 - 20) / 40; 
 
  //进行取整来确定棋子最终显示的区域 
  x = parseInt(x); 
  y = parseInt(y); 
  //如果超出棋盘或者在棋盘边界直接返回,边界上不能画棋子 
  if(x < 0 || x >= 15 || y < 0 || y >= 15) { 
   return; 
  } 
  //进行判断该位置是否已经显示过棋子 
  if (arr[x][y] != 0) { 
   alert("你不能在这个位置下棋"); 
   return; 
  } 
  // 判断是显示黑子还是白子 
  if (flag) {//白子 
   flag = false; //将标志置为false,表示下次为黑子 
   drawChess(1, x, y); //调用函数来画棋子 
 
  } else {//黑子 
   flag = true; //将标志置为true,表示下次为白子 
   drawChess(2, x, y); //调用函数来画棋子 
 
  } 
 } 
 //画棋子 
 function drawChess(num, x, y) { 
  //根据x和y确定图片显示位置,让图片显示在十字线中间,因为一个格子为40,图片大小为30,所以40-30/2等于25,所以需要加上25 
  var x0 = x * step + 25; 
  var y0 = y * step + 25; 
  if (num == 1) { 
   //绘制白棋 
   ctx.drawImage(img_w, x0, y0); 
   arr[x][y] = 1; //白子 
  } else if (num == 2) { 
   // 绘制黑棋 
   ctx.drawImage(img_b, x0, y0); 
   arr[x][y] = 2; //黑子 
  } 
  //调用函数判断输赢 
  judge(num, x, y); 
 } 
 //判断输赢 
 function judge(num, x, y) { 
  var n1 = 0, //左右方向 
    n2 = 0, //上下方向 
    n3 = 0, //左上到右下方向 
    n4 = 0; // 右上到左下方向 
  //***************左右方向*************
  //先从点击的位置向左寻找,相同颜色的棋子n1自加,直到不是相同颜色的棋子,则跳出循环 
  for (var i = x; i >= 0; i--) { 
   if (arr[i][y] != num) { 
    break; 
   } 
   n1++; 
  } 
  //然后从点击的位置向右下一个位置寻找,相同颜色的棋子n1自加,直到不是相同颜色的棋子,则跳出循环 
  for (var i = x + 1; i < 15; i++) { 
   if (arr[i][y] != num) { 
    break; 
   } 
   n1++; 
  } 
  //****************上下方向************ 
  for (var i = y; i >= 0; i--) { 
   if (arr[x][i] != num) { 
    break; 
   } 
   n2++; 
  } 
  for (var i = y + 1; i < 15; i++) { 
   if (arr[x][i] != num) { 
    break; 
   } 
   n2++; 
  } 
  //****************左上到右下斜方向*********** 
  for(var i = x, j = y; i >=0, j >= 0; i--, j--) { 
   if (i < 0 || j < 0 || arr[i][j] != num) { 
    break; 
   } 
   n3++; 
  } 
  for(var i = x+1, j = y+1; i < 15, j < 15; i++, j++) { 
   if (i >= 15 || j >= 15 || arr[i][j] != num) { 
    break; 
   } 
   n3++; 
  } 
  //****************右上到左下斜方向*************
  for(var i = x, j = y; i >= 0, j < 15; i--, j++) { 
   if (i < 0 || j >= 15 || arr[i][j] != num) { 
    break; 
   } 
   n4++; 
  } 
  for(var i = x+1, j = y-1; i < 15, j >= 0; i++, j--) { 
   if (i >= 15 || j < 0 || arr[i][j] != num) { 
    break; 
   } 
   n4++; 
  } 
  //用一个定时器来延时,否则会先弹出对话框,然后才显示棋子 
  var str; 
  if (n1 >= 5 || n2 >= 5 || n3 >= 5 || n4 >= 5) { 
   if (num == 1) {//白棋 
    str = "白棋赢了,游戏结束!" 
   } else if (num == 2) {//黑棋 
    str = "黑棋赢了,游戏结束!" 
   } 
   txt.innerHTML = str; 
   isWin = true; 
  } 
 } 
 //重新开始 
 btn.onclick = function() { 
  flag = true; 
  isWin = false; 
 
  for (var i = 0; i < 15; i++) { 
   for (var j = 0; j < 15; j++) { 
    arr[i][j] = 0; 
   } 
  } 
  ctx.clearRect(0, 0, 640, 640); 
  txt.innerHTML = ""; 
  drawLine(); 
 } 
 drawLine(); 
</script> 
</body> 
</html>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study! !

Related recommendations:

Javascript uses rem to do responsive development example sharing

A brief discussion on the difference between Ajax and JavaScript

How to implement red envelope grabbing plug-in in Javascript web page

The above is the detailed content of Implementing backgammon game based on JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles