【发布时间】:2021-05-23 13:12:48
【问题描述】:
我正在尝试用 Java 制作基于图块的游戏,但我注意到绘图存在问题。一些图块之间大约有一个像素的间隙,我不确定是什么原因造成的。
这是它的截图:
到目前为止,这是我的代码:
主类:
package Game.main;
import javax.swing.JFrame;
public class Main {
public static JFrame window;
public static void main(String[] args) {
window = new JFrame();
window.setVisible(true);
window.setSize(1280, 720);
window.setTitle("Game");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Game game = new Game();
window.add(game);
}
}
游戏类:
package Game.main;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.util.ArrayList;
import Game.tile.Tile;
public class Game extends JPanel implements Runnable {
public Game() {
start();
}
boolean running = false;
int width,height;
ArrayList<Tile> tiles = new ArrayList<>();
public void paint(Graphics g1) {
//cast to graphics2d
Graphics2D g = (Graphics2D)g1;
//fill background
g.setColor(Color.CYAN);
g.fillRect(0, 0, width, height);
//draw tiles
for(int i = 0; i < tiles.size(); i++) {
tiles.get(i).render(g, width, height);
}
}
private void start() {
Thread gameThread = new Thread(this);
gameThread.start();
//create start tiles
for(int x = 0; x < 1000; x+=10) {
for(int y = 700; y < 1000; y+=20) {
Tile tile = new Tile(x, y);
tiles.add(tile);
}
}
}
@Override
public void run() {
running = true;
while(running) {
//get window width and height
requestFocus();
width = Main.window.getWidth();
height = Main.window.getHeight();
//redraw current frame
repaint();
}
}
}
瓷砖类:
package Game.tile;
import java.awt.Graphics2D;
import java.awt.Color;
public class Tile {
public int x,y;
public int w,h;
public Tile(int x, int y) {
this.x = x;
this.y = y;
this.w = 10;
this.h = this.w*2;
}
public void render(Graphics2D g, int width, int height) {
g.setColor(Color.GRAY);
g.fillRect(this.x*width/1000, this.y*height/1000, this.w*width/1000, this.h*height/1000);
}
}
【问题讨论】:
标签: java graphics awt rendering tile