Skip to content

Instantly share code, notes, and snippets.

@sota1235
Last active August 29, 2015 14:13
Show Gist options
  • Save sota1235/4d9e6fe4dded422affea to your computer and use it in GitHub Desktop.
Save sota1235/4d9e6fe4dded422affea to your computer and use it in GitHub Desktop.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class Maru extends JFrame implements KeyListener, Runnable {
public int width = 800, height = 600; // 画面サイズ
public int x = width/2, y = height/2; // 主人公座標
public int size = 50; // 円のサイズ
public int range = 5; // 移動幅
public int interval = 20; // 描画の間隔
public boolean right = false; // 右方向のフラグ
public boolean left = false; // 左方向のフラグ
public static void main(String[] args) {
Maru f = new Maru();
}
public Maru() {
//フレーム作成
this.setSize(this.width, this.height);
this.setVisible(true);
addKeyListener(this);
new Thread(this).start();
}
public void paint(Graphics g) {
// 背景色で塗りつぶし
g.clearRect(0, 0, this.width, this.height);
// 円表示
g.drawOval(this.x, this.y, this.size, this.size);
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
// 方向キーで制御
if(key == KeyEvent.VK_RIGHT) {
right = true;
//x += this.range;
} else if(key == KeyEvent.VK_LEFT) {
//is.x -= this.range;
left = true;
} else if(key == KeyEvent.VK_UP) {
this.y -= this.range;
} else if(key == KeyEvent.VK_DOWN) {
this.y += this.range;
}
// 画面の中に納まっているか判定
if(this.x < 0) {
this.x = 0;
} else if (x > this.width - this.size) {
this.x = this.width - this.size;
} else if (y < 0) {
this.y = 0;
} else if (y > this.height - this.size) {
this.y = this.height - this.size;
}
// paint()を実行
//repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
right = false;
left = false;
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
if(right) {
x += range;
}
if(left) {
x -= range;
}
repaint();
try {
Thread.sleep(interval);
} catch(Exception e) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment