Home How to determine a winner in Hangman Game?
Reply: 0

How to determine a winner in Hangman Game?

user6626
1#
user6626 Published in May 27, 2018, 3:34 am

I have created a Hangman game in Android Studio. It is working as it should be when drawing down the letters to form the words etc. and the number of tries remaining.

i am stuck on determining when the player has won in the logic to prompt an AlertDialog box and start a new game. Appreciate if some light can be shed on how i can do this?

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();
}

}

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314431 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO