61、动画与游戏编程:从弹球到简单游戏实现

动画与游戏编程:从弹球到简单游戏实现

在动画和游戏编程领域,弹球效果是一个基础且有趣的示例,它能帮助我们理解动画的基本原理,如物体的移动、碰撞检测等。下面将详细介绍从简单的弹球动画到实现一个简单游戏的过程。

1. 弹球动画基础

首先,我们从一个简单的弹球动画开始。 PaintSurface 类继承自 JComponent ,用于定义动画的表面。该类的实例变量定义了球的特征,包括球在组件上的 x 和 y 位置以及球的直径。

class PaintSurface extends JComponent
{
    int x_pos = 0;
    int y_pos = 0;
    int d = 20;
    int width = BallRoom.WIDTH;
    int height = BallRoom.HEIGHT;

    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        x_pos += 1;
        Shape ball = new Ellipse2D.Float(
            x_pos, y_pos, d, d);
        g2.setColor(Color.RED);
        g2.fill(ball);
    }
}

paint 方法在 PaintSurface 组件需要重绘时被调用,这里通过 AnimationThread 类的 run 方法每 20 毫秒触发一次。该方法首先将图形上下文转换为 Graphics2D 对象并启用抗锯齿,然后通过将 x 位置加 1 来计算球的新位置,最后创建一个 Shape 对象表示球并绘制出来。

2. 双缓冲技术

在动画和游戏编程中,双缓冲技术是实现平滑、无闪烁动画的关键。传统上,使用双缓冲时,不直接将形状绘制到组件上,而是创建一个名为缓冲区的离屏图像对象,将形状绘制到该对象上,绘制完成后将整个缓冲区图像传输到组件上。

幸运的是,在 Swing 组件上进行的任何绘制都会自动进行双缓冲。如果出于某种原因想关闭双缓冲,可以调用绘制组件的 setDoubleBuffered 方法:

this.setDoubleBuffered(false);
3. 实现弹球反弹效果

前面的弹球动画只是让球沿直线飞过屏幕并消失,为了让动画更有趣,我们需要让球在不同方向上移动并从组件边缘反弹。实现这一效果有两种基本方法:
- 精确计算法 :跟踪球的两个变量,即它的运动角度和速度,然后使用高中三角函数为每个动画周期计算球的新 (x, y) 位置。如果球撞到边缘,还需要计算球的新角度,这种方法需要一定的数学知识。
- 简单加法法 :存储两个变量 x_speed 和 y_speed ,分别表示球在每个动画周期内水平和垂直移动的距离。每个周期只需将 x_speed 加到 x 位置,将 y_speed 加到 y 位置。如果球撞到左右边缘,将 x_speed 取反以反转水平方向;如果撞到上下边缘,将 y_speed 取反以反转垂直方向。

以下是实现反弹效果的 PaintSurface 类代码:

class PaintSurface extends JComponent
{
    int x_pos = 0;
    int y_pos = 0;
    int x_speed = 1;
    int y_speed = 2;
    int d = 20;
    int width = BallRoom.WIDTH;
    int height = BallRoom.HEIGHT;

    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        if (x_pos < 0 || x_pos > width - d)
            x_speed = -x_speed;
        if (y_pos < 0 || y_pos > height - d)
            y_speed = -y_speed;
        x_pos += x_speed;
        y_pos += y_speed;
        Shape ball = new Ellipse2D.Float(
            x_pos, y_pos, d, d);
        g2.setColor(Color.RED);
        g2.fill(ball);
    }
}

该类的关键元素如下:
- 实例变量跟踪球的 x 和 y 位置、速度、直径以及绘图表面的高度和宽度。
- if 语句检查球是否撞到左右边缘或上下边缘,如果是则反转相应的速度。
- 调整速度后,更新球的位置并绘制。

4. 多个弹球动画

大多数游戏需要同时动画多个精灵,例如屏幕上可能同时有多个球。为了实现这一点,我们可以创建一个表示单个球的类,并将其实例添加到数组列表或其他集合中,然后在 paint 方法中使用循环移动和绘制每个精灵。

4.1 创建 Ball 类
class Ball extends Ellipse2D.Float
{
    private int x_speed, y_speed;
    private int d;
    private int width = BallRoom.WIDTH;
    private int height = BallRoom.HEIGHT;

    public Ball(int diameter)
    {
        super((int)(Math.random() * (BallRoom.WIDTH - 20) + 1),
              (int)(Math.random() * (BallRoom.HEIGHT - 20) + 1),
              diameter, diameter);
        this.d = diameter;
        this.x_speed = (int)(Math.random() * 5 + 1);
        this.y_speed = (int)(Math.random() * 5 + 1);
    }

    public void move()
    {
        if (super.x < 0 || super.x > width - d)
            x_speed = -x_speed;
        if (super.y < 0 || super.y > height - d)
            y_speed = -y_speed;
        super.x += x_speed;
        super.y += y_speed;
    }
}

这个类的特点如下:
- 继承自 Ellipse2D.Float ,这样可以直接将 Ball 对象传递给 draw 和 fill 方法来绘制球。
- 定义了五个私有实例变量,分别表示球的 x 和 y 速度、直径以及组件的宽度和高度。由于 Ellipse2D.Float 类已经跟踪其 x 和 y 位置,所以不需要额外的实例变量。
- 构造函数接受球的直径作为参数,并随机计算其他值,因此每次创建的球都有不同的起始位置和轨迹。
- move 方法用于移动球,首先检查球是否撞到边缘并调整轨迹,然后更新球的位置。

4.2 动画多个随机球

以下是一个 PaintSurface 类,用于创建一个包含 10 个随机放置球的数组列表,并在 paint 方法中绘制每个球:

class PaintSurface extends JComponent
{
    public ArrayList<Ball> balls = new ArrayList<Ball>();

    public PaintSurface()
    {
        for (int i = 0; i < 10; i++)
            balls.add(new Ball(20));
    }

    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.RED);
        for (Ball ball : balls)
        {
            ball.move();
            g2.fill(ball);
        }
    }
}

这个类的工作流程如下:
1. 声明一个名为 balls 的实例变量,用于存储要动画的球。
2. 在构造函数中,使用 for 循环创建 10 个球并添加到集合中。
3. 在 paint 方法中,每 20 毫秒调用一次,使用 for 循环调用每个球的 move 方法,然后将球传递给 fill 方法在组件上绘制。

5. 实现可碰撞的球

前面创建的球有一个不太真实的行为,即它们相互透明,如果两个球同时到达同一位置,它们会直接穿过彼此。为了让球既能从墙壁反弹又能相互反弹,需要修改 Ball 类的 move 方法。

class Ball extends Ellipse2D.Float
{
    public int x_speed, y_speed;
    private int d;
    private int width = BallRoom.WIDTH;
    private int height = BallRoom.HEIGHT;
    private ArrayList<Ball> balls;

    public Ball(int diameter, ArrayList<Ball> balls)
    {
        super((int)(Math.random() * (BallRoom.WIDTH - 20) + 1),
              (int)(Math.random() * (BallRoom.HEIGHT - 20) + 1),
              diameter, diameter);
        this.d = diameter;
        this.x_speed = (int)(Math.random() * 5 + 1);
        this.y_speed = (int)(Math.random() * 5 + 1);
        this.balls = balls;
    }

    public void move()
    {
        // detect collision with other balls
        Rectangle2D r = new Rectangle2D.Float(
            super.x, super.y, d, d);
        for (Ball b : balls)
        {
            if (b != this &&
                b.intersects(r))
            {
                // on collision, the balls swap speeds
                int tempx = x_speed;
                int tempy = y_speed;
                x_speed = b.x_speed;
                y_speed = b.y_speed;
                b.x_speed = tempx;
                b.y_speed = tempy;
                break;
            }
        }
        if (super.x < 0)
        {
            super.x = 0;
            x_speed = Math.abs(x_speed);
        }
        else if (super.x > width - d)
        {
            super.x = width - d;
            x_speed = -Math.abs(x_speed);
        }
        if (super.y < 0)
        {
            super.y = 0;
            y_speed = Math.abs(y_speed);
        }
        else if (super.y > height - d)
        {
            super.y = height - d;
            y_speed = -Math.abs(y_speed);
        }
        super.x += x_speed;
        super.y += y_speed;
    }
}

这个版本的 Ball 类的关键步骤如下:
- 构造函数接受一个引用,指向存储所有球的数组列表,以便每个球可以确定是否与其他球发生碰撞。
- move 方法首先创建一个矩形表示当前球,然后使用 for 循环检查是否与其他球发生碰撞。如果发生碰撞,交换两个球的 x 和 y 速度。
- 检查球是否撞到边缘,如果是则调整球的位置和速度,确保球在组件内移动。

弹球动画与简单游戏实现的流程总结

graph TD;
    A[开始] --> B[创建PaintSurface类绘制单个球];
    B --> C[使用双缓冲技术优化动画];
    C --> D[实现球的反弹效果];
    D --> E[创建Ball类实现多个球动画];
    E --> F[实现球的相互碰撞效果];
    F --> G[添加用户交互实现简单游戏];
    G --> H[结束];

代码关键元素总结

功能 关键代码元素
单个球动画 PaintSurface 类的 paint 方法
双缓冲 setDoubleBuffered 方法
球反弹 x_speed 和 y_speed 的调整
多个球动画 Ball 类和 ArrayList
球碰撞 Ball 类的 move 方法中的碰撞检测
用户交互 鼠标事件监听器

通过以上步骤,我们从简单的弹球动画逐步实现了多个球的动画、球的相互碰撞以及用户交互的简单游戏,掌握了动画和游戏编程的一些基本技巧。接下来,将进一步介绍如何将这些技术应用到一个简单的 Pong 类游戏中。

动画与游戏编程:从弹球到简单游戏实现

6. 实现简单游戏 - 类 Pong 游戏

将动画程序转变为游戏程序的关键在于添加用户交互,可通过鼠标或键盘实现。具体做法是添加事件监听器来处理键盘或鼠标事件,然后在事件监听器中根据用户的操作对游戏精灵进行相应的更改。

以下是一个简单的类 Pong 游戏的完整代码:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;

public class NotPong extends JApplet
{
    public static final int WIDTH = 400;
    public static final int HEIGHT = 400;
    private PaintSurface canvas;

    public void init()
    {
        this.setSize(WIDTH, HEIGHT);
        canvas = new PaintSurface();
        this.add(canvas, BorderLayout.CENTER);
        Thread t = new AnimationThread(this);
        t.start();
    }
}

class AnimationThread extends Thread
{
    JApplet c;

    public AnimationThread(JApplet c)
    {
        this.c = c;
    }

    public void run()
    {
        while (true)
        {
            c.repaint();
            try
            {
                Thread.sleep(20);
            }
            catch (InterruptedException ex)
            {
                // swallow the exception
            }
        }
    }
}

class PaintSurface extends JComponent
{
    int paddle_x = 0;
    int paddle_y = 360;
    int score = 0;
    float english = 1.0f;
    Ball ball;
    Color[] color = {Color.RED, Color.ORANGE, 
                     Color.MAGENTA, Color.ORANGE, 
                     Color.CYAN, Color.BLUE};
    int colorIndex;

    public PaintSurface()
    {
        addMouseMotionListener(new MouseMotionAdapter()
        {
            public void mouseMoved(MouseEvent e)
            {
                if (e.getX() - 30 - paddle_x > 5)
                    english = 1.5f;
                else if (e.getX() - 30 - paddle_x < -5)
                    english = -1.5f;
                else
                    english = 1.0f;
                paddle_x = e.getX() - 30;
            }
        } );
        ball = new Ball(20);
    }

    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        Shape paddle = new Rectangle2D.Float(
            paddle_x, paddle_y, 60, 8);
        g2.setColor(color[colorIndex % 6]);
        if (ball.intersects(paddle_x, paddle_y, 60, 8)
            && ball.y_speed > 0)
        {
            ball.y_speed = -ball.y_speed;
            ball.x_speed = (int)(ball.x_speed * english);
            if (english != 1.0f)
                colorIndex++;
            score += Math.abs(ball.x_speed * 10);
        }
        if (ball.getY() + ball.getHeight()
            >= NotPong.HEIGHT)
        {
            ball = new Ball(20);
            score -= 1000;
            colorIndex = 0;
        }
        ball.move();
        g2.fill(ball);
        g2.setColor(Color.BLACK);
        g2.fill(paddle);
        g2.drawString("Score: " + score, 250, 20);
    }
}

class Ball extends Ellipse2D.Float
{
    public int x_speed, y_speed;
    private int d;
    private int width = NotPong.WIDTH;
    private int height = NotPong.HEIGHT;

    public Ball(int diameter)
    {
        super((int)(Math.random() * (NotPong.WIDTH - 20) + 1),
              0, diameter, diameter);
        this.d = diameter;
        this.x_speed = (int)(Math.random() * 5 + 5);
        this.y_speed = (int)(Math.random() * 5 + 5);
    }

    public void move()
    {
        if (super.x < 0 || super.x > width - d)
            x_speed = -x_speed;
        if (super.y < 0 || super.y > height - d)
            y_speed = -y_speed;
        super.x += x_speed;
        super.y += y_speed;
    }
}

这个程序的详细解释如下:
- NotPong 类 :
- 继承自 JApplet ,可以通过少量修改使其作为独立的 Swing 应用程序运行。
- init 方法在小程序启动时被调用,它设置小程序的大小,创建一个新的 PaintSurface 对象并添加到小程序中,然后创建并启动控制动画的线程。
- AnimationThread 类 :
- 与前面的程序中的 AnimationThread 类相同。在 run 方法中,使用 while 循环调用 repaint 方法强制动画更新,然后休眠 20 毫秒。
- PaintSurface 类 :
- 继承自 JComponent ,提供绘制动画的表面。
- 实例变量定义了球拍的初始位置、分数、应用于球的旋转(English)、球对象以及球的颜色数组和索引。
- 构造函数添加了一个鼠标运动监听器,用于更新球拍的 x 位置,并创建一个新的球对象。
- paint 方法在组件重绘时被调用,大约每 20 毫秒一次。该方法首先将图形上下文转换为 Graphics2D 对象并启用抗锯齿,然后创建球拍的 Shape 对象,检查球是否与球拍碰撞,如果碰撞则更新球的速度和颜色索引,并增加分数;如果球撞到南墙,则创建一个新球,重置颜色索引并扣除 1000 分;最后移动球、绘制球和球拍,并显示分数。
- Ball 类 :
- 与前面创建的 Ball 类类似,用于定义球的属性和移动方法。

7. 简单游戏实现步骤总结
graph TD;
    A[创建NotPong类] --> B[设置小程序大小并添加PaintSurface];
    B --> C[创建并启动动画线程];
    C --> D[创建PaintSurface类处理绘制和交互];
    D --> E[添加鼠标运动监听器更新球拍位置];
    E --> F[在paint方法中检查球与球拍碰撞];
    F --> G[根据碰撞结果更新球和分数];
    G --> H[创建Ball类定义球的属性和移动];
    H --> I[结束];
8. 游戏关键元素总结
功能 关键代码元素
小程序启动 NotPong 类的 init 方法
动画更新 AnimationThread 类的 run 方法
球拍移动 PaintSurface 类的鼠标事件监听器
球与球拍碰撞 PaintSurface 类的 paint 方法中的碰撞检测
分数计算 PaintSurface 类的 paint 方法中的分数更新
球的属性和移动 Ball 类的构造函数和 move 方法

通过以上步骤,我们成功实现了一个简单的类 Pong 游戏,从简单的弹球动画逐步引入用户交互,完成了从动画到游戏的转变。在实际应用中,可以根据需求进一步扩展和优化游戏,例如增加关卡、改变球的速度和颜色等,以提高游戏的趣味性和挑战性。

相关推荐

Cursor Agent模式下如何优雅切换conda环境运行Python脚本?3种实用方法实测

本文针对Cursor Agent模式下运行Python脚本时环境错配的痛点,实测了三种优雅切换conda环境的实用方法。通过Shell全局配置、项目级.cursorrc文件定制以及对话中直接指令,开发者可以确保AI助手在正确的虚拟环境中执行代码,从而提升开发效率和协作流畅度。

redis7keeper的博客 603

ARM Cortex-M0+调试实战:CoreSight架构、SWD接口与MTB追踪解析

在嵌入式系统开发中,调试是定位问题、优化性能的核心环节。其原理基于处理器内置的调试子系统,通过标准化接口与主机通信,实现对芯片内部状态的观测与控制。这项技术的核心价值在于,它允许开发者在不停止程序运行或仅 minimally 侵入的情况下,深入理解代码执行流程、内存访问模式及外设行为,从而显著提升复杂问题的诊断效率。典型应用场景包括实时系统行为分析、低功耗模式下的状态监控,以及死机、跑飞等疑难问题的根因定位。本文以NXP Kinetis KE1xZ64微控制器为例,深入剖析其基于ARM CoreSight的

weixin_32025789的博客 315

WordPress搭建“外贸独立站”完整操作教程

  以往的文章,我们介绍了很多种搭建独立站的方式,有最省事的Shopify 、最专业的Magento以及最省钱的Wordpress Woocommerce。其中,通过主机托管的方式又分了免费的谷歌云vps主机、1美元Godaddy主机以及SiteGround共享主机三种。建站方法方式实在太多了,有免费的,有廉价的,有商业版的,有共享主机、有云主机主机以及各种各样的vps服务器,选择哪种方式,哪款主机,也只有真正试了才直到。   没错,上述的这些方法方式,无一例外,我都亲身折腾过。从个人实际需求和建站方式来

www25qi的博客 8103

FitzHugh-Nagumo 模型连续-MATLAB仿真

【代码】FitzHugh-Nagumo 模型连续-MATLAB仿真。

qq_43688618的博客 898

Matlab:指数函数的图形比较

在上述代码中,我们使用不同的线型和颜色来区分不同的指数函数。运行代码后,我们将得到一个包含自然指数函数、以底数2的指数函数和指数衰减函数的图形比较。在本文中,我们通过Matlab代码展示了如何绘制自然指数函数、以底数2的指数函数和指数衰减函数的图形,并提供了比较不同指数函数的图形的示例代码。在本文中,我们将比较几种常见的指数函数的图形,并提供相应的Matlab源代码。图形呈现出指数增长的特征,随着x的增大,函数值呈现出快速的上升趋势。运行代码后,我们将获得以底数2的指数函数的图形。绘制自然指数函数的图形。

学习使你进步。 1452

Android 14.0 系统开机屏幕设置默认横屏显示

在14.0的系统ROM产品定制化开发中,对于产品需求来说,由于是宽屏设备所以产品需要开机默认横屏显示,开机横屏显示这就需要从 两部分来实现,一部分是系统开机动画横屏显示,另一部分是系统屏幕显示横屏显示,从这两方面就可以做到开机默认横屏显示了

安卓兼职framework和app工程师的博客 2156

OmniParser V2 和 OmniTool 让 AI 来控制 Windows 设备

OmniParser V2 和 OmniTool 是由微软开发的一套工具,通过屏幕解析技术让 AI 能够理解和控制 Windows 设备。OmniParser V2 是一款数据解析工具,可以解读屏幕内容,并将内容传递给大模型OmniTool 则是一个运行 Windows Agent 的工具,提供 Windows 界面给 AI 操作。

简简单单Onlinezuozuo 2759

YOLOv11 模型改进:利用新型损失函数实现精度跃升(含代码全解析)

在目标检测领域,损失函数的选择直接决定模型的精度上限。某自动驾驶公司将 YOLOv11 原有损失替换为新型损失后,障碍物检测 mAP 提升 10%,夜间场景误检率降低 22%;某物流分拣项目中,采用新损失的 YOLOv11 模型对小包裹的识别准确率从 82% 升至 96%。如果你也在为模型精度瓶颈、样本不平衡问题困扰,这篇教程将带你掌握 YOLOv11 损失函数的进阶技巧,真正帮你在检测性能上实现突破。损失函数是模型训练的“指南针”,它定义了模型“学习的方向”。传统损失(如 BCE、Focal Loss)在

m0_71589036的博客 726

深度学习工具包 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'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('DeepLearnToolbox'));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('state',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'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',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 = 'sigm';%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, 'Too big error');```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('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';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)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';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, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% 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'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 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, 'Too big error');```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('state',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, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',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, 'Too big error');%% ex3 neural net with dropoutrand('state',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, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % 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, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % 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, 'Too big error');%% 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('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % 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, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

上一篇: 15、IoT与混合IT的安全及管理策略
下一篇: 11、基于ICEEMDAN与迁移学习的轴承故障诊断方法研究
vim8coder
博客等级 码龄1天 0粉丝 1693原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值