paintComponent 让我压力很大; Hangman 编程项目

问题描述 投票:0回答:1

我有一个实现 Hangman 游戏的编程项目。我一次只能绘制刽子手的某些部分,这取决于用户错误尝试的次数。我的编程课老师要求刽子手绘图的创建在不同的班级。

我遇到的问题是将错误尝试的次数发送到带有

paintComponent
的班级。

if(updatedChallenge == challenge)
    {
        incorrectTries += 1;
    }
    challenge = updatedChallenge;

challenge == updatedChallenge
指的是用户猜测之前的隐藏单词和用户猜测之后的隐藏单词。如果它们仍然相等,则意味着用户做出了错误的选择。错误尝试总数增加 1。

这是我的另一堂课:

class HangmanPicture extends JPanel
{
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        g.setColor(Color.BLACK);
        g.drawLine(250, 300, 300, 300); //Platform

        g.drawLine(275, 300, 275, 200); //Pole

        g.setColor(Color.YELLOW);
        g.drawLine(275, 200, 350, 200); //Rope

        g.drawLine(350, 200, 350, 225); //Noose

        g.setColor(Color.CYAN);
        g.drawOval(350, 225, 15, 15); //Head

        g.drawLine(350, 230, 350, 260); //Torso

        g.drawLine(350, 240, 340, 230); //Left Arm

        g.drawLine(350, 240, 360, 230); // Right Arm

        g.drawLine(350, 260, 330, 280); // Left Leg

        g.drawLine(350, 260, 390, 280); // Right Leg
    }
}

我想添加一个

if
语句,其中每个身体部位都会在每次错误尝试后添加,这需要我将错误尝试的次数发送给班级。每当我尝试发送号码时,它总是会以某种方式干扰
paintComponent

java object paint paintcomponent
1个回答
0
投票

由于您要扩展

JPanel
类,我们可以向该类添加额外的方法和字段,并在使用
HangmanPicture
的地方使用它们。

HangmanPicture panel = new HangmanPicture();
  ...
  if(updatedChallenge == challenge)
  {
      panel.addIncorrectAttempt();
  }
  challenge = updatedChallenge; 


class HangmanPicture extends JPanel
{
    private int incorrectAttempts = 0;

    // Add one to counter
    public void addIncorrectAttempt(){
      incorrectAttempte++;
    }

    // Get how many times the player entered an incorrect number
    public int getIncorrectAttempts(){
      return incorrectAttempts;
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        g.setColor(Color.BLACK);
        if( incorrectAttempts >= 1 ){
          g.drawLine(250, 300, 300, 300); //Platform
        }

        if( incorrectAttempts >= 2 ){
          g.drawLine(275, 300, 275, 200); //Pole
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.