js練習--貪吃蛇(轉)

  最近一直在看javascript,但是發現不了動力。就開始想找動力,于是在網上找到了一個用js寫的貪吃蛇游戲。奈何還不會用git,就只能先這樣保存著。哈哈哈,這也算第一篇博客了,以后會堅持用自己的代碼寫博客的,下面的代碼是別人寫的,具體在哪找的我也忘了。。。by the way,寫一些小游戲真的是學習的動力啊,很有趣。

?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS貪吃蛇-練習</title>
<style type="text/css">
#pannel table {
border-collapse: collapse;
}
#pannel table td {
border: 1px solid #808080;
width: 10px;
height: 10px;
font-size: 0;
line-height: 0;
overflow: hidden;
}
#pannel table .snake {
background-color: green;
}
#pannel table .food {
background-color: blue;
}
</style>
<script type="text/javascript">
var Direction = new function () {
this.UP = 38;
this.RIGHT = 39;
this.DOWN = 40;
this.LEFT = 37;
};
var Common = new function () {
this.width = 20; /*水平方向方格數*/
this.height = 20; /*垂直方向方格數*/
this.speed = 250; /*速度 值越小越快*/
this.workThread = null;
};
var Main = new function () {
var control = new Control();
window.onload = function () {
control.Init("pannel");
/*開始按鈕*/
document.getElementById("btnStart").onclick = function () {
control.Start();
this.disabled = true;
document.getElementById("selSpeed").disabled = true;
document.getElementById("selSize").disabled = true;
};
/*調速度按鈕*/
document.getElementById("selSpeed").onchange = function () {
Common.speed = this.value;
}
/*調大小按鈕*/
document.getElementById("selSize").onchange = function () {
Common.width = this.value;
Common.height = this.value;
control.Init("pannel");
}
};
};
/*控制器*/
function Control() {
this.snake = new Snake();
this.food = new Food();
/*初始化函數,創建表格*/
this.Init = function (pid) {
var html = [];
html.push("<table>");
for (var y = 0; y < Common.height; y++) {
html.push("<tr>");
for (var x = 0; x < Common.width; x++) {
html.push('<td id="box_' + x + "_" + y + '">?</td>');
}
html.push("</tr>");
}
html.push("</table>");
this.pannel = document.getElementById(pid);
this.pannel.innerHTML = html.join("");
};
/*開始游戲 - 監聽鍵盤、創建食物、刷新界面線程*/
this.Start = function () {
var me = this;
this.MoveSnake = function (ev) {
var evt = window.event || ev;
me.snake.SetDir(evt.keyCode);
};
try {
document.attachEvent("onkeydown", this.MoveSnake);
} catch (e) {
document.addEventListener("keydown", this.MoveSnake, false);
}
this.food.Create();
Common.workThread = setInterval(function () {
me.snake.Eat(me.food); me.snake.Move();
}, Common.speed);
};
}
/*蛇*/
function Snake() {
this.isDone = false;
this.dir = Direction.RIGHT;
this.pos = new Array(new Position());
/*移動 - 擦除尾部,向前移動,判斷游戲結束(咬到自己或者移出邊界)*/
this.Move = function () {
document.getElementById("box_" + this.pos[0].X + "_" + this.pos[0].Y).className = "";
//所有 向前移動一步
for (var i = 0; i < this.pos.length - 1; i++) {
this.pos[i].X = this.pos[i + 1].X;
this.pos[i].Y = this.pos[i + 1].Y;
}
//重新設置頭的位置
var head = this.pos[this.pos.length - 1];
switch (this.dir) {
case Direction.UP:
head.Y--;
break;
case Direction.RIGHT:
head.X++;
break;
case Direction.DOWN:
head.Y++;
break;
case Direction.LEFT:
head.X--;
break;
}
this.pos[this.pos.length - 1] = head;
//遍歷畫蛇,同時判斷游戲結束
for (var i = 0; i < this.pos.length; i++) {
var isExits = false;
for (var j = i + 1; j < this.pos.length; j++)
if (this.pos[j].X == this.pos[i].X && this.pos[j].Y == this.pos[i].Y) {
isExits = true;
break;
}
if (isExits) { this.Over();/*咬自己*/ break; }
var obj = document.getElementById("box_" + this.pos[i].X + "_" + this.pos[i].Y);
if (obj) obj.className = "snake"; else { this.Over();/*移出邊界*/ break; }
}
this.isDone = true;
};
/*游戲結束*/
this.Over = function () {
clearInterval(Common.workThread);
alert("游戲結束!");
}
/*吃食物*/
this.Eat = function (food) {
var head = this.pos[this.pos.length - 1];
var isEat = false;
switch (this.dir) {
case Direction.UP:
if (head.X == food.pos.X && head.Y == food.pos.Y + 1) isEat = true;
break;
case Direction.RIGHT:
if (head.Y == food.pos.Y && head.X == food.pos.X - 1) isEat = true;
break;
case Direction.DOWN:
if (head.X == food.pos.X && head.Y == food.pos.Y - 1) isEat = true;
break;
case Direction.LEFT:
if (head.Y == food.pos.Y && head.X == food.pos.X + 1) isEat = true;
break;
}
if (isEat) {
this.pos[this.pos.length] = new Position(food.pos.X, food.pos.Y);
food.Create(this.pos);
}
};
/*控制移動方向*/
this.SetDir = function (dir) {
switch (dir) {
case Direction.UP:
if (this.isDone && this.dir != Direction.DOWN) { this.dir = dir; this.isDone = false; }
break;
case Direction.RIGHT:
if (this.isDone && this.dir != Direction.LEFT) { this.dir = dir; this.isDone = false; }
break;
case Direction.DOWN:
if (this.isDone && this.dir != Direction.UP) { this.dir = dir; this.isDone = false; }
break;
case Direction.LEFT:
if (this.isDone && this.dir != Direction.RIGHT) { this.dir = dir; this.isDone = false; }
break;
}
};
}
/*食物*/
function Food() {
this.pos = new Position();
/*創建食物 - 隨機位置創建立*/
this.Create = function (pos) {
document.getElementById("box_" + this.pos.X + "_" + this.pos.Y).className = "";
var x = 0, y = 0, isCover = false;
/*排除蛇的位置*/
do {
x = parseInt(Math.random() * (Common.width - 1));
y = parseInt(Math.random() * (Common.height - 1));
isCover = false;
if (pos instanceof Array) {
for (var i = 0; i < pos.length; i++) {
if (x == pos[i].X && y == pos[i].Y) {
isCover = true;
break;
}
}
}
} while (isCover);
this.pos = new Position(x, y);
document.getElementById("box_" + x + "_" + y).className = "food";
};
}
function Position(x, y) {
this.X = 0;
this.Y = 0;
if (arguments.length >= 1) this.X = x;
if (arguments.length >= 2) this.Y = y;
}
</script>
</head>
<body>
<div id="pannel" style="margin-bottom: 10px;"></div>
<select id="selSize">
<option value="20">20*20</option>
<option value="30">30*30</option>
<option value="40">40*40</option>
</select>
<select id="selSpeed">
<option value="500">速度-慢</option>
<option value="250" selected="selected">速度-中</option>
<option value="100">速度-快</option>
</select>
<input type="button" id="btnStart" value="開始" />
</body>
</html>

轉載于:https://www.cnblogs.com/ff1997/p/7416554.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391596.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391596.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391596.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

bzoj千題計劃169:bzoj2463: [中山市選2009]誰能贏呢?

http://www.lydsy.com/JudgeOnline/problem.php?id2463 n為偶數時&#xff0c;一定可以被若干個1*2 矩形覆蓋 先手每次從矩形的一端走向另一端&#xff0c;后手每次走向一個新的矩形 所以先手必勝 n為奇數時&#xff0c;先手走完一步后&#xff0c;剩下同n為偶數 所以先手必敗…

無監督學習-主成分分析和聚類分析

聚類分析&#xff08;cluster analysis&#xff09;是將一組研究對象分為相對同質的群組&#xff08;clusters&#xff09;的統計分析技術&#xff0c;即將觀測對象的群體按照相似性和相異性進行不同群組的劃分&#xff0c;劃分后每個群組內部各對象相似度很高&#xff0c;而不…

struts實現分頁_在TensorFlow中實現點Struts

struts實現分頁If you want to get started on 3D Object Detection and more specifically on Point Pillars, I have a series of posts written on it just for that purpose. Here’s the link. Also, going through the Point Pillars paper directly will be really help…

封裝jQuery下載文件組件

使用jQuery導出文檔文件 jQuery添加download組件 jQuery.download function(url, data, method){if( url && data ){data typeof data string ? data : paramEdit(data);     function paramEdit(obj){        var temStr "",tempStr"…

7.13. parallel - build and execute shell command lines from standard input in parallel

并行執行shell命令 $ sudo apt-get install parallel 例 7.5. parallel - build and execute shell command lines from standard input in parallel $ cat *.csv | parallel --pipe grep 13113 設置塊大小 $ cat *.csv | parallel --block 10M --pipe grep 131136688 原…

MySQL-InnoDB索引實現

聯合索引提高查詢效率的原理 MySQL會為InnoDB的每個表建立聚簇索引&#xff0c;如果表有索引會建立二級索引。聚簇索引以主鍵建立索引&#xff0c;如果沒有主鍵以表中的唯一鍵建立&#xff0c;唯一鍵也沒會以隱式的創建一個自增的列來建立。聚簇索引和二級索引都是一個b樹&…

Go語言-基本的http請求操作

Go發起GET請求 基本的GET請求 //基本的GET請求 package mainimport ("fmt""io/ioutil""net/http" )func main() {resp, err : http.Get("http://www.hao123.com")if err ! nil {fmt.Println(err)return}defer resp.Body.Close()body, …

釘釘設置jira機器人_這是當您機器學習JIRA票證時發生的事情

釘釘設置jira機器人For software developers, one of the most-debated and maybe even most-hated questions is “…and how long will it take?”. I’ve experienced those discussions myself, which oftentimes lacked precise information on the requirements. What I…

python的賦值與參數傳遞(python和linux切換)

1&#xff0c;python模式切回成linux模式------exit&#xff08;&#xff09; linux模式切換成python模式------python 2,在linux里運行python的復合語句&#xff08;得在linux創建.py文件&#xff09; touch le.py vim le.py----在le文件里輸入python語句 #!/usr/bin/python …

vscode 標準庫位置_如何在VSCode中使用標準

vscode 標準庫位置I use Visual Studio Code as my text editor. When I write JavaScript, I follow JavaScript Standard Style.Theres an easy way to integrate Standard in VS Code—with the vscode-standardjs plugin. I made a video for this some time ago if youre …

leetcode 1603. 設計停車系統

請你給一個停車場設計一個停車系統。停車場總共有三種不同大小的車位&#xff1a;大&#xff0c;中和小&#xff0c;每種尺寸分別有固定數目的車位。 請你實現 ParkingSystem 類&#xff1a; ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 類&#xf…

IBM量子計算新突破:成功構建50個量子比特原型機

本文來自AI新媒體量子位&#xff08;QbitAI&#xff09;IBM去年開始以云計算服務的形式提供量子計算能力。當時&#xff0c;IBM發布了包含5個量子比特的計算機。在短短18個月之后&#xff0c;IBM周五宣布&#xff0c;將發布包含20個量子比特的計算機。 IBM還宣布&#xff0c;該…

ChromeDriver與chrome對應關系

http://chromedriver.storage.googleapis.com/index.html 轉載于:https://www.cnblogs.com/gcgc/p/11387605.html

快速排序和快速選擇(quickSort and quickSelect)算法

排序算法&#xff1a;快速排序(quicksort)遞歸與非遞歸算法 TopK問題&#xff1a;快速選擇(quickSelect)算法 import java.util.*; import java.lang.*;public class Demo {// 非遞歸 using stackpublic static void quickSortStack(int[] nums, int left, int right) {if (lef…

小程序點擊地圖氣泡獲取氣泡_氣泡上的氣泡

小程序點擊地圖氣泡獲取氣泡Combining two colors that are two steps apart on the Color Wheel creates a Diad Color Harmony. This Color Harmony is one of the lesser used ones. I decided to cover it here to add variety to your options for colorizing visualizati…

leetcode 150. 逆波蘭表達式求值(棧)

根據 逆波蘭表示法&#xff0c;求表達式的值。 有效的算符包括 、-、*、/ 。每個運算對象可以是整數&#xff0c;也可以是另一個逆波蘭表達式。 說明&#xff1a; 整數除法只保留整數部分。 給定逆波蘭表達式總是有效的。換句話說&#xff0c;表達式總會得出有效數值且不存在…

WebLogic常見問題

myeclipseweblogic10的配置&#xff0c;配置成功 運行中可能失敗&#xff0c;由于weblogic10不穩定&#xff0c;重啟機器后可以使用了 web工程使用到hibernate3時可能出現問題 ClassNotFoundException: org.hibernate.hql.ast.HqlToken 參考http://blog.chinajavaworld.com/ent…

PopTheBubble —測量媒體偏差的產品創意

產品管理 (Product Management) A couple of months ago, I decided to try something new. The MVP Lab by Mozilla is an 8-week incubator for pre-startup teams to explore product concepts and, over the 8 weeks of the program, ship a minimum viable product that p…

linux-Centos7安裝nginx

首先配置linux環境&#xff0c;我這里是剛剛裝好linux&#xff0c;所以一次性安裝了一系列我需要到的環境&#xff1b; yum install pcre pcre-devel zlib zlib-devel openssl openssl-devel gd gd-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel e…

javascript原型_JavaScript原型初學者指南

javascript原型You cant get very far in JavaScript without dealing with objects. Theyre foundational to almost every aspect of the JavaScript programming language. In fact, learning how to create objects is probably one of the first things you studied when …