实际上我想在java中制作一条蛇,而且我必须在我的框架中为蛇的身体放置图像。我搜索解决方案,但没有一个有效,我尝试了 jlabel,或者只是一个图像,它做的事情完全相同。在搜索了一些 github 页面后,我发现我在其他地方遇到了问题,因为我有相同的图像代码。
这是我的代码:
private ImageIcon upMouth;
private ImageIcon downMouth;
private ImageIcon leftMouth;
private ImageIcon rightMouth;
private ImageIcon body;
private ImageIcon dot;
private int[] lensnakeX = new int[750];
private int[] lensnakeY = new int[750];
private int moves = 0;
private int length = 3;
private boolean left = false;
private boolean up = false;
private boolean down = false;
private boolean right = false;
private Timer t;
private int delay = 140;
public Content(){
initGame();
}
public void initGame(){
setBackground(Color.GRAY);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
t = new Timer(delay, this);
t.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
public void doDrawing(@NotNull Graphics g){
if(moves == 0){
lensnakeX[2] = 50;
lensnakeX[1] = 75;
lensnakeX[0] = 100;
lensnakeY[2] = 100;
lensnakeY[1] = 100;
lensnakeY[0] = 100;
}
//title
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.WHITE);
g.fillRect(24,10, 851, 55);
Font f = new Font("Serif", Font.PLAIN, 60);
g2d.setFont(f);
g2d.setColor(Color.BLACK);
g2d.drawString("Snake", 375, 55);
//gameplay
g.setColor(Color.BLACK);
g.fillRect(24, 74, 851, 600);
//background
g.setColor(Color.black);
g.drawRect(25, 75, 850, 575);
for (int i = 0; i < length; i++) {
if(i == 0 && right){
rightMouth = new ImageIcon("src/resources/right.png");
rightMouth.paintIcon(this, g, lensnakeX[i], lensnakeY[i]);
}
if(i == 0 && left){
leftMouth = new ImageIcon("src/resources/left.png");
leftMouth.paintIcon(this, g, lensnakeX[i], lensnakeY[i]);
}
if(i == 0 && up){
upMouth = new ImageIcon("src/resources/up.png");
upMouth.paintIcon(this, g, lensnakeX[i], lensnakeY[i]);
}
if(i == 0 && down){
downMouth = new ImageIcon("src/resources/down.png");
Image image = downMouth.getImage();
downMouth.paintIcon(this, g, lensnakeX[i], lensnakeY[i]);
}
if(i != 0){
body = new ImageIcon("src/resources/body.png");
body.paintIcon(this, g, lensnakeX[i], lensnakeY[i]);
}
}
g.dispose();
}```
The expected result is a snake with 3 parts (1 head and 2 parts for the body), but i've only got a jframe with a black rect, and a white rect for the title with "Snake" in it. Thank you for taking time to answer.