D3.js版贪吃蛇(Eating Snake)

JavaScript制作贪吃蛇小游戏 揭秘贪吃蛇小游戏代码 阅读详情

简介

三方君用 d3.js 实现贪吃蛇小游戏设计

点这边玩玩看

Source Code

<!DOCTYPE html>
<html>
<head>
    <title>Eating Snake</title>
	<script src="https://d3js.org/d3.v3.min.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<style>
	button {
      padding: 6px 12px;
      font-size: 14px;
      background-color: #fff;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin: 5px;
    }
    .start {
      color: white;
      background-color: red;
      border: 1px solid transparent;
    }	
	.new {
      color: white;
      background-color: #5cb85c;
      border: 1px solid transparent;
    }
	#Grids{
	  border: 1.5px solid #ccc;
	  max-width: 250px;
	  max-height: 250px;
	}
</style>
<p>Eating Snake</p>
<div id="Control"></div>
<div id="Grids"></div>
<script>
$(document).ready(function(){
	var rectW = 25, rectL = 25, cc = 10, delayTime = 100, timerID = 0, stopped = true, 
		nextDir, grids, body, food, head,
		color = ['white','black','green'],
		directionVectors = {
			65: [-1,0], 37: [-1,0],    // 'A' or Left Arrow
			87: [0,-1], 38: [0,-1],    // 'W' or Up Arrow
			68: [1,0],  39: [1,0],     // 'D' or Right Arrow
			83: [0,1],  40: [0,1]      // 'S' or Down Arrow
		};
		
	var xs = d3.scale.linear().domain([0,rectL]).range([0,rectL * cc]),
		ys = d3.scale.linear().domain([0,rectW]).range([0,rectW * cc]);
		
	var rects = d3.select("#Grids")
				.append("svg:svg")    
				.attr("stroke", "rgba(204, 204,204,0.2)")
				.attr("shape-rendering", "optimizeSpeed")
				.attr("width",rectL*cc)
				.attr("height", rectW*cc);
			
	var ctrl = d3.select("#Control")
		
		ctrl.append('button')
			.attr('class', 'new')
			.text('New')
			.on('click', function(){ return setNewGrid() });
		
		ctrl.append('button')
			.attr('class', 'start')
			.text('Start')
			.on('click', startStop);
			
	var initialize = function(){
		
		grids = [];
		d3.range(rectL).forEach(function(x){
			grids[x] = new Array();
			d3.range(rectW).forEach(function(y){	
				grids[x][y] = 0;
			});
		});
		
		body = [[0,0],[0,1],[0,2],[0,3]];
		head = [0,3];
		nextDir = [0,1];
		
		makeFood();
		makeBody();

		rects.selectAll("rect")
			.data(function(){ return setGrid()})
			.enter()
			.append("rect")
			.attr("x", function(d){ return xs(d.x)})
			.attr("y", function(d){ return ys(d.y)})
			.attr("width",cc)
			.attr("height",cc)
			.attr("fill", function(d){ return color[d.state];});
	};

	$(document).keydown(function(event){
		var vector = directionVectors[event.which];
		if (!vector) return;
		// (right <--> left or up <--> down)
		if ((vector[0] !== 0 && vector[0] + nextDir[0] === 0) ||
			(vector[1] !== 0 && vector[1] + nextDir[1] === 0)) {
				return;
			}		
		nextDir = vector;
		event.preventDefault()
	});
	 
	function collide(a, b){
		var k = 0
		b.forEach( function(x){
			if(a[0]==x[0] && a[1]==x[1]){
				k = 1;
			}
		});
		return k;
	} ;
	
	function makeFood(){
		var x, y, k = 1;
		while(k){
			x = Math.floor(Math.random()*rectL); 
			y = Math.floor(Math.random()*rectW);
			if(!collide([x,y],body))
				k = 0;
		}
		food = [x, y];
		grids[x][y] = 2; 
	}
	
	function makeBody(){
		for(var i in body){
			var x = body[i][0],
				y = body[i][1];
			grids[x][y] = 1;
		}
	}
	
	var setGrid = function (){
		var bits = [];
		for(var i= 0; i< rectL; i++){
			for(var j= 0; j< rectW; j++){
				bits.push({ "x": i, "y": j, "state": grids[i][j] });
			}
		}
		return bits;
	};
	
	var setNewGrid = function (){	
		initialize();
		displayGrid();
		nextDir = [0,1];
	}
	
	var move = function(){

		function getNext(i,j){
			var x = i[0] + j[0];
			var y = i[1] + j[1];
			return [x, y];
		}
		
		var nextPos = getNext(head, nextDir);
		
		if(nextPos[0] < 0 || nextPos[1] < 0 || nextPos[0] >= rectL ||  nextPos[1] >= rectW ){
			startStop();
			return;
		}
		
		if(collide(nextPos, body)){
			startStop();
			return;
		}
		
		head[0] = nextPos[0];
		head[1] = nextPos[1];
		body.push([head[0], head[1]]);
		
		if(nextPos[0] == food[0] && nextPos[1] == food[1]){
			makeFood(); 
		}
		else{
			grids[body[0][0]][body[0][1]] = 0;
			body.shift();
		}
		
		makeBody()
		
		displayGrid();
	};

	var displayGrid = function(){	
		rects.selectAll("rect")
			.data(function(){ return setGrid()})
			.transition()
			.attr("fill", function(d) { return color[d.state]; })
			.duration(0);
	}
	
	function startStop() {
		stopped = !stopped;
		d3.select('button.start')
			.text(function () { return stopped ? 'Start' : 'Stop';});
	}
	
	var run = function(){		
		clearInterval(timerID);
		timerID = setInterval( function(){ if (!stopped) move();},delayTime);
	}
	
	initialize();
	run();
});
</script>
</body>
</html>

 

 

D3JS相关系列教程

  1. D3.js 实战 - 上色落伍了,来点图样吧!
  2. D3.js 实战 - 地表最快地球仪应用   
  3. 让我的视觉化动起来!D3.js 动画函数入门
  4. D3.js 视觉化教学 -全球即时地震视觉化
  5. 总整理!你不可错过的 d3.js 数据转换技巧
  6. D3.js版贪吃蛇(Eating Snake)
  7. 统计图表制作 – 使用 d3-generator
  8. 用 JavaScript 做数据视觉化 - D3.JS
  9. 高手才知道!七个你所不知道的 D3.js 秘技
  10. D3JS 实战 - 是长条也是圆饼的变形图表

JavaScript做贪吃蛇 文章目录前言一、效果动画展示二、html主页面二、三个js包1.Game.js2.Snake.js (蛇的设置)3.Food.js (食物的设置) 前言 这个关卡是用JavaScript做的一个贪吃蛇游戏 一、效果动画展示 二、html主页面 代码展示: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Comp 阅读详情

相关推荐

jQuery鱼骨图形式信息展示代码

jQuery鱼骨图形式信息展示代码 jQuery鱼骨图形式信息展示代码

js/jq/HTML5实现 鱼骨图(因果图) 附下载地址demo

下载地址:https://github.com/ybx13579/d3.fishbone-js.git 1、官网示例(data.json控制数据) 官网 作者 效果图展示: 2、当前页面实时编辑 效果图展示:

Ice Yang的博客 1万+

d3.fishbone-js:js鱼骨图(因果图)基于SVG 预览:http

d3.fishbone-js js鱼骨图(因果图) 弊端:css样式无法精准设定 实现原理:SVG绘图 效果图 : 1、官网示例(data.json控制数据) 预览: 官网: 作者: 2、当前页面实时编辑

d3.js学习笔记 (五) (打包图与冒泡图)

打包图仅表示数据间包含关系,打包图如下示例: var width = 500; var height = 500; //================设置打包图布局======================= var pack = d3.layout.pack() .size([width, height]) ...

u012846041的专栏 1525

js控件实现鱼刺图(fishbone)的控件源码

将鱼刺图嵌入java web 系统的js控件 需要的自己研究下 ps:看评论里面近期负面评价比较多,在此声明一下:这是我刚工作(2014年)的时候做技术攻关的时候研究的,时间比较久,技术也比较老,当时只是用在普通javaweb项目中的,而且当时还没有nodejs,也可能是我不懂前端不知道,但是确实是使用在已交付的项目中了,觉得有问题跑不通的,自己认真研究一下吧,毕竟环境差距比较大。做技术的,还是要沉下心来研究一下,毕竟是偏门,做的人比较少,经验分享也比较少,当时也没有意识要总结出一份文档出来,也对大家说一声抱歉,下载需谨慎!!!下载需谨慎!!!下载需谨慎!!!

jQuery鱼骨图时间趋势图代码.zip

有兴趣刚需的可以自己下载,非常使用的jquery代码,可以完美运行,有能力的还可以二次修改!

d3.fishbone-js - 基于SVG的鱼骨图(因果图)JavaScript库

d3.fishbone-js - 基于SVG的鱼骨图(因果图)JavaScript库 【下载地址】d3.fishbone-js-基于SVG的鱼骨图因果图JavaScript库 d3.fishbone-js 是一个基于SVG的鱼骨图(因果图)JavaScript库,专为直观展示因果关系而设计。它利用SVG技术,确保图形的高...

gitblog_06744的博客 961

vue使用svg文件补充-svg放大缩小操作(使用d3.js)

主要介绍了vue使用svg文件补充-svg放大缩小操作(使用d3.js),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

Vue路由

一、Vue路由: 1. SPA是什么 单页Web应用(single page application,SPA),就是只有一个Web页面的应用, 是加载单个HTML页面,并在用户与应用程序交互时动态更新该页面的Web应用程序 单页面应用程序: 只有第一次会加载页面, 以后的每次请求, 仅仅是获取必要的数据.然后, 由页面中js解析获取的数据, 展示在页面中 传统...

weixin_44557427的博客 590

【PyTorch版本兼容性指南】如何在不同版本中正确使用torch.nn.attention

本文详细解析了PyTorch版本兼容性问题,特别是torch.nn.attention模块在不同版本中的使用差异。针对常见的ModuleNotFoundError错误,提供了三种实用解决方案:升级PyTorch版本、使用自定义实现和源码移植方案,并分享了最佳实践建议,帮助开发者有效避免兼容性问题。

weixin_29084231的博客 474

深入解析Dataloader中shuffle机制与随机种子对模型训练的影响

本文深入探讨了Dataloader中shuffle机制与随机种子对机器学习模型训练的影响。通过实际案例分析,详细解释了数据打乱顺序的必要性、随机种子的正确设置方法以及两者协同工作的原理,帮助开发者避免常见陷阱并提升模型训练效果。

weixin_29166013的博客 142

JS高级3贪吃蛇

属性:宽 高 背景颜色 定位 左 上 方向。方法: 渲染方法 蛇吃食物 蛇移动的方向。属性:宽 高 背景颜色 定位 左 上。方法:渲染方法 游戏开始方法。属性:食物 蛇 地图。// 创建食物的实例化对象。// 创建蛇的实例化对象。// 获取地图。

weixin_53560514的博客 309

如何在Android上使用OpenCV进行摄像头标定

如何在Android上使用OpenCV进行摄像头标定,我们这里使用官方一个例程,其实并不难,只是网上的资料少了而已。相机标定是计算机视觉工作的前提,为了确定相机矩阵和畸变参数。

花草的博客 3441

JavaScript Snake 游戏开发指南

JavaScript Snake 游戏开发指南 项目介绍 JavaScript Snake 是一个基于 JavaScript 的经典贪吃蛇游戏实现。该项目由 Jakes Gordon 创建并维护,它不仅重温了早期手机时代的趣味小游戏,还展示了如何用现代 Web 技术构建简单而有趣的交互式应用。此项目适合初学者学习基本的编程概念,如事件处理、动画以及简单的游戏逻辑。 项目快速启动 要快速启动并运行 ...

gitblog_00386的博客 629

多目标优化NSGA-II(快速精英非支配排序遗传算法)及python实现

文章目录前言一、什么是NSGA-II?二、学习NSGA-II1.快速非支配排序算法2.密度估计3.拥挤比较算子4.主循环5.代码6.总结 前言 NSGA-II适用于复杂的多目标优化问题,是K-Deb教授在2000年在一篇paper《MOEAs — A fast and elitist multi-objective genetic algorithm: nsga2》提出。 Keywords: optimization; multi-objective evolutionary algorithm; no

ricky_blog 9749

±10V ADC 输入电路的高共模差分输入电压

这篇文章分析了±10V ADC输入电路的设计需求与挑战,重点讨论了高共模差分输入电压的处理方案。文章首先明确了设计目标,即安全转换±10V差分信号并保持信号完整性,同时克服高共模电压、阻抗匹配和噪声优化等难点。随后详细比较了仪表放大器和差分放大器的性能特点,并提出了器件选型理论。在信号链架构部分,文章通过公式推导阐述了增益设置、共模抑制设计和输入阻抗匹配等关键技术。此外,还建立了噪声源模型,提出了噪声优化措施。最后,文章总结了设计验证方法,并扩展了在工业保护和生物电信号采集等场景的应用。该设计强调根据具体应

泛红尘的博客 1963

gh_mirrors/snake1/snake:在浏览器URL上玩贪吃蛇?这个创意小游戏让你大开眼界!

gh_mirrors/snake1/snake是一个极具创意的开源项目,它将经典的贪吃蛇游戏巧妙地搬到了浏览器的URL地址栏中。这款独特的小游戏让你在浏览网页的同时,就能体验到怀旧又新奇的游戏乐趣,是GitHub加速计划中一个充满趣味的创新应用。 ## 前所未有的游戏体验:URL地址栏变身游戏场 🎮 传统的贪吃蛇游戏通常需要在专门的应用程序或网页区域内运行,而gh_mirrors/snake

gitblog_00291的博客 996

PyTorch实战(12)——图神经网络(Graph Neural Network,GNN)

在本节中,我们首先简要概述了图神经网络 (Graph Neural Network, GNN) 的核心概念与应用,GNN 通过构建计算图分层聚合节点特征,解决了传统神经网络处理图数据时的四大局限:信息深度不足、节点顺序敏感、动态扩展困难和特征稀疏性问题。了解了不同类型的图学习任务(包括节点级、边级和图级三大类)。接着我们研究了几种流行的 GNN 模型,包括:GCN (通过权重共享实现图卷积)、GAT (引入注意力机制区分邻居重要性)和 GraphSAGE (采用随机采样应对大规模图)。

盼小辉丶的博客 3734

【源代码分享】 Snake Game - 贪吃蛇

npm run build # 将 dist/ 目录上传到你的服务器👉详细部署指南→。

JavaPub 1030

MIL图像处理那些事:MIL的安装和MIL工具箱

MIL图像处理那些事:MIL的安装和测试,如何用C#使用MIL

十多年IT经验,专注机器视觉,智能制造半导体行业 5279

【2026年华为秋招(AI)-2月4日-第一题(100分)- 选择题】(题目+思路+Java&C++&Python解析+在线测试)

本文摘要:本文包含20道选择题,涵盖机器学习、线性代数、Transformer架构、概率统计等多个领域。题目涉及正交矩阵性质、Transformer注意力机制、聚类距离度量、ReAct框架、Softmax函数、混淆矩阵计算、Flash-Attention优化、位置编码、期望计算、归一化方法、矩阵迭代法、矩阵秩、大模型架构、神经网络推理、泊松流性质、SVM核函数以及聚类算法等知识点。每道题均提供解析,帮助理解核心概念和解题思路。

m0_73659489的博客 126

javascript贪吃蛇 (附带百度网盘链接)

这里贪吃蛇游戏是通过javascript面向对象编程的方法编写,代码结构分为游戏类(Game.js), 蛇行为类(Snake.js),食物类(Food.js),话不多说,直接源码了。(粘贴源码,引入正确路径即可运行) 贪吃蛇:链接:https://pan.baidu.com/s/1_gfxQOWZ5ktZXLARzcn6fA 提取码:672a 游戏页面: 1.html&css页面搭建: index.html: <!DOCTYPE html> <ht...

weixin_45851686的博客 4104

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

JavaScript 游戏系列(一): 贪吃蛇

JavaScript 游戏系列目录 文章目录JavaScript 游戏系列目录一、实例截图二、游戏分析三、HTML 与 CSS 文件1、入口文件2、样式文件四、游戏逻辑的实现1、创建类 一、实例截图 默认界面 游戏界面 二、游戏分析 首先,从截图里我们能够看到,游戏存在着 地图,蛇,食物 。 由此我们可以划分三个类 蛇类,食物类 与 游戏类。 每个类包含如下功能: Snake 类 : 移动 改变移动方向 验证是否撞到自身 长大(吃到食物) Food 类 : 定义食物位置 Game 类 :

Amecai的学习博客 681

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Space Snake 开源项目安装及使用指南

Space Snake 开源项目安装及使用指南 1. 项目介绍 Space Snake, 是一个基于 Web 技术创建的游戏项目,其核心理念是将经典的贪吃蛇游戏扩展至宇宙背景中,赋予了传统玩法新的生命。项目采用了 HTML5 的 Canvas API 进行图形绘制,结合 JavaScript 实现游戏逻辑,提供了流畅的用户体验和丰富的视觉效果。 2. 快速启动 2.1 环境准备 确保你的开发环境中...

gitblog_00438的博客 933

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

js 贪吃蛇

不管是写法 还是逻辑结构上 都有待提高 希望园子里的高手拍砖 提意见 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://w...

aian91805的博客 124

linux 贪吃蛇终极脚本,javascript贪吃蛇完整版(源码)

javascript贪吃蛇完整版 注释完整,面向对象贪吃蛇 Snake v2.4body{font-size:9pt;}table{border-collapse: collapse;border:solid #333 1px;}td{height: 10px;width: 10px;font-size: 0px;}.filled{background-color:blue;}function $...

weixin_39523887的博客 163
上一篇: 高手才知道!七个你所不知道的 D3.js 秘技
下一篇: D3.js 视觉化教学 -全球即时地震视觉化
opensourceLab
博客等级 码龄10年 5粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值