Java游戏开发:实现暂停功能
private boolean isPaused = false;//添加一个标志位记录游戏是否暂停
public void paintComponent(Graphics g){
super.paintComponent(g);//画棋盘
int imgWidth= img.getWidth(this);
int imgHeight=img.getHeight(this);//获得图片的宽度与高度
int FWidth=getWidth();
int FHeight=getHeight();//获得窗口的宽度与高度
int x=(FWidth-imgWidth)/2;
int y=(FHeight-imgHeight)/2;
g.drawImage(img, x, y, null);
for(int i=0;i<=ROWS;i++){//画横线
for(int j=0;j<COLS;j++) {
g.drawLine(MARGIN, MARGIN + i * GRID_SPAN, MARGIN + COLS * GRID_SPAN, MARGIN + i * GRID_SPAN);
}
}
//判断游戏是否暂停,如果暂停则不进行绘制
if(!isPaused){//如果游戏未暂停,进行绘制
for(int i=0;i<=COLS;i++){//画竖线
g.drawLine(MARGIN+i*GRID_SPAN, MARGIN, MARGIN+i*GRID_SPAN, MARGIN+ROWS*GRID_SPAN);
}
//画棋子
for(int i=0;i<chessCount;i++){
//网格交叉点x,y坐标
int xPos=chessList[i].getX()*GRID_SPAN+MARGIN;
int yPos=chessList[i].getY()*GRID_SPAN+MARGIN;
g.setColor(chessList[i].getColor());//设置颜色
// g.fillOval(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2,
//Point.DIAMETER, Point.DIAMETER);
//g.drawImage(shadows, xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER, null);
colortemp=chessList[i].getColor();
if(colortemp==Color.black){
RadialGradientPaint paint = new RadialGradientPaint(xPos-Point.DIAMETER/2+25, yPos-Point.DIAMETER/2+10, 20, new float[]{0f, 1f}
, new Color[]{Color.WHITE, Color.BLACK});
((Graphics2D) g).setPaint(paint);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);
}
else if(colortemp==Color.white){
RadialGradientPaint paint = new RadialGradientPaint(xPos-Point.DIAMETER/2+25, yPos-Point.DIAMETER/2+10, 70, new float[]{0f, 1f}
, new Color[]{Color.WHITE, Color.BLACK});
((Graphics2D) g).setPaint(paint);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);
}
Ellipse2D e = new Ellipse2D.Float(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, 34, 35);
((Graphics2D) g).fill(e);
//标记最后一个棋子的红矩形框
if(i==chessCount-1){//如果是最后一个棋子
g.setColor(Color.red);
g.drawRect(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2,
34, 35);
}
}
}else{//如果游戏已暂停,绘制提示语
Font font=new Font("黑体",Font.BOLD,20);
g.setFont(font);
g.setColor(Color.red);
g.drawString("当前游戏处于暂停模式,请点击继续按钮继续游戏", 100, 300);
}
}
//添加暂停和继续按钮的事件监听
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("暂停")) {
isPaused = true;//将游戏状态标志置为暂停
} else if (command.equals("继续")) {
isPaused = false;//将游戏状态标志置为继续
}
}
代码中,通过isPaused标志位判断游戏是否处于暂停状态。如果游戏已暂停,则不会进行绘制操作,并绘制提示语;如果游戏未暂停,则正常进行绘制。同时,代码添加了暂停和继续按钮的事件监听,通过按钮点击改变isPaused标志位,实现游戏暂停和继续功能。
希望以上代码和解释能够帮助你实现Java游戏开发中的暂停功能!
原文地址: https://www.cveoy.top/t/topic/ozSO 著作权归作者所有。请勿转载和采集!