使用JavaScript的图像识别游戏

Today we are going to develop a fully functional image recognition game using JavaScript. JavaScript is the best fit choice since it is a web-based game. The game is totally based on event handling and event objects.

今天,我们将使用JavaScript开发功能全面的图像识别游戏 。 JavaScript是最适合的选择,因为它是基于Web的游戏。 游戏完全基于事件处理和事件对象

Code files

代码文件

1) battleship.js

1)Battleship.js

var view = {
displayMessage: function(msg) {
var messageArea = document.getElementById("messageArea");
messageArea.innerHTML = msg;
},
displayHit: function(location) {
var cell = document.getElementById(location);
cell.setAttribute("class", "hit");
},
displayMiss: function(location) {
var cell = document.getElementById(location);
cell.setAttribute("class", "miss");
}
}
var model = {
boardSize: 7,
numShips: 3,
shipsSunk: 0,
shipLength: 3,
generateShipLocations: function() {
var locations;
for (var i = 0; i < this.numShips; i++) {
do {
locations = this.generateShip();
} while (this.collision(locations));
this.ships[i].locations = locations;
}
},
generateShip: function() {
var direction = Math.floor(Math.random() * 2);
var row, col;
if (direction === 1) {
row = Math.floor(Math.random() * this.boardSize);
col = Math.floor(Math.random() * (this.boardSize - this.shipLength));
} else {
row = Math.floor(Math.random() * (this.boardSize - this.shipLength));
col = Math.floor(Math.random() * this.boardSize);
}
var newShipLocations = [];
for (var i = 0; i < this.shipLength; i++) {
if (direction === 1) {
newShipLocations.push(row + "" + (col + i));
} else {
newShipLocations.push((row + i) + "" + col);
}
}
return newShipLocations;
},
collision: function(locations) {
for (var i = 0; i < this.numShips; i++) {
var ship = model.ships[i];
for (var j = 0; j < locations.length; j++) {
if (ship.locations.indexOf(locations[j]) >= 0) {
return true;
}
}
}
return false;
},
ships: [{
locations: [0, 0, 0],
hits: ["", "", ""]
}, {
locations: [0, 0, 0],
hits: ["", "", ""]
}, {
locations: [0, 0, 0],
hits: ["", "", ""]
}],
fire: function(guess) {
for (var i = 0; i < this.numShips; i++) {
var ship = this.ships[i];
var index = ship.locations.indexOf(guess);
if (index >= 0) {
ship.hits[index] = "hit";
view.displayHit(guess);
view.displayMessage("HIT!");
if (this.isSunk(ship)) {
view.displayMessage("You sank my battleship!");
this.shipsSunk++;
}
return true;
}
}
view.displayMiss(guess);
view.displayMessage("You missed.");
return false;
},
isSunk: function(ship) {
for (var i = 0; i < this.shipLength; i++) {
if (ship.hits[i] !== "hit") {
return false;
}
}
return true;
}
};
// model.fire("53");
// model.fire("06");
function parseGuess(guess) {
var alphabet = ["A", "B", "C", "D", "E", "F", "G"];
if (guess === null || guess.length !== 2) {
alert("Oops, please enter a letter and a number on the board.");
} else {
firstChar = guess.charAt(0);
var row = alphabet.indexOf(firstChar);
var column = guess.charAt(1);
if (isNaN(row) || isNaN(column)) {
alert("Oops, that isn't on the board.");
} else if (row < 0 || row >= model.boardSize ||
column < 0 || column >= model.boardSize) {
alert("Oops, that's off the board!");
} else {
return row + column;
}
}
return null;
}
// console.log(parseGuess("C0"));
//  console.log(parseGuess("H0"));
var controller = {
guesses: 0,
processGuess: function(guess) {
var location = parseGuess(guess);
if (location) {
this.guesses++;
var hit = model.fire(location);
if (hit && model.shipsSunk === model.numShips) {
view.displayMessage("You sank all my battleships, in " +
this.guesses + " guesses");
}
}
}
};
function init() {
var fireButton = document.getElementById("fireButton");
fireButton.onclick = handleFireButton;
model.generateShipLocations();
}
function handleFireButton() {
var guessInput = document.getElementById("guessInput");
var guess = guessInput.value;
controller.processGuess(guess);
guessInput.value = "";
}
window.onload = init;

Download file (battleship.js)

下载文件(battleship.js)

2) game.html

2)game.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Battleship</title>
<style>
body {
background-color: black;
}
div#board {
position: relative;
width: 1024px;
height: 863px;
margin: auto;
background: url("board.png") no-repeat;
background-color: black;
}
.hit {
background: url("ship.png") no-repeat center center;
}
.miss {
background: url("miss.png") no-repeat center center;
}
div#messageArea {
position: absolute;
height: 20px;
width: 180px;
font-size: 30px;
top: 150px;
left: 500px;
color: rgb(83, 175, 19);
}
table {
position: absolute;
left: 8px;
top: 10px;
border-spacing: 0px;
}
td {
width: 46px;
height: 45px;
}
form {
position: absolute;
bottom: 200px;
right: 0px;
padding: 15px;
background-color: rgb(83, 175, 19);
}
form input {
background-color: rgb(152, 207, 113);
border-color: rgb(83, 175, 19);
font-size: 1em;
}
</style>
</head>
<body>
<div id="board">
<div id="messageArea"></div>
<table>
<tr>
<td id="00"></td>
<td id="01"></td>
<td id="02"></td>
<td id="03">
</td>
<td id="04"></td>
<td id="05"></td>
<td id="06"></td>
</tr>
<tr>
<td id="10"></td>
<td id="11"></td>
<td id="12"></td>
<td id="13"></td>
<td id="14"></td>
<td id="15"></td>
<td id="16"></td>
</tr>
<tr>
<td id="20"></td>
<td id="21"></td>
<td id="22"></td>
<td id="23"></td>
<td id="24"></td>
<td id="25"></td>
<td id="26"></td>
</tr>
<tr>
<td id="30"></td>
<td id="31"></td>
<td id="32"></td>
<td id="33"></td>
<td id="34"></td>
<td id="35"></td>
<td id="36"></td>
</tr>
<tr>
<td id="40"></td>
<td id="41"></td>
<td id="42"></td>
<td id="43"></td>
<td id="44"></td>
<td id="45"></td>
<td id="46"></td>
</tr>
<tr>
<td id="50"></td>
<td id="51"></td>
<td id="52"></td>
<td id="53"></td>
<td id="54"></td>
<td id="55"></td>
<td id="56"></td>
</tr>
<tr>
<td id="60"></td>
<td id="61"></td>
<td id="62"></td>
<td id="63"></td>
<td id="64"></td>
<td id="65"></td>
<td id="66"></td>
</tr>
</table>
<form>
<input type="text" id="guessInput" placeholder="A0">
<input type="button" id="fireButton" value="Fire!">
</form>
</div>
<script src="battleship.js"></script>
</body>
</html>

Download file (game.html)

下载文件(game.html)

Download project (Game_using_JavaScript)

下载项目(Game_using_JavaScript)

On running the above code you will see two blurred images. On clicking on them the unblurred version of the same image is displayed. So first the user has to make a guess about the image and then he/she can click on the image to reveal answer i.e. to see the unblurred version of the image.

运行上述代码后,您将看到两个模糊的图像。 单击它们后,将显示同一图像的未模糊版本。 因此,首先用户必须对图像进行猜测,然后他/她可以单击图像以显示答案,即查看图像的未模糊版本。

The logic behind the magic:

魔术背后的逻辑:

First, in line number 9 all the HTML image tags are accessed by document.getElementbyTagName which returns an array of DOM objects. Each element of this array represents a unique image tag. Onclick event of each DOM object in the array has been assigned the showanswer event handler.

首先,在第9行中,所有HTML图像标签都由document.getElementbyTagName访问,该文档返回DOM对象的数组。 该数组的每个元素代表一个唯一的图像标签。 已为数组中每个DOM对象的Onclick事件分配了showanswer事件处理程序。

Now after that, you can see that showanswer is nothing but a simple function in which an event object is being passed. The event object contains usual information about the event. Like here its target property is a DOM object representing the HTML element on which event has occurred.

现在,您可以看到showanswer只是一个简单的函数,其中传递了事件对象。 事件对象包含有关事件的常规信息。 像这里一样,它的目标属性是一个DOM对象,表示发生事件HTML元素。

Pay attention:

请注意:

The image object has a number of properties through which many attributes of the corresponding HTML element can be accessed directly. Like here we have used id and then src properties to change the image to the unblurred version on the occurrence of the click event.

图像对象具有许多属性,通过它们可以直接访问相应HTML元素的许多属性。 像这里一样,我们使用id和src属性在发生click事件时将图像更改为未模糊的版本。

You must have noticed that unblurred image stays there for just a moment and then again the blurred image is displayed. This is because of the setTimeout function. It is an inbuilt function in JS.

您必须已经注意到未模糊的图像在此处停留了片刻,然后再次显示了模糊的图像。 这是因为有setTimeout函数。 它是JS中的内置函数。

Line number 20 effectively means that after 2000ms of invoking of showanswer function , another function reblur will be called and the image will be passed as an argument to reblur function.

第20行有效地表示在调用showanswer函数2000ms之后,将调用另一个函数reblur ,并且图像将作为参数传递给reblur函数。

In reblur function, in a similar manner as in showanswer function the image is changed back to blur image via image object that was passed in it.

在reblur功能,以类似的方式,如showanswer功能的图像被改变回经由在它通过图像对象模糊图像。

翻译自: https://www.includehelp.com/code-snippets/image-recognition-game-using-javascript.aspx

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/541814.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php 判断 in,tinkphp常用判断条件in、notin、between、AND、OR

越来越多的人使用thinkphp框架开发应用&#xff0c;容易上手开发周期短&#xff0c;接下来吾爱编程为大家分享一下tinkphp常用判断条件in、notin、between、AND、OR&#xff0c;有需要的小伙伴可以参考一下&#xff1a;in&#xff1a;{in name"Think.get.level" valu…

关于设置不同linux主机之间ssh免密登录简易方法

2019独角兽企业重金招聘Python工程师标准>>> 在linux日常中&#xff0c;经常会有ssh链接其他主机服务器的action,也学习过大家日常用配置ssh免密登录的方法。 小编今天在这里给大家介绍一种比较简单的配置linux主机ssh免密登录的方法。 两台主机的IP地址&#xff1a…

c语言指针++_C ++此指针| 查找输出程序| 套装1

c语言指针Program 1: 程序1&#xff1a; #include <iostream>using namespace std;int main(){int A 10;this* ptr;ptr &A;*ptr 0;cout << *ptr << endl;return 0;}Output: 输出&#xff1a; main.cpp: In function ‘int main()’:main.cpp:7:5: e…

java自定义线程池池,线程池使用及自定义线程池

一 案例引申编写代码同时只允许五个线程并发访问(以下文的函数为例子)private static void method() {System.out.println("ThreadName" Thread.currentThread().getName() "进来了");Thread.sleep(2000);System.out.println("ThreadName" Th…

long类型20位示例_Java Long类reverseBytes()方法与示例

long类型20位示例长类reverseBytes()方法 (Long class reverseBytes() method) reverseBytes() method is available in java.lang package. reverseBytes()方法在java.lang包中可用。 reverseBytes() method is used to returns the value generated by reversing the order o…

impala和mysql语法,impala CREATE TABLE语句

CREATE TABLE语句用于在Impala中的所需数据库中创建新表。 创建基本表涉及命名表并定义其列和每列的数据类型。语法以下是CREATE TABLE语句的语法。 这里&#xff0c;IF NOT EXISTS是一个可选的子句。 如果使用此子句&#xff0c;则只有在指定数据库中没有具有相同名称的现有表…

Guava翻译系列之EventBus

EventBus 类解析 当我们开发软件时&#xff0c;各个对象之间的数据共享和合作是必须的。 但是这里比较难做的是 怎样保证消息之间的传输高效并且减少各个模块之间的耦合。 当组件的职责不清楚时&#xff0c;一个组件还要承担另一个组件的职责&#xff0c;这样的系统我们就认为是…

Java PipedOutputStream close()方法与示例

PipedOutputStream类close()方法 (PipedOutputStream Class close() method) close() method is available in java.io package. close()方法在java.io包中可用。 close() method is used to close this PipedOutputStream and free all system resources linked with this str…

Java二维数组谷电,java二维数组遍历的2种代码

二维数组遍历&#xff1a;思想&#xff1a;1.先将二维数组中所有的元素拿到2.再将二维数组中每个元素进行遍历&#xff0c;相当于就是在遍历一个一维数组第一种方法&#xff1a;双重for循环//遍历二维数组public class Traverse_a_two_dimensional_array {public static void m…

【转】MyEclipse快捷键大全

常用快捷键 -------------------------------------MyEclipse 快捷键1(CTRL)-------------------------------------Ctrl1 快速修复CtrlD: 删除当前行 CtrlQ 定位到最后编辑的地方 CtrlL 定位在某行 CtrlO 快速显示 OutLine CtrlT 快速显示当前类的继承结构 CtrlW 关闭当…

Java整数类的compareTo()方法和示例

整数类compareTo()方法 (Integer class compareTo() method) compareTo() method is available in java.lang package. compareTo()方法在java.lang包中可用。 compareTo() method is used to check equality or inequality for this Integer object against the given Integer…

MATLAB元胞自动机报告,元胞自动机概述与MATLAB实现

什么是元胞自动机&#xff1f;元胞自动机(cellular automata&#xff0c;CA) 是一种时间、空间、状态都离散&#xff0c;空间相互作用和时间因果关系为局部的网格动力学模型&#xff0c;具有模拟复杂系统时空演化过程的能力。它能构建随时间推移发生状态转移的系统&#xff0c;…

python(33)多进程和多线程的区别

多线程可以共享全局变量&#xff0c;多进程不能。多线程中&#xff0c;所有子线程的进程号相同&#xff1b;多进程中&#xff0c;不同的子进程进程号不同。 #!/usr/bin/python # -*- coding:utf-8 -*- import os import threading import multiprocessing count_thread 0 coun…

Java FilterInputStream reset()方法与示例

FilterInputStream类的reset()方法 (FilterInputStream Class reset() method) reset() method is available in java.io package. reset()方法在java.io包中可用。 reset() method is used to reset this FilterInputStream to the position set by the most recent call of m…

不同php文件,php-不同文件夹的不同登录(会话)

我有一个Web服务,需要用户登录并创建标准$_SESSION [‘XXX’]个用户变量.我想为应用程序创建一个“演示”,因此为它创建了另一个文件夹.相同的代码在那里,除了数据库以外的所有东西.问题是,当用户登录这两个帐户之一时,它可以访问两个帐户.因此,如果他登录了演示应用程序,它将使…

Java Hashtable containsValue()方法与示例

哈希表类containsValue()方法 (Hashtable Class containsValue() method) containsValue() method is available in java.util package. containsValue()方法在java.util包中可用。 containsValue() method is used to check whether this table Hashtable associated one or m…

php session redis db,php session redis 配置

具体环境&#xff1a;一台apachephp的服务器(yum安装remi源及配置 httpd-2.2.15 php-5.4.45)一台redis服务器(yum安装remi源及配置 redis-3.2.6)保证apache服务器可以访问redis服务器的6379端口具体步骤&#xff1a;1、在apachephp服务器上安装redis扩展点击(此处)折叠或打开yu…

sigprocmask, sigpending, sigsuspend的用法

sigset_t set sigemptyset(&set) :清空阻塞信号集合变量 sigfillset(&set) &#xff1a;添加所有的信号到阻塞集合变量里 sigaddset(&set,SIGINT):添加单一信号到阻塞信号集合变量 sigdelset(&set,SIGINT):从阻塞信号集合变量中删除单一信号 void handler(int …

Java Calendar getDisplayName()方法与示例

日历类的getDisplayName()方法 (Calendar Class getDisplayName() method) getDisplayName() method is available in java.util package. getDisplayName()方法在java.util包中可用。 getDisplayName() method is used to return string denotation of the given calendar fie…

matlab dir数,DIR - matlab函数

DIR List directory.DIR directory_name lists the files in a directory. Pathnames andwildcards may be used. For example, DIR *.m lists all the M-filesin the current directory.D DIR(‘directory_name‘) returns the results in an M-by-1structure with the field…