game.html :
<html >
<head>
<title></title>
<script src="game.js"></script>
</head>
<canvas id="cvsPnl" width = 800 height = 500 ></canvas>
<div id="debug" ></div>
<body>
<script type="text/javascript">
var canvas = document.getElementById("cvsPnl");
var context = canvas.getContext("2d");
全局游戏控制器
var gameMaster;
var debuger;
window.οnlοad=function(){
gameMaster = new GameMaster(context);
gameMaster.GameStart();
}
键盘事件handler
document.onkeydown = function (){
var key = document.all ? event.keyCode : arguments[0].keyCode;
left
if(key == 37){
}
up
else if(key == 38){
}
right
else if(key == 39){
}
//down
else if(key == 40){
}
}
连续按键时使用
document.onkeyup = function(){
var key = document.all ? event.keyCode : arguments[0].keyCode;
if(key == 37 || key == 38 || key == 39 ||key == 40){
isKeyBoardMoving = false;
}
}
鼠标事件
document.οnclick=function(e){
如果是左键
if (e.button == 0){
// clickX = Math.round(e.clientX/10) * 10;
// clickY = Math.round(e.clientY/10) * 10;
}
}
</script>
</body>
</html>
game.js:
document.write("<script language='javascript' src='config.js'></script>");
document.write("<script language='javascript' src='utility.js'></script>");
document.write("<script language='javascript' src='global.js'></script>");
document.write("<script language='javascript' src='debug.js'></script>");
游戏入口
var debuger;
function GameMaster(context){
this.context = context;
debuger = new Debuger("debug");
}
GameMaster.prototype = {
GameStart : function(){
this.InitGame();
this.RunGame(this);
},
InitGame : function(){
},
RunGame : function(gameMaster){
if(timer){
clearInterval(timer);
}
timer = setInterval(function(){
if(gameMaster.IsGameOver()){
alert("game over!");
clearInterval(timer);
return;
}
debuger.DebugTxt(GetCurrentDateTime());
gameMaster.Repaint();
},sleepTime);
},
IsGameOver : function(){
return false;
},
重绘
Repaint : function(){
}
}
config.js:
/*
全局系统配置
*/
var timer;
var sleepTime = 1000;
utility.js:
/*
全局函数工具类
*/
返回客户端对象
function $(clientId){
return document.getElementById(clientId);
}
获得SELECT选中项
function GetSelectObj(clientId){
var obj = $(clientId);
var index = obj.selectedIndex; // 选中索引
return obj.options[index];
}
生产随机数
function GetRandom(n){return Math.floor(Math.random()*n+1)}
存储键值对
function addKV(k,v){
localStorage.setItem(k,v);
}
取得键值对的值
function getV(k){
return localStorage.getItem(k);
}
获得本地存储的所有值并转化为字符串
function getAllValueToStr(){
var content = "";
for(var i=0;i<localStorage.length;i++){
//key(i)获得相应的键,再用getItem()方法获得对应的值
content += localStorage.key(i)+ " : " + localStorage.getItem(localStorage.key(i)) + "<br />";
}
return content;
}
显示当前时间
function GetCurrentDateTime(){
var time ;
with(new Date()){
time =toLocaleString() + '星期' + '日一二三四五六'.charAt(getDay());
}
return time;
}
global.js
debug.js:
function Debuger(clientId){
this.clientId = clientId;
}
Debuger.prototype = {
DebugTxt : function(value){
$(this.clientId).innerHTML = value;
}
}