代码实现ts:
1 'use strict'
module Main { const FloorType = {
space: "space",
snack: "body",
food: "food"
}
const enum Direction {
left = 37,
up = 38,
right = 39,
down = 40
}
interface Block {
pos: Pos
type: string
node: HTMLElement }
interface Pos {
x: number
y: number
}
let score: number = 0;
export class FLoor { private table: HTMLTableElement
public row: number
public col: number
public blocks: Block[]
private parent: HTMLElement
constructor(options?) {
console.log(options);
options = options || {};
this.table = document.createElement("table");
this.parent = options.parent || document.body;
this.row = options.row || 20;
this.col = options.col || 20;
this.blocks = [];
}
DrawFloor() { for (let i = 0; i < this.row; i++) {
let tr = <HTMLTableRowElement>this.table.insertRow(-1);
for (let k = 0; k < this.col; k++) {
let td = <HTMLTableCellElement>tr.insertCell(-1);
td.className = FloorType.space;
let block: Block = {
pos: { x: k, y: i },
type: FloorType.space,
node: td
}
this.blocks.push(block);
}
}
this.parent.appendChild(this.table); }
DrawGameOver() {
let div = document.createElement("div");
div.className = "gameover";
div.innerHTML = "Game Over score:" + score;
div.style.top = this.row * 20 / 2 - 50 + "px";
div.style.left = this.row * 20 / 2 - 100 + "px";
this.parent.appendChild(div); } ReDraw(blocks: Block[]) { blocks.forEach((block) => { block.node.className = block.type })
}
}
export class Snack { private len: number;
private speed: number;
private bodies: Block[];
private direction: Direction;
private floor: FLoor;
private timer?: number;
constructor(floor: FLoor, options?) {
options = options || {};
this.len = options.len || 3;
this.speed = options.speed || 60;
this.direction = options.direction || Direction.right;
this.floor = options.floor || floor;
this.bodies = [];
}
DrawSnack() { let setDirection = (e: KeyboardEvent): void => {
const keycode = e.keyCode;
switch (keycode) {
case Direction.left:
if (this.direction !== Direction.right) {
this.direction = Direction.left;
}
break; case Direction.right:
if (this.direction !== Direction.left) {
this.direction = Direction.right;
}
break;
case Direction.up:
if (this.direction !== Direction.down) {
this.direction = Direction.up;
}
break;
case Direction.down:
if (this.direction !== Direction.up) {
this.direction = Direction.down;
}
break;
}
}
document.addEventListener('keydown', setDirection, false);
for (let i = 0; i < this.len; i++) {
this.bodies.push(this.floor.blocks[i]);
}
this.RandFood();
this.bodies.forEach((block) => { block.type = FloorType.snack });
this.floor.ReDraw(this.bodies);
this.timer = setInterval(() => { this.Move() }, this.speed);
}
RandFood() { let p: Pos = {
x: Math.ceil(this.floor.col * Math.random()),
y: Math.ceil(this.floor.row * Math.random()),
}
let food = this.floor.blocks.filter((block) => {
if (block.pos.x == p.x && block.pos.y == p.y) {
return true;
}
});
food[0].type = FloorType.food;
this.floor.ReDraw(food); }
Move() { let head: Block = this.bodies[this.bodies.length - 1];
let next: Block = this.next(head);
if (!next || next.type == FloorType.snack) {
this.Die();
return;
}
if (next.type == FloorType.food) {
this.bodies.push(next);
next.type = FloorType.snack;
this.floor.ReDraw(this.bodies);
this.RandFood();
next = this.next(this.bodies[this.bodies.length - 1]);
score++;
} let tail: Block = <Block>this.bodies.shift();
tail.type = FloorType.space;
next.type = FloorType.snack;
this.bodies.push(next);
this.floor.ReDraw([tail]);
this.floor.ReDraw(this.bodies);
}
Die() {
clearInterval(this.timer);
this.floor.DrawGameOver();
} next(targert: Block): Block {
let x: number;
let y: number;
switch (this.direction) {
case Direction.left:
x = targert.pos.x - 1;
y = targert.pos.y;
break;
case Direction.right:
x = targert.pos.x + 1;
y = targert.pos.y;
break;
case Direction.up:
x = targert.pos.x;
y = targert.pos.y - 1;
break;
case Direction.down:
x = targert.pos.x;
y = targert.pos.y + 1;
break;
}
return this.floor.blocks.filter((block) => {
if (x == block.pos.x && y == block.pos.y) {
return true;
}
})[0]; } } }
let floor=new Main.FLoor({ parent:document.getElementById("box")
});
floor.DrawFloor();
let snack=new Main.Snack(floor);
snack.DrawSnack();
html页面
 <html lang="en">

 <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
table {
border-bottom: 1px solid black;
border-right: 1px solid black;
border-collapse: collapse;
} td {
border-left: 1px solid black;
border-top: 1px solid black;
padding: 10px; } .space {
background-color: white;
} .body {
background-color: black;
} .food {
background-color: red;
}
.gameover{ position: absolute;
font-size: 36px;
color: aqua;
width:200px;
text-align: center;
}
#box{
float: left;
position: relative; }
</style>
</head> <body> <div id="box"> </div>
<script src="Snack.js"></script>
<!-- <script src="Game.js"></script> -->
</body> </html>
代码下载:发送邮件to:xiaotiejiang_90@163.com

typescript 贪吃蛇[学习过程中,模仿的一个例子]的更多相关文章

  1. mysql中case的一个例子

    最近遇到一个问题: year amount num 1991 1 1.1 1991 2 1.2 1991 3 1.3 1992 1 2.1 1992 2 2.2 1992 3 3.3 把上面表格的数据 ...

  2. 使用TypeScript实现简单的HTML5贪吃蛇游戏

    TypeScript是一种由微软开发的自由和开源的编程语言.它是JavaScript的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程.安德斯·海尔斯伯格,C#的首席架构师,已 ...

  3. 【C/C++】10分钟教你用C++写一个贪吃蛇附带AI功能(附源代码详解和下载)

    C++编写贪吃蛇小游戏快速入门 刚学完C++.一时兴起,就花几天时间手动做了个贪吃蛇,后来觉得不过瘾,于是又加入了AI功能.希望大家Enjoy It. 效果图示 AI模式演示 imageimage 整 ...

  4. 小菜学习Winform(一)贪吃蛇2

    前言 上一篇<小菜学习Winform(一)贪吃蛇>中实现了简单版的贪吃蛇,在文章末也提到需要优化的地方,比如使用oo.得分模式.速度加快模式和减少界面重绘.因为是优化篇,实现方式上一篇有, ...

  5. [C入门 - 游戏编程系列] 贪吃蛇篇(四) - 食物实现

    由于食物是贪吃蛇游戏中最简单的一部分,而且和其他部分关联性不强,基本上是一个独立的部分,所以我打算先实现它. 我的想法是食物必须在世界中才能被创造出来,也就是说,先有世界再有食物,所以我得先判断世界是 ...

  6. [C入门 - 游戏编程系列] 贪吃蛇篇(二) - 食物定义

    游戏中的食物没有那么多复杂属性,特别是贪吃蛇游戏中,我把食物看待的很简单: 1. 它必须属于世界,才能出现在世界.不可能一个不属于世界的食物,出现在世界中:但是可能存在着一个食物,它属于世界,但是却没 ...

  7. 前端笔记之JavaScript面向对象(三)初识ES6&underscore.js&EChart.js&设计模式&贪吃蛇开发

    一.ES6语法 ES6中对数组新增了几个函数:map().filter().reduce() ES5新增的forEach(). 都是一些语法糖. 1.1 forEach()遍历数组 forEach() ...

  8. AI贪吃蛇前瞻——基于Dijkstra算法的最短路径问题

    在贪吃蛇流程结构优化之后,我又不满足于亲自操刀控制这条蠢蠢的蛇,干脆就让它升级成AI,我来看程序自己玩,哈哈. 一.Dijkstra算法原理 作为一种广为人知的单源最短路径算法,Dijkstra用于求 ...

  9. JavaScript原生实现《贪吃蛇》

    概述 JavaScript原生实现<贪吃蛇>,每吃掉一个食物,蛇的身体会变长,食物会重新换位置. 详细 代码下载:http://www.demodashi.com/demo/10728.h ...

随机推荐

  1. Percona-Toolkit工具包之pt-archiver

      Preface       There's a common case that we neet to archive amount of records in some tables to a ...

  2. sqlite3 简单实用方法

    打开数据库:sqlite3.exe test.db 显示所有表: .tables 退出 sqlite3:.quit 还有个问题,已经打开一个数据库文件了. 不知道如何在不退出命令行的情况下,更换另一个 ...

  3. 讯为iTop4412嵌入式开发板学习之-------前言

    一.linux 工作的分类以及培养时间 Linux 作为一个庞大的体系,有很多相关的研究领域,总结起来大致有五个方向: 1.服务器维护:需要了解 Linux 服务,熟练使用 Shell,了解网络配置. ...

  4. python基础知识 -- set集合

    Set集合:是Python的一个基本数据类型.一般不是很常用.Set中的元素是不重复的,无序的,里面的元素必须是可hash的(int,str,tuple,bool).我们可以这样来计Set就是dict ...

  5. python-time模块、sys模块、os模块以及大量实例

    模块 通俗的说模块就把一个已经写好的带有可使用的函数的文件,通过文件名进行导入,然后调用里面的函数等来完成所需功能,模块封装了你需要实现功能的代码,使用者只需调用即可,简化代码量,缩短编程时间. ti ...

  6. ts包、表、子表、section的关系

    我们经常接触到创建 DEMUX,注册 Filter 过滤数据, 通过回调过滤出 section 数据,然后我们对 section 数据做具体的解析或者其他操作. 我们这里说的 section 就是段的 ...

  7. [BZOJ2809][Apio2012]dispatching(左偏树)

    首先对于一个节点以及它的子树,它的最优方案显然是子树下选最小的几个 用左偏树维护出每棵子树最优方案的节点,记录答案 然后它的这棵树可以向上转移给父节点,将所有子节点的左偏树合并再维护就是父节点的最优方 ...

  8. [转载]Java类打包成JAR文件

    原文传送门:http://www.2cto.com/kf/201204/129495.html 使用的工具及环境: MyEclipse 7.5 Java Enterprise.JDK1.6.0 打包J ...

  9. struts2官方 中文教程 系列六:表单验证

    先贴个本帖的地址,以免被爬:struts2教程 官方系列六:表单验证  即 http://www.cnblogs.com/linghaoxinpian/p/6906720.html 下载本章节代码 介 ...

  10. nodejs环境搭建与express安装配置

    一.NPM 1.下载nodeJS 下载地址:https://nodejs.org/en/download/ 因为我的系统是Linux 的,所以下载已经编译好的Linux,nodejs tar包 3.下 ...