이 기사의 예에서는 JavaScript로 간단한 Tetris를 구현하는 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.
먼저 작업 렌더링을 살펴보겠습니다.
전체 예제 코드는 다음과 같습니다.
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>俄罗斯方块</title> <style type="text/css"> .c{margin:1px; width:19px; height:19px; background:red; position:absolute;} .d{margin:1px; width:19px; height:19px; background:gray; position:absolute;} .f{top:0px; left:0px; background:black; position:absolute;} .e{top:0px; background:#151515; position:absolute;} .g{width:100px; height:20px; color:white; position:absolute;} </style> <script type="text/javascript"> var row = 18; var col = 10; var announcement = 6; var size = 20; var isOver = false; var shapes = ("0,1,1,1,2,1,3,1;1,0,1,1,1,2,2,2;2,0,2,1,2,2,1,2;0,1,1,1,1,2,2,2;1,2,2,2,2,1,3,1;1,1,2,1,1,2,2,2;0,2,1,2,1,1,2,2").split(";"); var tetris; var container; function createElm(tag,css) { var elm = document.createElement(tag); elm.className = css; document.body.appendChild(elm); return elm; } function Tetris(css,x,y,shape) { // 创建4个div用来组合出各种方块 var myCss = css?css:"c"; this.divs = [createElm("div",myCss),createElm("div",myCss),createElm("div",myCss),createElm("div",myCss)]; if(!shape) { this.divs2 = [createElm("div",myCss),createElm("div",myCss),createElm("div",myCss),createElm("div",myCss)]; this.score = createElm("div","g"); this.score.style.top = 10*size+"px"; this.score.style.left = (col- -1)*size+"px"; this.score.innerHTML = "score:0"; } this.container = null; this.refresh = function() { this.x = (typeof(x)!='undefined')?x:3; this.y = (typeof(y)!='undefined')?y:0; // 如果有传参,优先使用参数的,如果有预告,优先使用预告,都没有就自己生成 if(shape) this.shape = shape; else if(this.shape2) this.shape = this.shape2; else this.shape = shape?shape:shapes[Math.floor((Math.random()*shapes.length-0.000000001))].split(","); this.shape2 = shapes[Math.floor((Math.random()*shapes.length-0.000000001))].split(","); if(this.container && !this.container.check(this.x,this.y,this.shape)) { isOver = true; alert("游戏结束"); } else { this.show(); this.showScore(); this.showAnnouncement(); } } // 显示方块 this.show = function() { for(var i in this.divs) { this.divs[i].style.top = (this.shape[i*2+1]- -this.y)*size+"px"; this.divs[i].style.left = (this.shape[i*2]- -this.x)*size+"px"; } } // 显示预告 this.showAnnouncement = function() { for(var i in this.divs2) { this.divs2[i].style.top = (this.shape2[i*2+1]- -1)*size+"px"; this.divs2[i].style.left = (this.shape2[i*2]- -1- -col)*size+"px"; } } // 显示分数 this.showScore = function() { if(this.container && this.score) { this.score.innerHTML = "score:" + this.container.score; } } // 水平移动方块的位置 this.hMove = function(step) { if(this.container.check(this.x- -step,this.y,this.shape)) { this.x += step; this.show(); } } // 垂直移动方块位置 this.vMove = function(step) { if(this.container.check(this.x,this.y- -step,this.shape)) { this.y += step; this.show(); } else { this.container.fixShape(this.x,this.y,this.shape); this.container.findFull(); this.refresh(); } } // 旋转方块 this.rotate = function() { var newShape = [this.shape[1],3-this.shape[0],this.shape[3],3-this.shape[2],this.shape[5],3-this.shape[4],this.shape[7],3-this.shape[6]]; if(this.container.check(this.x,this.y,newShape)) { this.shape = newShape; this.show(); } } this.refresh(); } function Container() { this.init = function() { // 绘制方块所在区域 var bgDiv = createElm("div","f"); bgDiv.style.width = size*col+"px"; bgDiv.style.height = size*row+"px"; // 绘制预告所在区域 var bgDiv = createElm("div","e"); bgDiv.style.left = size*col+"px"; bgDiv.style.width = size*announcement+"px"; bgDiv.style.height = size*row+"px"; // 清空积分 this.score = 0; } this.check = function(x,y,shape) { // 检查边界越界 var flag = false; var leftmost=col; var rightmost=0; var undermost=0; for(var i=0;i<8;i+=2) { // 记录最左边水平坐标 if(shape[i]<leftmost) leftmost = shape[i]; // 记录最右边水平坐标 if(shape[i]>rightmost) rightmost = shape[i]; // 记录最下边垂直坐标 if(shape[i+1]>undermost) undermost = shape[i+1]; // 判断是否碰撞 if(this[(shape[i+1]- -y)*100- -(shape[i]- -x)]) flag = true; } // 判断是否到达极限高度 for(var m=0;m<3;m++) for(var n=0;n<col;n++) if(this[m*100+n]) flag = true; if((rightmost- -x+1)>col || (leftmost- -x)<0 || (undermost- -y+1)>row || flag) return false; return true; } // 用灰色方块替换红色方块,并在容器中记录灰色方块的位置 this.fixShape = function(x,y,shape) { var t = new Tetris("d",x,y,shape); for(var i=0;i<8;i+=2) this[(shape[i+1]- -y)*100- -(shape[i]- -x)] = t.divs[i/2]; } // 遍历整个容器,判断是否可以消除 this.findFull = function() { var s = 0; for(var m=0;m<row;m++) { var count = 0; for(var n=0;n<col;n++) if(this[m*100+n]) count++; if(count==col) { s++; this.removeLine(m); } } this.score -= -this.calScore(s); } this.calScore = function(s) { if(s!=0) return s- -this.calScore(s-1) else return 0; } // 消除指定一行方块 this.removeLine = function(row) { // 移除一行方块 for(var n=0;n<col;n++) document.body.removeChild(this[row*100+n]); // 把所消除行上面所有的方块下移一行 for(var i=row;i>0;i--) { for(var j=0;j<col;j++) { this[i*100- -j] = this[(i-1)*100- -j] if(this[i*100- -j]) this[i*100- -j].style.top = i*size + "px"; } } } } function init() { container = new Container(); container.init(); tetris = new Tetris(); tetris.container = container; document.onkeydown = function(e) { if(isOver) return; var e = window.event?window.event:e; switch(e.keyCode) { case 38: //up tetris.rotate(); break; case 40: //down tetris.vMove(1); break; case 37: //left tetris.hMove(-1); break; case 39: //right tetris.hMove(1); break; } } setInterval("if(!isOver) tetris.vMove(1)",500); } </script> </head> <body onload="init()"> </body> </html>
더 많은 JavaScript 관련 콘텐츠에 관심이 있는 독자는 이 사이트의 특별 주제를 확인할 수 있습니다: "JavaScript 검색 알고리즘 기술 요약", "JavaScript 애니메이션 특수 효과 및 기술 요약 ", "JavaScript 오류 및 디버깅 기술 요약", "JavaScript 데이터 구조 및 알고리즘 기술 요약", "JavaScript 순회 알고리즘 및 기술 요약" 및 "JavaScript 수학 연산 사용법 요약》
이 기사가 JavaScript 프로그래밍에 종사하는 모든 사람에게 도움이 되기를 바랍니다.

Python과 JavaScript의 주요 차이점은 유형 시스템 및 응용 프로그램 시나리오입니다. 1. Python은 과학 컴퓨팅 및 데이터 분석에 적합한 동적 유형을 사용합니다. 2. JavaScript는 약한 유형을 채택하며 프론트 엔드 및 풀 스택 개발에 널리 사용됩니다. 두 사람은 비동기 프로그래밍 및 성능 최적화에서 고유 한 장점을 가지고 있으며 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

Python 또는 JavaScript를 선택할지 여부는 프로젝트 유형에 따라 다릅니다. 1) 데이터 과학 및 자동화 작업을 위해 Python을 선택하십시오. 2) 프론트 엔드 및 풀 스택 개발을 위해 JavaScript를 선택하십시오. Python은 데이터 처리 및 자동화 분야에서 강력한 라이브러리에 선호되는 반면 JavaScript는 웹 상호 작용 및 전체 스택 개발의 장점에 없어서는 안될 필수입니다.

파이썬과 자바 스크립트는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구와 개인 선호도에 따라 다릅니다. 1. Python은 간결한 구문으로 데이터 과학 및 백엔드 개발에 적합하지만 실행 속도가 느립니다. 2. JavaScript는 프론트 엔드 개발의 모든 곳에 있으며 강력한 비동기 프로그래밍 기능을 가지고 있습니다. node.js는 풀 스택 개발에 적합하지만 구문은 복잡하고 오류가 발생할 수 있습니다.

javaScriptisNotBuiltoncorc; it'SangretedLanguageThatrunsonOngineStenWrittenInc .1) javaScriptWasDesignEdasAlightweight, 해석 hanguageforwebbrowsers.2) Endinesevolvedfromsimpleplemporectreterstoccilpilers, 전기적으로 개선된다.

JavaScript는 프론트 엔드 및 백엔드 개발에 사용할 수 있습니다. 프론트 엔드는 DOM 작업을 통해 사용자 경험을 향상시키고 백엔드는 Node.js를 통해 서버 작업을 처리합니다. 1. 프론트 엔드 예 : 웹 페이지 텍스트의 내용을 변경하십시오. 2. 백엔드 예제 : node.js 서버를 만듭니다.

Python 또는 JavaScript는 경력 개발, 학습 곡선 및 생태계를 기반으로해야합니다. 1) 경력 개발 : Python은 데이터 과학 및 백엔드 개발에 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 적합합니다. 2) 학습 곡선 : Python 구문은 간결하며 초보자에게 적합합니다. JavaScript Syntax는 유연합니다. 3) 생태계 : Python에는 풍부한 과학 컴퓨팅 라이브러리가 있으며 JavaScript는 강력한 프론트 엔드 프레임 워크를 가지고 있습니다.

JavaScript 프레임 워크의 힘은 개발 단순화, 사용자 경험 및 응용 프로그램 성능을 향상시키는 데 있습니다. 프레임 워크를 선택할 때 : 1. 프로젝트 규모와 복잡성, 2. 팀 경험, 3. 생태계 및 커뮤니티 지원.

서론 나는 당신이 이상하다는 것을 알고 있습니다. JavaScript, C 및 Browser는 정확히 무엇을해야합니까? 그들은 관련이없는 것처럼 보이지만 실제로는 현대 웹 개발에서 매우 중요한 역할을합니다. 오늘 우리는이 세 가지 사이의 밀접한 관계에 대해 논의 할 것입니다. 이 기사를 통해 브라우저에서 JavaScript가 어떻게 실행되는지, 브라우저 엔진의 C 역할 및 웹 페이지의 렌더링 및 상호 작용을 유도하기 위해 함께 작동하는 방법을 알게됩니다. 우리는 모두 JavaScript와 브라우저의 관계를 알고 있습니다. JavaScript는 프론트 엔드 개발의 핵심 언어입니다. 브라우저에서 직접 실행되므로 웹 페이지를 생생하고 흥미롭게 만듭니다. 왜 Javascr


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

WebStorm Mac 버전
유용한 JavaScript 개발 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.