JavaScript:js实现在线五子棋人机(人人)对弈

2024-04-25 20:04

本文主要是介绍JavaScript:js实现在线五子棋人机(人人)对弈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在线五子棋人机对弈

全部使用前端技术,使用HTML,CSS以及JS进行实现.

棋盘在后端就是一个15*15的二维数组

页面设计

请添加图片描述

页面设计的比较粗糙

主要使用js自带的canvas画布进行绘画

HTML代码如下:

<div class="outer"><canvas id="canvas" height="900" width="900"></canvas><div class="button"><div id="reset"><button v-on:click="reset()">重试</button></div><!-- <div id="check"><button v-on:click="check()">开始</button></div> --><div id="jump"><button v-on:click="jump()">玩家本地对战</button></div></div>
</div>

CSS样式设计如下:

给canvas加了个居中和看上去像棋盘的颜色

按钮使用fixed布局跟随视口移动

#canvas {margin: 0 auto;display: block;margin: auto;background:burlywood ;border: 5px solid black;border-radius: 5px;
}.outer {background: grey;padding: 20px;
}.button{position: fixed;top: 100px;left: 100px;
}.button button{color: black;font-size: 20px;background-color:powderblue
}#reset{float: left;
}#check{float: left;margin-left: 10px;
}

JS代码如下:

简而言之:就是画了一堆横线和竖线

var canvas = document.getElementById("canvas");var ctx = canvas.getContext("2d");for (let index = 0; index <= 15; index += 1) {ctx.moveTo(0, 60 * index);ctx.lineTo(900, 60 * index);ctx.stroke()ctx.moveTo(60 * index, 0);ctx.lineTo(60 * index, 900);ctx.stroke()};

落子

效果如下

请添加图片描述

同样使用canvas进行绘画,代码如下

 canvas.addEventListener('click', e => {//获取坐标距离父级的偏移量var { offsetX, offsetY } = e;//边界判断 不能点击格子外面的范围if (offsetX < 30 || offsetY < 30 || offsetX > 870 || offsetY > 870) {return;} else if (flag === "black") {let x = Math.round(e.offsetX / 60) * 60;let y = Math.round(e.offsetY / 60) * 60;if (arr[y / 60][x / 60] != 0) {alert("此处已有棋子")return;}arr[y / 60][x / 60] = "black";ctx.fillStyle = '#000';ctx.beginPath();ctx.arc(x, y, 20, 0, 2 * Math.PI)ctx.fill();ctx.closePath();if (test()) {return;}// setTimeout(//     () => {//         clear(arrai);//         aitest();//         ai();//     }//     , 100);flag = "white"} else {let x = Math.round(e.offsetX / 60) * 60;let y = Math.round(e.offsetY / 60) * 60;if (arr[y / 60][x / 60] != 0) {alert("此处已有棋子")return;}arr[y / 60][x / 60] = "white";ctx.fillStyle = '#fff';ctx.beginPath();ctx.arc(x, y, 20, 0, 2 * Math.PI)ctx.fill();ctx.closePath();test();flag = "black";}});

给页面的鼠标点击绑了个监听事件.

画棋子也是依靠canvas实现

就是相当于先画一个圆,再往里面填颜色.

 ctx.fillStyle = '#000';ctx.beginPath();ctx.arc(x, y, 20, 0, 2 * Math.PI)ctx.fill();ctx.closePath();

判断输赢

js逻辑判断,代码如下

就是遍历棋盘,然后判断横向纵向以及斜向是否连成五子

 function test() {let countx = 1;for (let i = 0; i <= 14; i++) {for (let j = 0; j <= 14; j++) {if (arr[i][j] !== 0 && arr[i][j] === arr[i][j + 1]) {countx++;if (countx == 5) {alert(flag == "black" ? "黑棋获胜" : "白棋获胜");setTimeout(() => location.reload(), 1000);return true;}} else {countx = 1;}}}let county = 1;for (let j = 0; j <= 14; j++) {for (let i = 0; i <= 14; i++) {if (arr[i][j] !== 0 && arr[i][j] === arr[i + 1][j]) {county++;if (county == 5) {alert(flag == "black" ? "黑棋获胜" : "白棋获胜");setTimeout(() => location.reload(), 1000);return true;}} else {county = 1;}}}let countob = 1;let orii = 0;let orij = 0;for (let i = 0; i <= 14; i++) {for (let j = 0; j <= 14; j++) {if (arr[i][j] === arr[i + 1][j + 1]) {orii = i;orij = j;while (1 <= i <= 14 && j <= 14) {if (arr[i][j] === arr[i + 1][j + 1] && arr[i][j] !== 0) {countob++;// console.log(countob);i++;j++;if (countob == 5) {alert(flag == "black" ? "黑棋获胜" : "白棋获胜");setTimeout(() => location.reload(), 1000);return true;}} else {break;}}i = orii;j = orij;countob = 1;}}}let countob1 = 1;let orii1 = 0;let orij1 = 0;for (let i = 1; i <= 14; i++) {for (let j = 0; j <= 14; j++) {if (arr[i][j] === arr[i + 1][j - 1]) {orii = i;orij = j;while (i <= 14 && 1 <= j <= 14) {if (arr[i][j] === arr[i + 1][j - 1] && arr[i][j] !== 0) {countob1++;// console.log(countob);i++;j--;if (countob1 == 5) {alert(flag == "black" ? "黑棋获胜" : "白棋获胜");setTimeout(() => location.reload(), 1000);return true;}} else {break;}}i = orii;j = orij;countob1 = 1;}}}return false;}
到此为止,五子棋的人人对弈功能已经完全实现.

接下来是人机对弈

ai判断

逻辑就是算出棋盘上己方的最高分位置和对方的最高分位置,进行分数相加,最终的最高分位置就是最优位置.

js逻辑,代码如下:

遍历棋盘对所有位置的所有方向进行判断,得出得分

 function aitest() {let sum1 = 0;let sum2 = 0;for (let i = 0; i <= 14; i++) {for (let j = 0; j <= 14; j++) {sum1 += aitestx(i, j);sum1 += aitesty(i, j);sum1 += aitestobl(i, j);sum1 += aitestobr(i, j);flag = (flag == "black") ? "white" : "black";sum2 += aitestx(i, j);sum2 += aitesty(i, j);sum2 += aitestobl(i, j);sum2 += aitestobr(i, j);flag = (flag == "black") ? "white" : "black";arrai[i][j] = sum1 + sum2;console.log(arrai[i][j]);sum1 = 0;sum2 = 0;}}}
横向判断
function aitestx(x, y) {let temp = arr[x][y];let deadr = false;let deadl = false;let count = 1;for (let i = 1; i <= 5; i++) {if (y + i > 14) {deadr = true;break;}if (arr[x][y + i] != flag) {if (arr[x][y + i] != 0) {deadr = true;}break;} else {count++;}}for (let i = 1; i <= 5; i++) {if (y - i < 0) {deadl = true;break;}if (arr[x][y - i] != flag) {if (arr[x][y - i] != 0) {deadl = true;}break;} else {count++;}}if (deadl == true && deadr == true) {return 0;} else {if (count > 5) {count = 5;count = 5;}return (score(count, deadl == deadr ? false : true));}}
纵向判断
function aitesty(x, y) {let temp = arr[x][y];let deadr = false;let deadl = false;let count = 1;for (let i = 1; i <= 5; i++) {if (x + i > 14) {deadr = true;break;}if (arr[x + i][y] != flag) {if (arr[x + i][y] != 0) {deadr = true;}break;} else {count++;}}for (let i = 1; i <= 5; i++) {if (x - i < 0) {deadl = true;break;}if (arr[x - i][y] != flag) {if (arr[x - i][y] != 0) {deadl = true;}break;} else {count++;}}if (deadl == true && deadr == true) {return 0;} else {return (score(count, deadl == deadr ? false : true));}}
斜向判断
function aitestobl(x, y) {let temp = arr[x][y];let deadr = false;let deadl = false;let count = 1;for (let i = 1; i <= 5; i++) {if (x + i > 14 || y + i > 14) {deadr = true;break;}if (arr[x + i][y + i] != flag) {if (arr[x + i][y + i] != 0) {deadr = true;}break;} else {count++;}}for (let i = 1; i <= 5; i++) {if (x - i < 0 || y - i < 0) {deadl = true;break;}if (arr[x - i][y - i] != flag) {if (arr[x - i][y - i] != 0) {deadl = true;}break;} else {count++;}}if (deadl == true && deadr == true) {return 0;} else {return (score(count, deadl == deadr ? false : true));}}
反斜向判断
function aitestobr(x, y) {let temp = arr[x][y];let deadr = false;let deadl = false;let count = 1;for (let i = 1; i <= 5; i++) {if (x - i < 0 || y + i > 14) {deadr = true;break;}if (arr[x - i][y + i] != flag) {if (arr[x - i][y + i] != 0) {deadr = true;}break;} else {count++;}}for (let i = 1; i <= 5; i++) {if (x + i > 14 || y - i < 0) {deadl = true;break;}if (arr[x + i][y - i] != flag) {if (arr[x + i][y - i] != 0) {deadl = true;}break;} else {count++;}}if (deadl == true && deadr == true) {return 0;} else {return (score(count, deadl == deadr ? false : true));}}
根据上面方法得出的连子数调用方法算出得分返回给aitest()
function score(num, dead) {if (dead) {switch (num) {case 1:return 1;case 2:return 10;case 3:return 50;case 4:return 400;case 5:return 500000;}} else {switch (num) {case 1:return 5;case 2:return 30;case 3:return 250;case 4:return 10000;case 5:return 500000;}}}
当玩家落子时,调用回调函数settimeout()调用ai落子
setTimeout(() => {clear(arrai);aitest();ai();}, 100);flag = "white"
ai()落子函数

遍历棋盘,将分数和映射到另一个二维数组

如果发现此处已有棋子则递归调用本方法.

最后在相应位置完成落子

大功告成
 function ai() {let max = -1;let maxarr = new Array(-1, -1);for (let i = 1; i <= 14; i++) {for (let j = 1; j <= 14; j++) {if (max < arrai[i][j] && arr[i][j] == 0) {max = arrai[i][j];maxarr[0] = i;maxarr[1] = j;}}}console.log(maxarr);console.log(arr);if (arr[maxarr[0]][maxarr[1]] != 0) {arrai[maxarr[0]][maxarr[1]] = -1;ai();console.log("重新来过");return;}console.log("max:" + max);console.log("max数组:" + maxarr[0] + "  " + maxarr[1]);x = 60 * maxarr[1];y = 60 * maxarr[0];arr[maxarr[0]][maxarr[1]] = "white";ctx.fillStyle = '#fff';ctx.beginPath();ctx.arc(x, y, 20, 0, 2 * Math.PI)ctx.fill();ctx.closePath();test();flag = "black";clear(arrai);}

总结

一个不难的小游戏,逻辑存在一定漏洞,主要是对js也不熟悉,包括对var和let的理解等等都比较欠缺,以现在的知识储备应该是改不明白了,再多学点把这个做成线上人人对战.

这篇关于JavaScript:js实现在线五子棋人机(人人)对弈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/935662

相关文章

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

轻量级在线服装3D定制引擎Myway简介

我写的面向web元宇宙轻量级系列引擎中的另外一个,在线3D定制引擎Myway 3D。 用于在线商品定制,比如个性化服装的定制、日常用品(如杯子)、家装(被套)等物品的在线定制。 特性列表: 可更换衣服款式,按需定制更换模型可实时更改材质颜色可实时添加文本,并可实时修改大小、颜色和角度,支持自定义字体可实时添加艺术图标,并可实时修改大小、颜色和角度,支持翻转、各种对齐可更改衣服图案,按需求定制

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001