本文实例讲述了jQuery实现的五子棋游戏。分享给大家供大家参考。具体如下:
这是一款非常不错的代码,就是人工智能方面差了一点
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>五子棋</title> <style type="text/css"> div{margin:0;padding:0;} div.board{width:561px; height:561px; border:1px solid #ccc; margin:0 auto;} div.board div{ width:31px; height:31px; border:1px solid #ccc; float:left; cursor:pointer; background-repeat:no-repeat; } div.board .person { background-image:url('images/1/files/demo/white.jpg')} div.board .machine{ background-image:url('images/1/files/demo/black.jpg')} div.board .person_star{background-image:url('images/1/files/demo/white_star.jpg')} div.board .machine_star{background-image:url('images/1/files/demo/black_star.jpg')} input.ipt{ display:block; margin:0 auto; margin-top:8px;width:70px} </style> </head> <body> <div class='board' id='board'> </div> <input type='button' value='开始游戏' onclick="initGame(); this.value='重新开始'" class='ipt'/> <script type='text/javascript'> var TRANSVERSE = 16; var VERTICAL = 16; var LEFT = 1; var RIGHT = 2; var TOP = 3; var BOTTOM = 4; var LEFT_TOP = 5; var LEFT_BOTTOM = 6; var RIGHT_TOP = 7; var RIGHT_BOTTOM = 8; var Chess = function() { var owner = ''; var victory = false; this.getOwner = function(){return owner;}; this.setOwner = function(value){owner = value;}; this.getVictory = function(){ return victory;} this.setVictory = function(value){ victory = value; } } var Board = function() { var chessBoard = []; var isGameOver = false; this.getChess = function(point) { var x = point.x , y = point.y; return chessBoard[y][x]; } this.setChess = function(chess , point) { var x = point.x , y = point.y; chessBoard[y][x] = chess; } this.setVictory = function(points) { for(var i = 0 ; i < points.length ; i ++) { for(var j = 0 ; j < points[i].length; j ++) { var chess = this.getChess(points[i][j]); chess.setVictory(true); } } } this.getAvaiablePoints = function() { var avaiable = new Array; for(var y = 0 ; y <= VERTICAL ; y ++) { for(var x = 0 ; x <= TRANSVERSE ; x ++) { if(chessBoard[y][x]) continue; var point = {x : x , y : y}; avaiable.push(point); } } return avaiable; } this.getMap = function() { var map = {}; for(var y = 0 ; y <= VERTICAL ; y ++) { for(var x = 0 ; x <= TRANSVERSE ; x++) { var chess = chessBoard[y][x]; var value = ''; if(chess) { value = chess.getOwner(); if(chess.getVictory()) value += '_star'; } else { value = ''; } map[ x + ',' + y ] = value; } } return map; } this.gameOver = function() { return isGameOver = true; } this.isGameOver = function() { return isGameOver; } this.getNextPoint = function(point , direction) { var next = {x : point.x , y : point.y}; switch(direction) { case LEFT : next.x -= 1; break; case RIGHT: next.x += 1; break; case TOP: next.y -= 1; break; case BOTTOM: next.y += 1; break; case LEFT_TOP: next.x-= 1 , next.y-= 1; break; case RIGHT_TOP: next.x += 1 , next.y -= 1; break; case LEFT_BOTTOM: next.x -= 1 , next.y += 1; break; case RIGHT_BOTTOM: next.x += 1 , next.y += 1; break; default : alert('方向错误'); } return next; } var initialize = function() { for(var i = 0 ; i <= VERTICAL ; i++ ) chessBoard.push([]); } initialize(); } var Compute = function(role) { var directions = [LEFT , TOP , RIGHT , BOTTOM , LEFT_TOP , LEFT_BOTTOM , RIGHT_TOP , RIGHT_BOTTOM]; var score = 0; var self = this; this._computeScore = function(direction) { throw new Error('未实现'); } this._convertToPattern = function(chesslist) { return role.convertToPattern(chesslist) } this.compute = function(point) { score = 0; for(var i = 0, direction ; direction = directions[i++];) { score += this._computeScore(point , direction); } } this.getScore = function(refPoint) { return score ; } } var Five = function(role) { Compute.call(this, role); var computeScore1 = function(refPoint , direction) { var predefined = 'IIII'; var chesslist = role.find(refPoint , direction , 4); var pattern = role.convertToPattern(chesslist); if(predefined == pattern) return true; return false ; } var computeScore2 = function(refPoint , direction) { var prev = role.find(refPoint , direction , 2); var next = role.find(refPoint , role.reverseDirection(direction) , 2); var prevPattern = role.convertToPattern(prev); var nextPattern = role.convertToPattern(next); if(prevPattern == 'II' && nextPattern == 'II') return true; return false; } var computeScore3 = function(refPoint , direction) { var prev = role.find(refPoint , direction , 3); var next = role.find(refPoint , role.reverseDirection(direction) , 1); var prevPattern = role.convertToPattern(prev); var nextPattern = role.convertToPattern(next); if(prevPattern == 'III' && nextPattern == 'I') return true; return false; } this._computeScore = function(refPoint , direction) { if(computeScore1(refPoint , direction) || computeScore2(refPoint , direction) || computeScore3(refPoint , direction)) return 100000; else return 0; } } var Four_Live = function(role) { Compute.call(this, role); this._computeScore = function(refPoint , direction) { var score = 0; var prev = role.find(refPoint , direction , 4); var next = role.find(refPoint , role.reverseDirection(direction), 1); var prevPattern = this._convertToPattern(prev); var nextPattern = this._convertToPattern(next); if(prevPattern == 'III0' && nextPattern == '0') score = 10000; return score; } } var Four_Live1 = function(role) { Compute.call(this, role); this._computeScore = function(refPoint , direction) { var prev = role.find(refPoint , direction , 3); var next = role.find(refPoint , role.reverseDirection(direction) , 2); var prevPattern = this._convertToPattern(prev); var nextPattern = this._convertToPattern(next); if(prevPattern == 'II0' && nextPattern == 'I0') return 10000; else return 0; } } var Tree_Live = function(role) { Compute.call(this, role); this._computeScore = function(refPoint , direction) { var score = 0; var prev = role.find(refPoint , direction , 3); var next = role.find(refPoint , role.reverseDirection(direction), 2); var prevPattern = this._convertToPattern(prev); var nextPattern = this._convertToPattern(next); if(prevPattern == 'II0' && nextPattern == '00') score += 1000; return score; } } var Tree_Live1 = function(role) { Compute.call(this, role); this._computeScore = function(refPoint , direction) { var prev = role.find(refPoint , direction , 2); var next = role.find(refPoint , role.reverseDirection(direction), 3); var prevPattern = this._convertToPattern(prev); var nextPattern = this._convertToPattern(next); if(prevPattern == 'I0' && nextPattern == 'I00') return 1000 else return 0; } } var Two_Live = function(role) { Compute.call(this, role); this._computeScore = function(refPoint , direction) { var prev = role.find(refPoint , direction , 3); var next = role.find(refPoint , role.reverseDirection(direction), 2); var prevPattern = this._convertToPattern(prev); var nextPattern = this._convertToPattern(next); if(prevPattern == 'I00' && nextPattern == '00') return 100; else return 0; } } var One_Live = function(role) { Compute.call(this, role); this._computeScore = function(refPoint , direction) { var prev = role.find(refPoint , direction , 3); var next = role.find(refPoint , role.reverseDirection(direction), 3); var prevPattern = this._convertToPattern(prev); var nextPattern = this._convertToPattern(next); if(prevPattern == '000' && nextPattern == '000') return 10; else return 0; } } var Four_End = function(role) { Compute.call(this, role); this._computeScore = function(refPoint , direction) { var prev = role.find(refPoint , direction , 3); var next = role.find(refPoint , role.reverseDirection(direction), 1); var prevPattern = this._convertToPattern(prev); var nextPattern = this._convertToPattern(next); if(prevPattern == 'III' && nextPattern == '0') return 150; else return 0; } } var Role = function(board) { var computers = []; var self = this; var isVictory = false; this.isVictory = function() { return isVictory; } var getScore = function(point) { var score = 0; for(var i = 0 , computer; computer = computers[i++];) { computer.compute(point); score += computer.getScore(); } var result = {score: score , point : point}; return result; } var getScoreList = function() { var result = []; var avaiablePoints = board.getAvaiablePoints(); for(var i = 0 , point; point = avaiablePoints[i++];) { result.push(getScore(point)); } return result; } this.getCode = function() { throw new Error('未实现'); } this.getPeak = function() { var scoreInfo = getScoreList(); scoreInfo.sort(function(a,b){ return b.score - a.score ; }); return scoreInfo[0]; } this.convertToPattern = function(chesslist) { var pattern = ''; if(!chesslist) return ''; for(var i = 0 ; i < chesslist.length ; i ++) { var chess = chesslist[i]; if(chess == undefined) pattern += '0'; else if(chess.getOwner() == this.getCode()) pattern += 'I'; else pattern += 'Y'; } return pattern ; } this.reverseDirection = function(direction) { switch(direction) { case LEFT : return RIGHT; case RIGHT : return LEFT; case TOP : return BOTTOM; case BOTTOM : return TOP; case LEFT_TOP : return RIGHT_BOTTOM; case RIGHT_BOTTOM : return LEFT_TOP; case RIGHT_TOP : return LEFT_BOTTOM; case LEFT_BOTTOM : return RIGHT_TOP; default : alert('方向错误'); } } this._checkGameOver = function(point) { var leftRight = findVictory(point , LEFT); var topBottom = findVictory(point , TOP); var leftTopRightBottom = findVictory(point , LEFT_TOP); var rightTopLeftBottom = findVictory(point , RIGHT_TOP); var array = [leftRight , topBottom , leftTopRightBottom , rightTopLeftBottom]; var victory = []; for(var i = 0 ; i < array.length ; i ++) { if(array[i].length >= 5) victory.push(array[i]); } if(victory.length > 0) { board.gameOver(); board.setVictory(victory); isVictory = true; } if(board.getAvaiablePoints().length ==0) board.gameOver(); } var isLicitPoint = function(point) { return point.x >= 0 && point.y >= 0 && point.x <= TRANSVERSE && point.y <= VERTICAL && board.getChess(point) && board.getChess(point).getOwner() == self.getCode() } var findVictory = function(refPoint , direction) { var reverse = self.reverseDirection(direction); var result = []; var nextPoint ; var currPoint = {x: refPoint.x , y: refPoint.y}; while(true) { nextPoint = board.getNextPoint(currPoint, direction); if(!isLicitPoint(nextPoint)) break; currPoint = {x :nextPoint.x , y:nextPoint.y}; } while(true) { result.push(currPoint); nextPoint = board.getNextPoint(currPoint , reverse); if(!isLicitPoint(nextPoint)) break; currPoint = { x: nextPoint.x , y: nextPoint.y }; } return result; } this.find = function(point , direction , deep) { var refPoint = {x: point.x , y : point.y}; var result = new Array; var index = 1; var nextPoint; while(index <= deep) { nextPoint = board.getNextPoint(refPoint, direction); if(nextPoint.x < 0 || nextPoint.y < 0 || nextPoint.x > TRANSVERSE || nextPoint.y > VERTICAL) return null; var chess = board.getChess(nextPoint); if(chess) chess.point = {x:nextPoint.x , y:nextPoint.y}; result.push(chess); refPoint = nextPoint; index ++; } return result; } var initialize = function() { computers.push(new Five(self)); computers.push(new Four_Live(self)); computers.push(new Tree_Live(self)); computers.push(new Four_Live1(self)); computers.push(new Tree_Live1(self)); computers.push(new Two_Live(self)); computers.push(new One_Live(self)); computers.push(new Four_End(self)); } initialize(); } var Machine = function(board, rival) { Role.call(this, board); this.setChess = function() { if(board.isGameOver()) return; var myPeak = this.getPeak(); var rivalPeak = rival.getPeak(); var peak ; if(myPeak.score >= rivalPeak.score) peak = myPeak; else peak = rivalPeak; var chess = new Chess(); chess.setOwner(this.getCode()); board.setChess(chess, peak.point); this._checkGameOver(peak.point); } this.getCode = function(){return 'machine';} } var Person = function(board , rival) { Role.call(this, board); this.setChess = function(x,y) { if(board.isGameOver()) return; var point = new Object; point.x = x; point.y = y; var chess = new Chess() chess.setOwner(this.getCode()); board.setChess(chess, point); this._checkGameOver(point); } this.getCode = function(){ return 'person'; } } var UIBase = function() { var self = this; this._id = '$UI' + (++ UIBase.index); this._globalKey = ""; this.getHTML = function() { return ""; } var setGlobalKey = function() { var magic = '$UI_Items'; self._globalKey = 'window.'+magic+'.'+self._id; window[magic] = window[magic] || {}; window[magic][self._id] = self; } var formatHTML = function(html) { html = html.replace(/\$\$/g, self._globalKey); html = html.replace(/&&/g,self._id); return html; } var initUIBase = function() { setGlobalKey(); } this.renderHTML = function() { return formatHTML(this.getHTML()); } this.getDOM = function() { var dom = document.getElementById(this._id) return dom; } initUIBase(); } UIBase.index = 0; var ChessUI = function(board, placeholder) { UIBase.call(this); this.setChess = function(){} this.getHTML = function() { var html = ''; var map = board.getMap(); for(var key in map) { var onclick = ''; var className = map[key]; if(className == '') onclick='$$._setChess('+ key +')'; html += '<div onclick="'+ onclick +'" class="'+ className +'"></div>'; } return html; } this.draw = function() { var html = this.renderHTML(); document.getElementById(placeholder).innerHTML = html; } this._setChess = function(x,y) { this.setChess(x,y); } this.draw(); } function getMSIEVersion() { var regex = /MSIE([^;]+)/; var userAgent = navigator.userAgent; var result = regex.exec(userAgent); if(result) return parseInt(result[1]); } function initGame() { var version = getMSIEVersion(); if(version && version <= 8) { alert('请使用非IE浏览器(ie9、10除外)进行游戏(google chrome 、firefox等 )'); return; } var board = new Board(); var person = new Person(board); var machine = new Machine(board, person); var chessUI = new ChessUI(board, 'board'); chessUI.setChess = function(x,y) { person.setChess(x,y); machine.setChess(); chessUI.draw(); if(board.isGameOver()) { if(person.isVictory()) alert('您获得了胜利'); else if(machine.isVictory()) alert('机器获得了胜利'); else alert('游戏结束,胜负未分'); } } if(Math.floor(Math.random() * 10) % 2) { alert('机器执棋'); machine.setChess(); chessUI.draw(); } else { alert('您执棋'); } } </script> </body> </html>
希望本文所述对大家的jQuery程序设计有所帮助。

실제 세계에서 JavaScript의 응용 프로그램에는 서버 측 프로그래밍, 모바일 애플리케이션 개발 및 사물 인터넷 제어가 포함됩니다. 1. 서버 측 프로그래밍은 Node.js를 통해 실현되며 동시 요청 처리에 적합합니다. 2. 모바일 애플리케이션 개발은 재교육을 통해 수행되며 크로스 플랫폼 배포를 지원합니다. 3. Johnny-Five 라이브러리를 통한 IoT 장치 제어에 사용되며 하드웨어 상호 작용에 적합합니다.

일상적인 기술 도구를 사용하여 기능적 다중 테넌트 SaaS 응용 프로그램 (Edtech 앱)을 구축했으며 동일한 작업을 수행 할 수 있습니다. 먼저, 다중 테넌트 SaaS 응용 프로그램은 무엇입니까? 멀티 테넌트 SAAS 응용 프로그램은 노래에서 여러 고객에게 서비스를 제공 할 수 있습니다.

이 기사에서는 Contrim에 의해 확보 된 백엔드와의 프론트 엔드 통합을 보여 주며 Next.js를 사용하여 기능적인 Edtech SaaS 응용 프로그램을 구축합니다. Frontend는 UI 가시성을 제어하기 위해 사용자 권한을 가져오고 API가 역할 기반을 준수하도록합니다.

JavaScript는 현대 웹 개발의 핵심 언어이며 다양성과 유연성에 널리 사용됩니다. 1) 프론트 엔드 개발 : DOM 운영 및 최신 프레임 워크 (예 : React, Vue.js, Angular)를 통해 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축합니다. 2) 서버 측 개발 : Node.js는 비 차단 I/O 모델을 사용하여 높은 동시성 및 실시간 응용 프로그램을 처리합니다. 3) 모바일 및 데스크탑 애플리케이션 개발 : 크로스 플랫폼 개발은 개발 효율을 향상시키기 위해 반응 및 전자를 통해 실현됩니다.

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

Python은 데이터 과학 및 기계 학습에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명하며 데이터 분석 및 웹 개발에 적합합니다. 2. JavaScript는 프론트 엔드 개발의 핵심입니다. Node.js는 서버 측 프로그래밍을 지원하며 풀 스택 개발에 적합합니다.

JavaScript는 이미 최신 브라우저에 내장되어 있기 때문에 설치가 필요하지 않습니다. 시작하려면 텍스트 편집기와 브라우저 만 있으면됩니다. 1) 브라우저 환경에서 태그를 통해 HTML 파일을 포함하여 실행하십시오. 2) Node.js 환경에서 Node.js를 다운로드하고 설치 한 후 명령 줄을 통해 JavaScript 파일을 실행하십시오.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.
