public class Game extends Canvas implements Runnable { private static final long serialVersionUID = 1L; public void run() { // run , "implements Runnable" } public static void main(String[] args) { } }
public void start() { running = true; new Thread(this).start(); }
public void run() { long lastTime = System.currentTimeMillis(); long delta; init(); while(running) { delta = System.currentTimeMillis() - lastTime; lastTime = System.currentTimeMillis(); update(delta); render(); } } public void init() { } public void render() { } public void update(long delta) { }
public void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(2); // BufferStrategy requestFocus(); return; } Graphics g = bs.getDrawGraphics(); // Graphics BufferStrategy g.setColor(Color.black); // g.fillRect(0, 0, getWidth(), getHeight()); // g.dispose(); bs.show(); // }
public static int WIDTH = 400; // public static int HEIGHT = 300; // public static String NAME = "TUTORIAL 1"; // public static void main(String[] args) { Game game = new Game(); game.setPreferredSize(new Dimension(WIDTH, HEIGHT)); JFrame frame = new JFrame(Game.NAME); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // ESC frame.setLayout(new BorderLayout()); frame.add(game, BorderLayout.CENTER); // frame.pack(); frame.setResizable(false); frame.setVisible(true); game.start(); }
import java.awt.Graphics; import java.awt.Image; public class Sprite { private Image image; // public Sprite(Image image) { this.image = image; } public int getWidth() { // return image.getWidth(null); } public int getHeight() { // return image.getHeight(null); } public void draw(Graphics g,int x,int y) { // g.drawImage(image,x,y,null); } }
public Sprite getSprite(String path) { BufferedImage sourceImage = null; try { URL url = this.getClass().getClassLoader().getResource(path); sourceImage = ImageIO.read(url); } catch (IOException e) { e.printStackTrace(); } Sprite sprite = new Sprite(Toolkit.getDefaultToolkit().createImage(sourceImage.getSource())); return sprite; }
// "" public static Sprite hero; // init() hero = getSprite("man.png"); // render() g.fillRect(0, 0, getWidth(), getHeight()); hero.draw(g, 20, 20);
private class KeyInputHandler extends KeyAdapter { }
private boolean leftPressed = false; private boolean rightPressed = false;
public void keyPressed(KeyEvent e) { // if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = true; } } public void keyReleased(KeyEvent e) { // if (e.getKeyCode() == KeyEvent.VK_LEFT) { leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { rightPressed = false; } }
addKeyListener(new KeyInputHandler());
private static int x = 0; private static int y = 0; hero.draw(g, x, y);
public void update(long delta) { if (leftPressed == true) { x--; } if (rightPressed == true) { x++; } }
Source: https://habr.com/ru/post/145433/
All Articles