使用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.pswp.cn/news/541814.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/541814.shtml
英文地址,請注明出處:http://en.pswp.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…