代码实现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. leetcode笔记(六)740. Delete and Earn

    题目描述 Given an array nums of integers, you can perform operations on the array. In each operation, yo ...

  2. 通过xshell在linux上安装redis3.0.0

    通过xshell在linux上安装redis3.0.0 0)首先要安装环境:yum install gcc-c++ 1)通过xftp6将redis安装包上传到linux:解压缩:tar -xvfz r ...

  3. Modify the apache2 default document and home page on ubuntu (ubuntu下修改apache2默认目录和默认主页)

    Change the apache2 default website directory As we know, The apache2 default directory at /var/www/, ...

  4. 什么是CPU平均负载

    所属分类:运维教程 平均负载是指上一分钟同时处于就绪状态的平均进程数.在CPU中可以理解为CPU可以并行处理的任务数量,就是CPU个数X核数.如果CPU Load等于CPU个数乘以核数,那么就说CPU ...

  5. PHP生成一个六位数的邀请码

    PHP生成一个六位数的邀请码 $unique_no = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, ...

  6. c#学习笔记《1》——regex类

    C#regex是正则表达式类用于string的处理,查找匹配的字符串.1,先看一个例子Regex regex=new Regex(@”OK“)://我们要在目标字符串中找到"OK" ...

  7. yii 自带RBAC

    common:中加 'authManager' => [ 'class' => 'yii\rbac\DbManager', 'itemTable' => 'auth_item', ' ...

  8. Hive优化之谓词下推

    Hive优化之谓词下推 解释 Hive谓词下推(Predicate pushdown) 关系型数据库借鉴而来,关系型数据中谓词下推到外部数据库用以减少数据传输 基本思想:尽可能早的处理表达式 属于逻辑 ...

  9. Learning Experience of Big Data:The First Day-Try to set up a network connection on my virtural machine

    After we install our virtual machine,the first thing we should do is to set up a network connection ...

  10. 初学tiny4412

    1.解压友善之臂提供的uboot make tiny4412_config make 然后将sd卡插到电脑上,编辑虚拟机,选择对应的usb口(usb3.0兼容),如果没有usb3.0,可能是虚拟机版本 ...