HTML5中国

 找回密码
 立即注册

QQ登录

只需一步,快速开始

HTML5中国 首页 应用推荐 HTML5游戏 查看内容

基于HTML5和JS实现的切水果游戏

2016-3-7 16:30| 发布者: html5cn| 查看: 25569| 评论: 1|来自: 码农网

摘要: 切水果游戏曾经是一款风靡手机的休闲游戏,今天要介绍的就是一款网页版的切水果游戏,由JavaScript和HTML5实现,虽然功能和原版的相差很大,但是基本的功能还是具备了,还是模仿挺逼真的。有一定JavaScript水平的朋 ...

  切水果游戏曾经是一款风靡手机的休闲游戏,今天要介绍的就是一款网页版的切水果游戏,由JavaScript和HTML5实现,虽然功能和原版的相差很大,但是基本的功能还是具备了,还是模仿挺逼真的。有一定JavaScript水平的朋友可以看看源代码,相信你的JavaScript水平会有很大提升。


  在线演示    源码下载


  所有JavaScript代码

/**
 * this file was compiled by jsbuild 0.9.6
 * @date Fri, 20 Jul 2012 16:21:18 UTC
 * @author dron
 * @site http://ucren.com
 */

void function(global){
	var mapping = {}, cache = {};
	global.startModule = function(m){
		require(m).start();
	};
	global.define = function(id, func){
		mapping[id] = func;
	};
	global.require = function(id){
		if(!/\.js$/.test(id))
			id += '.js';
		if(cache[id])
			return cache[id];
		else
			return cache[id] = mapping[id]({});
	};
}(this);

/**
 * @source D:\hosting\demos\fruit-ninja\output\scripts\collide.js
 */ 
define("scripts/collide.js", function(exports){
	var fruit = require("scripts/factory/fruit");
	var Ucren = require("scripts/lib/ucren");

	var fruits = fruit.getFruitInView();

	/**
	 * 碰撞检测
	 */

	exports.check = function( knife ){
		var ret = [], index = 0;

		fruits.forEach(function( fruit ){
		    var ck = lineInEllipse(
		    	knife.slice( 0, 2 ), 
		    	knife.slice( 2, 4 ), 
		    	[ fruit.originX, fruit.originY ],
		    	fruit.radius
		    );
		    if( ck )
		        ret[ index ++ ] = fruit;
		});
		return ret;
	};

	function sqr(x){
		return x * x;
	}

	function sign(n){
		return n < 0 ? -1 : ( n > 0 ? 1 : 0 );
	}

	function equation12( a, b, c ){
		if(a == 0)return;

		var delta = b * b - 4 * a * c;
		if(delta == 0)
			return [ -1 * b / (2 * a), -1 * b / (2 * a) ];
		else if(delta > 0)
			return [ (-1 * b + Math.sqrt(delta)) / (2 * a),  (-1 * b - Math.sqrt(delta)) / (2 * a) ];
	}

	// 返回线段和椭圆的两个交点,如果不相交,返回 null
	function lineXEllipse( p1, p2, c, r, e ){
		// 线段:p1, p2    圆心:c    半径:r    离心率:e
		if (r <= 0) return;
		e = e === undefined ? 1 : e;
		var t1 = r, t2 = r * e, k;

		a = sqr( t2) * sqr(p1[0] - p2[0]) + sqr(t1) * sqr(p1[1] - p2[1]);

		if (a <= 0) return;

		b = 2 * sqr(t2) * (p2[0] - p1[0]) * (p1[0] - c[0]) + 2 * sqr(t1) * (p2[1] - p1[1]) * (p1[1] - c[1]);
		c = sqr(t2) * sqr(p1[0] - c[0]) + sqr(t1) * sqr(p1[1] - c[1]) - sqr(t1) * sqr(t2);

		if (!( k = equation12(a, b, c, t1, t2) )) return;

		var result = [
			[ p1[0] + k[0] * (p2[0] - p1[0]), p1[1] + k[0] * (p2[1] - p1[1]) ],
			[ p1[0] + k[1] * (p2[0] - p1[0]), p1[1] + k[1] * (p2[1] - p1[1]) ]
		];

		if ( !( ( sign( result[0][0] - p1[0] ) * sign( result[0][0] - p2[0] ) <= 0 ) &&
			( sign( result[0][1] - p1[1] ) * sign( result[0][1] - p2[1] ) <= 0 ) ) )
			result[0] = null;

		if ( !( ( sign( result[1][0] - p1[0] ) * sign( result[1][0] - p2[0] ) <= 0 ) &&
			( sign( result[1][1] - p1[1] ) * sign( result[1][1] - p2[1] ) <= 0 ) ) )
			result[1] = null;

		return result;
	}

	// 判断计算线段和椭圆是否相交
	function lineInEllipse( p1, p2, c, r, e ){
		var t = lineXEllipse( p1, p2, c, r, e );
		return t && ( t[0] || t[1] );
	};

	return exports;
});

/**
 * @source D:\hosting\demos\fruit-ninja\output\scripts\control.js
 */ 
define("scripts/control.js", function(exports){
	var Ucren = require("scripts/lib/ucren");
	var knife = require("scripts/object/knife");
	var message = require("scripts/message");
	var state = require("scripts/state");

	var canvasLeft, canvasTop;

	canvasLeft = canvasTop = 0;

	exports.init = function(){
		this.fixCanvasPos();
		this.installDragger();
		this.installClicker();
	};

	exports.installDragger = function(){
	    var dragger = new Ucren.BasicDrag({ type: "calc" });

	    dragger.on( "returnValue", function( dx, dy, x, y, kf ){
	    	if( kf = knife.through( x - canvasLeft, y - canvasTop ) )
	            message.postMessage( kf, "slice" );
	    });

	    dragger.on( "startDrag", function(){
	        knife.newKnife();
	    });

	    dragger.bind( document.documentElement );
	};

	exports.installClicker = function(){
	    Ucren.addEvent( document, "click", function(){
	        if( state( "click-enable" ).ison() )
	        	message.postMessage( "click" );
	    });
	};

	exports.fixCanvasPos = function(){
		var de = document.documentElement;

		var fix = function( e ){
		    canvasLeft = ( de.clientWidth - 640 ) / 2;
		    canvasTop = ( de.clientHeight - 480 ) / 2 - 40;
		};

		fix();

		Ucren.addEvent( window, "resize", fix );
	};;

	return exports;
});

/**
 * @source D:\hosting\demos\fruit-ninja\output\scripts\game.js
 */ 
define("scripts/game.js", function(exports){
	/**
	 * game logic
	 */
	var timeline = require("scripts/timeline");
	var Ucren = require("scripts/lib/ucren");
	var sound = require("scripts/lib/sound");
	var fruit = require("scripts/factory/fruit");
	var score = require("scripts/object/score");
	var message = require("scripts/message");
	var state = require("scripts/state");
	var lose = require("scripts/object/lose");
	var gameOver = require("scripts/object/game-over");
	var knife = require("scripts/object/knife");
	// var sence = require("scripts/sence");
	var background = require("scripts/object/background");
	var light = require("scripts/object/light");

	var scoreNumber = 0;

	var random = Ucren.randomNumber;

	var volleyNum = 2, volleyMultipleNumber = 5;
	var fruits = [];
	var gameInterval;

	var snd;
	var boomSnd;

	// fruit barbette
	var barbette = function(){
	    if( fruits.length >= volleyNum )
	        return ;

	    var startX = random( 640 ), endX = random( 640 ), startY = 600;
	    var f = fruit.create( startX, startY ).shotOut( 0, endX );

	    fruits.push( f );
	    snd.play();

	    barbette();
	};

	// start game
	exports.start = function(){
	    snd = sound.create( "sound/throw" );
	    boomSnd = sound.create( "sound/boom" );
	    timeline.setTimeout(function(){
	        state( "game-state" ).set( "playing" );
	        gameInterval = timeline.setInterval( barbette, 1e3 );
	    }, 500);
	};

	exports.gameOver = function(){
	    state( "game-state" ).set( "over" );
	    gameInterval.stop();

	    gameOver.show();

	    // timeline.setTimeout(function(){
	    //     // sence.switchSence( "home-menu" );
	    //     // TODO: require 出现互相引用时,造成死循环,这个问题需要跟进,这里暂时用 postMessage 代替
	    //     message.postMessage( "home-menu", "sence.switchSence" );
	    // }, 2000);

	    scoreNumber = 0;
	    volleyNum = 2;
	    fruits.length = 0;
	};

	exports.applyScore = function( score ){
	    if( score > volleyNum * volleyMultipleNumber )
	        volleyNum ++,
	        volleyMultipleNumber += 50;
	};

	exports.sliceAt = function( fruit, angle ){
	    var index;

	    if( state( "game-state" ).isnot( "playing" ) )
	        return;

	    if( fruit.type != "boom" ){
	        fruit.broken( angle );
	        if( index = fruits.indexOf( fruit ) )
	            fruits.splice( index, 1 );
	        score.number( ++ scoreNumber );
	        this.applyScore( scoreNumber );
	    }else{
	        boomSnd.play();
	        this.pauseAllFruit();
	        background.wobble();
	        light.start( fruit );
	    }
	};

	exports.pauseAllFruit = function(){
	    gameInterval.stop();
	    knife.pause();
	    fruits.invoke( "pause" );
	};

	// message.addEventListener("fruit.fallOff", function( fruit ){
	// 	var index;
	// 	if( ( index = fruits.indexOf( fruit ) ) > -1 )
	// 	    fruits.splice( index, 1 );
	// });

	message.addEventListener("fruit.remove", function( fruit ){
	    var index;
	    if( ( index = fruits.indexOf( fruit ) ) > -1 )
	        fruits.splice( index, 1 );
	});

	var eventFruitFallOutOfViewer = function( fruit ){
	    if( fruit.type != "boom" )
	        lose.showLoseAt( fruit.originX );
	};

	state( "game-state" ).hook( function( value ){
	    if( value == "playing" )
	        message.addEventListener( "fruit.fallOutOfViewer", eventFruitFallOutOfViewer );
	    else
	        message.removeEventListener( "fruit.fallOutOfViewer", eventFruitFallOutOfViewer );
	} );

	message.addEventListener("game.over", function(){
	    exports.gameOver();
	    knife.switchOn();
	});

	message.addEventListener("overWhiteLight.show", function(){
	    knife.endAll();
	    for(var i = fruits.length - 1; i >= 0; i --)
	        fruits[i].remove();
	    background.stop();
	});

	message.addEventListener("click", function(){
	    state( "click-enable" ).off();
	    gameOver.hide();
	    message.postMessage( "home-menu", "sence.switchSence" );
	});;

	return exports;
});

/**
 * @source D:\hosting\demos\fruit-ninja\output\scripts\layer.js
 */ 
define("scripts/layer.js", function(exports){
	/**
	 * layer manager
	 */

	var Raphael = require("scripts/lib/raphael");
	var Ucren = require("scripts/lib/ucren");

	var layers = {};
	var zindexs = {
		"default": zi(),
		"light": zi(),
		"knife": zi(),
		"fruit": zi(),
		"juice": zi(),
		"flash": zi(),
		"mask": zi()
	};

	exports.createImage = function( layer, src, x, y, w, h ){
		layer = this.getLayer( layer );
	    return layer.image( src, x, y, w, h );
	};

	exports.createText = function( layer, text, x, y, fill, size ){
		layer = this.getLayer( layer );

		if( Ucren.isIe )
			y += 2;

		return layer.text(x, y, text).attr({
			fill: fill || "#fff",
			"font-size": size || "14px",
			"font-family": "黑体",
			"text-anchor": "start"
		});
	};

	exports.getLayer = function( name ){
		var p, layer;
		name = name || "default";

		if( p = layers[name] ){
		    return p;
		}else{
			layer = Ucren.makeElement( "div", { "class": "layer", "style": "z-index: " + ( zindexs[name] || 0 ) + ";" } );
			Ucren.Element( "extra" ).add( layer );
			p = layers[name] = Raphael( layer, 640, 480 );
			// if( Ucren.isSafari )
			//     p.safari();
			return p;
		}
	};

	function zi(){
	    return zi.num = ++ zi.num || 2;
	};

	return exports;
});

/**
 * @source D:\hosting\demos\fruit-ninja\output\scripts\main.js
 */ 
define("scripts/main.js", function(exports){
	var timeline = require("scripts/timeline");
	var tools = require("scripts/tools");
	var sence = require("scripts/sence");
	var Ucren = require("scripts/lib/ucren");
	var buzz = require("scripts/lib/buzz");
	var control = require("scripts/control");
	var csl = require("scripts/object/console");
	var message = require("scripts/message");
	var state = require("scripts/state");

	var game = require("scripts/game");

	var collide = require("scripts/collide");

	var setTimeout = timeline.setTimeout.bind( timeline );

	var log = function(){
	    var time = 1e3, add = 300, fn;
	    fn = function( text ){
	        setTimeout( function(){ csl.log( text ); }, time );
	        time += add;
	    };
	    fn.clear = function(){
	        setTimeout( csl.clear.bind( csl ), time );
	        time += add;
	    };
	    return fn;
	}();

	exports.start = function(){

	    [ timeline, sence, control ].invoke( "init" );

	    log( "正在加载鼠标控制脚本" );
	    log( "正在加载图像资源" );
		log( "正在加载游戏脚本" );
	    log( "正在加载剧情" );
	    log( "正在初始化" );
		log( "正在启动游戏..." );
	    log.clear();

	    setTimeout( sence.switchSence.saturate( sence, "home-menu" ), 3000 );
	};

	message.addEventListener("slice", function( knife ){
	    var fruits = collide.check( knife ), angle;
	    if( fruits.length )
	        angle = tools.getAngleByRadian( tools.pointToRadian( knife.slice(0, 2), knife.slice(2, 4) ) ),
	        fruits.forEach(function( fruit ){
	           message.postMessage( fruit, angle, "slice.at" );
	        });
	});

	message.addEventListener("slice.at", function( fruit, angle ){

	    if( state( "sence-state" ).isnot( "ready" ) )
	        return ;

	    if( state( "sence-name" ).is( "game-body" ) ){
	        game.sliceAt( fruit, angle );
	        return ;
	    }

	    if( state( "sence-name" ).is( "home-menu" ) ){
	        fruit.broken( angle );
	        if( fruit.isHomeMenu )
	            switch( 1 ){
	                case fruit.isDojoIcon:
	                    sence.switchSence( "dojo-body" ); break;
	                case fruit.isNewGameIcon:
	                    sence.switchSence( "game-body" ); break;
	                case fruit.isQuitIcon:
	                    sence.switchSence( "quit-body" ); break;
	            }
	        return ;
	    }
	});

	var tip = "";

	if( !Ucren.isChrome )
	    tip = "$为了获得最佳流畅度,推荐您使用 Google Chrome 体验本游戏";

	if( !buzz.isSupported() )
	    tip = tip.replace( "$", "您的浏览器不支持 
 
来源:码农网
更多
3

鲜花

握手

雷人

路过

鸡蛋

刚表态过的朋友 (3 人)

相关阅读

发表评论

最新评论

引用 linedd963 2017-4-7 01:46
舞蹈和**都是肢體語言。因此,**是另類的舞蹈。它們都從遠古走來,彌久不衰。在沒有?生語言之前,就有了舞蹈。舞蹈不需要語言,它用形體動作訴說壹切。狹義的舞蹈源于生活,在人還沒成?人之前,便會用“手舞之,足蹈之”表達喜悅;**,緣于需求,人們用它制造歡樂,繁衍後代,男人尋樂秘密基地+籟:dd963

查看全部评论(1)

HTML5中国微信

小黑屋|关于我们|HTML5论坛|友情链接|手机版|HTML5中国 ( 京ICP备11006447号 京公网安备:11010802018489号  

GMT+8, 2017-5-29 17:47

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

返回顶部