使用Java来模拟《宝可梦》的震撼情节
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
public class Pokemonshock {
public static void main(String[] args) {
Pokemonshock gtm = new Pokemonshock();
gtm.start();
}
JFrame mainwindow;
BufferStrategy strategy;
Boolean apple=true;
//コンストラクタ
Pokemonshock(){
this.mainwindow=new JFrame("Pokemonshock");
this.mainwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainwindow.setSize(1280,720);
this.mainwindow.setLocationRelativeTo(null);
this.mainwindow.setVisible(true);
this.mainwindow.setResizable(false);
//バッファストラテジー
this.mainwindow.setIgnoreRepaint(true);
this.mainwindow.createBufferStrategy(2);
this.strategy=this.mainwindow.getBufferStrategy();
}
void start(){
//intervalミリ秒毎にrunメソッドが呼ばれる
Timer t=new Timer();
long interval=(1000/12);
TimerTask task=new RenderTask();
t.schedule(task,0,interval);
}
void render(){
Graphics2D g=(Graphics2D)this.strategy.getDrawGraphics();
//背景色の指定
if(apple){
g.setBackground(Color.RED);
}else{
g.setBackground(Color.BLUE);
}
//反転させる
apple=!apple;
g.clearRect(0, 0,this.mainwindow.getWidth(), this.mainwindow.getHeight());
g.dispose();
this.strategy.show();
}
class RenderTask extends TimerTask{
@Override
public void run() {
Pokemonshock.this.render();
}
}
}
环境
裸机:Shuttle XS35GS V3
操作系统:Win7(32位)
JAVA SE8(jdk-8u45-windows-i586)
请留意
请注意,运行此程序可能会引发光过敏性发作。此外,我将提供如何将屏幕闪烁降至最低级别的方法。红色和蓝色屏幕切换的默认频率是每秒12次,但以下方法可将其更改为每秒1次。
long interval=(1000/12);
// ↓ 12から1に変える
long interval=(1000/1);
说明
这次选择了《宝可梦震撼,红蓝激烈闪烁》作为学习Java实时处理的素材。
在实时处理中,使用的是TimerTask类和TimerTask类的run方法。
TimerTask类是一个抽象类,TimerTask类的run方法是一个抽象方法。由于抽象类无法创建对象,所以必须继承TimerTask类并将其命名为RenderTask类,并且需要重写使用run方法。run方法每秒被调用12次。
执行结果
c:\2015>javac Pokemonshock.java
c:\2015>java Pokemonshock
c:\2015>
后记
1997年发生了一起名为“宝可梦冲击”的事件,当时有一个孩子因为观看了《口袋妖怪》第38集“电脑战士多边兽”的红色和蓝色闪烁的强烈光线而患上光过敏性发作,被送进了医院。当时我还是小学生,对宝可梦非常痴迷,但因为住在乡下,无法收到东京电视台的节目,只能在当地台观看稍稍滞后的宝可梦剧集,所以我并没有看到这第38集。由于这起事件,宝可梦暂时停播,取而代之的是在我所观看的当地台上播出的《学级王山崎》节目。