从数组中删除一个单词

时间:2014-05-09 20:02:18

标签: java android

我根据这里的教程构建了一个刽子手游戏。它从数组中为游戏选择一个随机单词。设置为不连续两次选择相同的单词。问题是它会在玩几个游戏时多次选择相同的单词。有没有办法标记或标记一个单词,所以在它被使用一次之后,它不会在同一个游戏会话中再次使用?

我想我需要一个ArrayList,但我无法弄清楚代码。我一直在寻找和尝试一周,但我无法得到它。我真的很努力地找到自己的答案。

完整代码

package com.slideproud.hangman;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;



public class GameActivity extends Activity {

//the words
private String[] words;
//random for word selection
private Random rand;
//store the current word
private String currWord;
//the layout holding the answer
private LinearLayout wordLayout;
//text views for each letter in the answer
private TextView[] charViews;
//letter button grid
private GridView letters;
//body part images
private ImageView[] bodyParts;
//total parts
private int numParts = 6;
//current part
private int currPart;
//num chars in word
private int numChars;
//num correct so far
private int numCorr;
//help
private AlertDialog helpAlert;

public GameActivity() {
}
//body part images



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

//read answer words in
    Resources res = getResources();
    ArrayList<String> words = new ArrayList<String>();
    words.addAll(Arrays.asList(res.getStringArray(R.array.words)));
//initialize random
    rand = new Random();
//initialize word


    //read answer words in
   // Resources res = getResources();
   // words = res.getStringArray(R.array.words);
   //initialize random
    //rand = new Random();
    //initialize word
   // currWord = "";

    //get answer area
    wordLayout = (LinearLayout) findViewById(R.id.word);

    //get letter button grid
    letters = (GridView) findViewById(R.id.letters);

    //get body part images
    bodyParts = new ImageView[numParts];
    bodyParts[0] = (ImageView) findViewById(R.id.head);
    bodyParts[1] = (ImageView) findViewById(R.id.body);
    bodyParts[2] = (ImageView) findViewById(R.id.arm1);
    bodyParts[3] = (ImageView) findViewById(R.id.arm2);
    bodyParts[4] = (ImageView) findViewById(R.id.leg1);
    bodyParts[5] = (ImageView) findViewById(R.id.leg2);




    //start gameplay
    playGame();

}

@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;
}

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

private void playGame() {
    //choose a word
    int random = rand.nextInt(words.length);
    String newWord = words.get(random);
    words.remove(random);
    currWord = newWord;


//play a new game
//private void playGame() {

    //choose a word
    //String newWord = words[rand.nextInt(words.length)];
    //make sure not same word as last time
   // while (newWord.equals(currWord)) newWord = words[rand.nextInt(words.length)];
    //update current word
    //newWord.remove(0);
    //currWord = newWord;

    //create new array for character text views
    charViews = new TextView[currWord.length()];

    //remove any existing letters
    wordLayout.removeAllViews();
    //loop through characters
    for (int c = 0; c < currWord.length(); c++) {
        charViews[c] = new TextView(this);
        charViews[c].setText(""+currWord.charAt(c));

        charViews[c].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        charViews[c].setGravity(Gravity.CENTER);
        charViews[c].setTextColor(Color.WHITE);
        charViews[c].setBackgroundResource(R.drawable.letter_bg);
        //add to layout
        wordLayout.addView(charViews[c]);
    }


    //reset adapter
    LetterAdapter ltrAdapt = new LetterAdapter(this);
    letters.setAdapter(ltrAdapt);

    //start part at zero
    currPart = 0;
    //set word length and correct choices
    numChars = currWord.length();
    numCorr = 0;

    //hide all parts
    for (int p = 0; p < numParts; p++) {
        bodyParts[p].setVisibility(View.INVISIBLE);
    }
}

//letter pressed method
public void letterPressed(View view) {
    //find out which letter was pressed
    String ltr = ((TextView) view).getText().toString();
    char letterChar = ltr.charAt(0);
    //disable view
    view.setEnabled(false);
    view.setBackgroundResource(R.drawable.letter_down);
    //check if correct
    boolean correct = false;
    for (int k = 0; k < currWord.length(); k++) {
        if (currWord.charAt(k) == letterChar) {
            correct = true;
            numCorr++;
            charViews[k].setTextColor(Color.BLACK);
        }
    }
    //check in case won
    if (correct) {
        if (numCorr == numChars) {
            //disable all buttons
            disableBtns();
            //let user know they have won, ask if they want to play again
            AlertDialog.Builder winBuild = new AlertDialog.Builder(this);
            winBuild.setTitle("YAY");
            winBuild.setMessage("You win!\n\nThe answer was:\n\n" + currWord);
            winBuild.setPositiveButton("Play Again",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            GameActivity.this.playGame();
                        }
                    }
            );
            winBuild.setNegativeButton("Exit",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            GameActivity.this.finish();
                        }
                    }
            );
            winBuild.show();
        }
    }
    //check if user still has guesses
    else if (currPart < numParts) {
        //show next part
        bodyParts[currPart].setVisibility(View.VISIBLE);
        currPart++;
    } else {
        //user has lost
        disableBtns();
        //let the user know they lost, ask if they want to play again
        AlertDialog.Builder loseBuild = new AlertDialog.Builder(this);
        loseBuild.setTitle("OOPS");
        loseBuild.setMessage("You lose!\n\nThe answer was:\n\n" + currWord);
        loseBuild.setPositiveButton("Play Again",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        GameActivity.this.playGame();
                    }
                }
        );
        loseBuild.setNegativeButton("Exit",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        GameActivity.this.finish();
                    }
                }
        );
        loseBuild.show();
    }
}

//disable letter buttons
public void disableBtns() {
    int numLetters = letters.getChildCount();
    for (int l = 0; l < numLetters; l++) {
        letters.getChildAt(l).setEnabled(false);
    }
}

//show help information
public void showHelp() {
    AlertDialog.Builder helpBuild = new AlertDialog.Builder(this);
    helpBuild.setTitle("Help");
    helpBuild.setMessage("Guess the word by selecting the letters.\n\n"
            + "You only have 6 wrong selections then it's game over!");
    helpBuild.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    helpAlert.dismiss();
                }
            }
    );
    helpAlert = helpBuild.create();
    helpBuild.show();
}

public void setWords(String[] words) {
    this.words = words;
}
}

这是我的错误 错误:任务'执行失败':HangMan:compileDebugJava'。

  

编译失败;请参阅编译器错误输出以获取详细信   ... \ AndroidStudioProjects \刽子手的\ src \主\ java中的\ com \ slideproud \刽子手\ GameActivity.java   错误:(128,31)找不到符号方法get(int)   错误:(129,14)找不到符号方法remove(int)

这些是我的警告

errors pic

3 个答案:

答案 0 :(得分:2)

你应该使用ArrayList

Resources res = getResources();
ArrayList<String> words = new ArrayList<String>;
words.addAll(Arrays.asList(res.getStringArray(R.array.words)));
//initialize random
rand = new Random();
//initialize word

然后你可以在得到之后删除它:

private void playGame() {
    //choose a word
    int random = rand.nextInt(words.size ());
    String newWord = words.get(random);
    words.remove(random);
    currWord = newWord;

修改

您必须更改words的范围,而不是:

public class GameActivity extends Activity {

    //the words
    private String[] words;
    //random for word selection
    private Random rand;

必须是:

public class GameActivity extends Activity {

    //the words
    ArrayList<String> words;
    //random for word selection
    private Random rand;

在您的onCreate()中,您只需初始化单词:

Resources res = getResources();
words = new ArrayList<String>;
words.addAll(Arrays.asList(res.getStringArray(R.array.words)));
//initialize random
rand = new Random();
//initialize word

答案 1 :(得分:0)

ArrayList提供了添加和删除任何内容的功能。

您可以尝试类似

的内容
ArrayList<String> words = new ArrayList<String>();
words.add("any_word");
words.remove(i);   //i is the index of the word which you want to remove

答案 2 :(得分:0)

更改

Resources res = getResources(); words = res.getStringArray(R.array.words); //initialize random rand = new Random(); //initialize word currWord = "";

Resources res = getResources(); words = (ArrayList<String>) Arrays.asList(res.getStringArray(R.array.words)); //initialize random rand = new Random();

(感谢Hossam的代码) 因此,您的单词将存储在ArrayList中,而不是常规的String数组。现在您已经掌握了词语,您可以将playGame()方法更改为:

private void playGame() {

//this is the line that makes sure no words are reused, it removes the current word before a new one is picked
words.remove(currWord);

//choose a word
currWord = words.get(rand.nextInt(words.size());

就是这样,除非你从资源中重新加载arraylist这个词,否则你不应该在游戏中重复说话。如果这篇文章的其他代码有任何问题,那么我们可以看到出了什么问题。