HTML5 打地鼠
一直想用HTML5做个小游戏,但总是没有时间,今天抽了几个小时做了个打地鼠的小游戏,体验一下HTML5上的游戏开发。本着OSC的分享精神,特分享出来。没有花时间去找更多的素材,再加上本来就不怎么会做图,出了那个地洞的素材以外其他的全是从网上搜到的。代码也比较混乱,大家就凑合着看看吧,欢迎大家批评指正,也欢迎大家能把这个小游戏做的更完善些。
废话不说了,大家先看看效果吧:
HTML文件:
02 <html lang="en" >
03 <head>
04 <meta charset="utf-8" />
05 <title>打地鼠</title>
06 <script type="text/javascript" src="js/game.js"></script>
07 </head>
08 <body onload="init()">
09 <div class="container">
10 <canvas onmouseover="hideCursor(this)" onmouseout="showCursor"
11 onmousemove="hammerMove(this);"
12 onmousedown="hammerDown();" onmouseUp="hammerUp();"
13 id="screen" width="700" height="500" style="border:1px solid #000"></canvas>
14 </div>
15
16 <div id="info"></div>
17 </body>
18 </html>
JS文件:
001 var canvas, ctx, info;
002 var bg;
003 var hammer, hamX, hamY;
004 var mouseState, mouseFrmLen = 10, mousePress = false;
005 var sprites = [], holes = [];
006 var score = 0;
007 var Sprite = function(w, h, x, y, state, image){
008 var self = this;
009 this.w = w;
010 this.h = h;
011 this.x = x;
012 this.y = y;
013 this.image = image;
014 this.state = state;
015
016 this.draw = function(){
017 if(this.state == 'show'){
018 ctx.drawImage(this.image, this.x, this.y, this.w, this.h);
019 setTimeout(function(){
020 self.state = 'hide';
021 },3000);
022 }
023 }
024 }
025
026 var HoleSprite = function(w, h, x, y, state, image){
027 var self = this;
028 this.w = w;
029 this.h = h;
030 this.x = x;
031 this.y = y;
032 this.image = image;
033 this.state = state;
034
035 this.draw = function(){
036 if(this.state == 'show'){
037 ctx.drawImage(this.image, this.x, this.y, this.w, this.h);
038 }
039 }
040 }
041
042 function HammerSprite(w, h, x, y, image){
043 HammerSprite.prototype.w = w;
044 HammerSprite.prototype.h = h;
045 HammerSprite.prototype.x = x;
046 HammerSprite.prototype.y = y;
047
048 HammerSprite.prototype.draw = function(isPress){
049 if(isPress){
050 ctx.save();
051
052 ctx.translate(this.x-10, this.y+34);
053 ctx.rotate(Math.PI/180*330);
054 ctx.drawImage(image, 0, 0, w, h);
055
056 ctx.restore();
057 }else{
058 ctx.drawImage(image, this.x, this.y, w, h);
059 }
060
061 }
062 }
063
064 function clearScreen(){
065 //ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
066 ctx.drawImage(bg, 0, 0, ctx.canvas.width, ctx.canvas.height);
067
补充:web前端 , HTML 5 ,