gpt4 book ai didi

java - 开始 : Applet Not Initialized Checkers Game

转载 作者:行者123 更新时间:2023-12-02 04:11:18 25 4
gpt4 key购买 nike

所以我正在开发一个玩西洋跳棋游戏的小程序,在这个阶段我只是尝试设置棋盘。我的代码可以编译,但是当我打开 AppletViewer 时,我收到一条消息“启动:Applet 未初始化”。知道为什么吗?

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class CheckerGame extends Applet implements MouseListener {
int player = 1;
Checker [] [] board = new Checker [8][8];
int mouseX = -200;
int mouseY = -200;
int col;
int row;

Image whiteChecker;
Image redChecker;
Image boardBG;
Image whiteKing;
Image redKing;
public void init()
{
this.addMouseListener(this);
boardBG=this.getImage(this.getCodeBase(),"checkerboard.jpg");
whiteChecker = this.getImage(this.getCodeBase(),"whiteChecker.png");
redChecker = this.getImage(this.getCodeBase(),"redChecker.png");
whiteKing = this.getImage(this.getCodeBase(),"whiteKing.png");
redKing = this.getImage(this.getCodeBase(),"redKing.png");
for(int r = 0; r < 8; r++)
{
for (int c = 0; c < 8; c++)
{
if(r < 3 && r%2 == 0 && c%2 == 1)
{
board[r][c].setPlayer(2);
board[r][c].setKing(false);
}
else if (r == 1 && c%2 == 0)
{
board[r][c].setPlayer(2);
board[r][c].setKing(false);
}
else if (r > 4 && r%2 == 1 && c%2 == 0)
{
board[r][c].setPlayer(1);
board[r][c].setKing(false);
}
else if (r == 6 && c%2 == 1)
{
board[r][c].setPlayer(1);
board[r][c].setKing(false);
}
else
{
board[r][c].setPlayer(0);
board[r][c].setKing(false);
}
}
}
this.setLayout(null);
}

public void mouseClicked(MouseEvent e) {
mouseX=e.getX();
mouseY=e.getY();
col = (mouseX-100)/100;
row = (mouseY-100)/100;
}

public void mousePressed(MouseEvent e) {
}

public void mouseReleased(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void paint(Graphics g)
{
g.drawImage(boardBG,100,100,800,800,this);
for(int r = 0; r < 7; r++)
{
for(int c = 0; c < 7; c++)
{
if(board[r][c].getPlayer() == 2 && board[r][c].getKing() == false)
{
g.drawImage(whiteChecker,100+100*c,100+100*r,40,40,this);
}
else if(board[r][c].getPlayer() == 2 && board[r][c].getKing() == true)
{
g.drawImage(whiteKing,100+100*c,100+100*r,40,40,this);
}
if(board[r][c].getPlayer() == 1 && board[r][c].getKing() == false)
{
g.drawImage(redChecker,100+100*c,100+100*r,40,40,this);
}
else if(board[r][c].getPlayer() == 1 && board[r][c].getKing() == true)
{
g.drawImage(redKing,100+100*c,100+100*r,40,40,this);
}
}
}
}

}

最佳答案

Vollmilchbb 是正确的。 init() 方法出错。

您犯了一个基本的 Java 错误。虽然您已经创建了一个 Checker 数组,但尚未实例化这些元素。尽管您没有在此处向我们展示您的输出日志(控制台日志),但您会在这些日志中发现 NullPointerException

它只是代码的一部分,但将下面的代码放在 init() 方法中的 if block 内即可完成这项工作。

board[r][c] = new Checker()

规则:
Java 中的对象数组(除了像字符串数组这样的最终类对象数组)只是为数组声明的类型的对象提供占位符(可以说是指针)。在访问它们之前,您必须设置一个对象或实例化一个新对象。

关于java - 开始 : Applet Not Initialized Checkers Game,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33761737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com