如何确定Hangman游戏中的赢家?

时间:2018-05-17 06:22:10

标签: java android

我在Android Studio中创建了一个Hangman游戏。在绘制字母以形成单词等以及剩余的尝试次数时,它应该正常工作。

我坚持确定玩家何时赢得了提示AlertDialog框并开始新游戏的逻辑。如果我可以做到这一点,可以了解一些亮点吗?

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AlertDialogLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import java.util.Random;

public class GameActivity extends AppCompatActivity {

//To reference the components
ImageSwitcher imageSwitcher;
TextView textView;
TextView textViewScore;
Button btn [] = new Button[26];

AlertDialog helpAlert;

//Images for the hangman
int img [] = {R.drawable.img0,
        R.drawable.img1,
        R.drawable.img2,
        R.drawable.img3,
        R.drawable.img4,
        R.drawable.img5,
        R.drawable.img6,
        R.drawable.img7,
        R.drawable.img8};

//Variables
String strSecret = "", strGuess="", strText="";

String strWords[] = {"APPLE", "ORANGE","BANANA"};

int intError = 0; //Error made by player

int livesRemaining = 8; //Lives remaining by player

Random random = new Random(); //Random generator


//To create help icon at top right
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

//To create help icon at top right
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        //case android.R.id.home:
           // NavUtils.navigateUpFromSameTask(this);
            //return true;
        case R.id.action_help:
            showHelp();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    //Retrieve the reference
    imageSwitcher = findViewById(R.id.imageSwitcher);
    textView = findViewById(R.id.textView);
    textViewScore = findViewById(R.id.textViewScore);
    textViewScore.setText(String.valueOf(livesRemaining));
    setupImageSwitcher();
    setup26Buttons();
    getSecretWord();

}


private void setup26Buttons() {

    GridLayout g = findViewById(R.id.gridLayout);


    //to create 26 buttons
    for(int i = 0; i<btn.length; i++) {

        btn[i] =new Button(this, null, R.attr.buttonStyleSmall); //Buttonsytlesmall so that it fits the screen
        btn[i].setText(""+(char)('A'+i)); //need to set back to char, as +i will set it back to integer. "" to set this to a String so it is sync to setText
        btn[i].setTag(""+(char)('A'+i));
        btn[i].setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onClick(View v) {

                strGuess += v.getTag(); //Get letter that the player guessed and keep adding on to strGuess
                v.setEnabled(false); //disable pressed button since the player already press
                v.setBackgroundColor(android.R.color.black);

                //Check for error guess. If the letter is not inside the strSecret, it will return less than 0
                if (strSecret.indexOf(v.getTag().toString())<0){

                    intError++; //your error is added
                    int livesRemaining = 8;
                    livesRemaining -= intError; // Countdown based on errors recorded
                    textViewScore.setText(String.valueOf(livesRemaining));
                    imageSwitcher.setImageResource(img[intError]); //set the img no. to follow the error
                }

                //Display all correct guesses
                strText = ""; //reset the display

                for (int i = 0 ; i<strSecret.length();i++){

                    char ch = strSecret.charAt(i); // get each character from strSecret

                    //To check if this letter can be found in strGuess
                    if(strGuess.indexOf(ch)>=0){
                        //found
                        strText += ch;

                    }

                    else{

                        //Not found
                        strText += "-";
                    }

                }

                textView.setText(strText);

            }

        });



        g.addView(btn[i]);

    }

}

private void getSecretWord() {

    int index = random.nextInt(strWords.length);
    strSecret = strWords[index];

    for(int i=0; i<strSecret.length(); i++) {

        strText += "-"; //to create multiple - for the unknown word

    }

    textView.setText(strText);


}

private void setupImageSwitcher() {

    //https://www.tutorialspoint.com/android/android_imageswitcher.htm
    imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

        @Override
        public View makeView() {

            ImageView imageView = new ImageView(getApplicationContext());

            imageView.setImageResource(R.drawable.img0);

            return imageView;
        }
    });

    Animation aniOut = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

    Animation aniIn = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);

    imageSwitcher.setOutAnimation(aniOut);

    imageSwitcher.setOutAnimation(aniIn);
}

//show help information
public void showHelp(){
    AlertDialog.Builder helpBuild = new AlertDialog.Builder(this);
    helpBuild.setTitle("Help");
    helpBuild.setMessage("Whisper the password (Hangman's favourite fruit) to save Batman\n\n"
            + "You only have 8 tries!");
    helpBuild.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    helpAlert.dismiss();
                }});
    helpAlert = helpBuild.create();
    helpBuild.show();
}

}

1 个答案:

答案 0 :(得分:2)

您可以在onClickListener onClick方法中添加布尔标记。示例代码:

// Display all correct guesses
String strText = ""; // reset the display
boolean allFound = true;

for (int i = 0; i < strSecret.length(); i++)
{
    char ch = strSecret.charAt(i); // get each character from strSecret

    // To check if this letter can be found in strGuess
    if (strGuess.indexOf(ch) >= 0)
    {
        // found
        strText += ch;
    }
    else
    {
        // Not found
        strText += "-";
        allFound = false;
    }

}

if(allFound)
{
    // Word was guessed correctly
    [...]
}

allFound是一个布尔标志,默认为true。如果找不到一个猜到的字符,则将其设置为false。循环完整的单词后,检查它是否仍然是真的,这意味着没有找到任何字符,这反过来意味着每个字符都被找到。

在这种情况下,您可以确定您的单词被正确猜测并且可以采取相应的行动。