我创造了简单的安卓游戏。如果球员未能在3分钟内回答所有10个问题。将弹出一个针对totalGuesses的alertDialog,游戏将终止。我的问题是如何添加计时器,任何修改此代码将不胜感激:) 以下是所有代码:
NewgameActivity.class
public class NewgameActivity extends Activity{
private static final String TAG = "NewgameActivity Activity";
private List<String> fileNameList; //game file name
private List<String> quizAnswerList; //answer
private Map<String, Boolean> gamesMap; //which game enable
private String correctAnswer; //correct answer
private int totalGuesses; //no of guesses made
private int correctAnswers; //no of correct guesses
private Random random; //random no generator
private Handler handler; //used to delay loading next image
private Animation shakeAnimation; //for incorrect guesses
private int guessRows;
private TextView answerTextView; //display correct and incorrect
private TextView questionNumberTextView;
private ImageView imageImageView; //display image
private TableLayout buttonTableLayout; //table for answer button
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newgame);
fileNameList = new ArrayList<String>(); //list of image
quizAnswerList = new ArrayList<String>();
gamesMap = new HashMap<String, Boolean>();
guessRows=2;
random = new Random(); //random number generator
handler = new Handler();
//load the shake animation for incorrect answer
shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.incorrect_shake);
shakeAnimation.setRepeatCount(3);//animation repeat 3x
//array of games from string.xml
String[] gameNames = getResources().getStringArray(R.array.gameList);
//by default, answer are chosen from all games
for (String game : gameNames)
gamesMap.put(game, true);
//get references to GUI components
questionNumberTextView = (TextView) findViewById(R.id.questionNumberTextView);
imageImageView = (ImageView) findViewById(R.id.imageImageView);
buttonTableLayout = (TableLayout) findViewById(R.id.buttonTableLayout);
answerTextView = (TextView) findViewById(R.id.answerTextView);
//set questionNumberTextView's text
questionNumberTextView.setText(getResources().getString(R.string.question) + " 1 " +
getResources().getString(R.string.of) + " 10");
resetQuiz(); //start a new Game
}
//set up and start the next game
private void resetQuiz(){
//use the Assetmanager to get the image game
//file name for the only enable game
AssetManager assets = getAssets();
fileNameList.clear();//empty the list
try
{
Set<String> games = gamesMap.keySet(); //get set of games
//loop through each game
for (String game : games)
{
if (gamesMap.get(game))
{
String[] paths = assets.list(game);
for (String path : paths)
fileNameList.add(path.replace(".png", ""));
}
}
}
catch (IOException e)
{
Log.e(TAG, "Error loading image file names", e);
}
correctAnswers = 0; //reset the correct answer made
totalGuesses = 0; //reset total
quizAnswerList.clear();
//add 10 random file name to quizAnswerList
int imageCounter = 1;
int numberOfImages = fileNameList.size();
while (imageCounter <= 10)
{
int randomIndex = random.nextInt(numberOfImages);
String fileName = fileNameList.get(randomIndex);
if (!quizAnswerList.contains(fileName))
{
quizAnswerList.add(fileName);
++imageCounter;
}
}
loadNextImage();
}
//after guesses a correct answer
private void loadNextImage() {
//get file name of the next flag and remove from the list
String nextImageName = quizAnswerList.remove(0);
correctAnswer = nextImageName; //update the correct answer
answerTextView.setText(""); //clear answerTextView
//display the number of current question in the game
questionNumberTextView.setText(
getResources().getString(R.string.question) + " " + (correctAnswers + 1) + " " +
getResources().getString(R.string.of) + " 10");
//extract the region from the next image's name
String game = nextImageName.substring(0, nextImageName.indexOf('-'));
//use AssetManager to load next image from assets folder
AssetManager assets = getAssets();
InputStream stream; //utk bace image
try
{
//get an InputStream to asset representing the next image
stream = assets.open(game + "/" + nextImageName + ".png");
//load the asset as a Drawable and display on the imageImageView
Drawable image = Drawable.createFromStream(stream, nextImageName);
imageImageView.setImageDrawable(image);
}
catch (IOException e)
{
Log.e(TAG, "Error Loading " + nextImageName, e);
}
for (int row = 0; row < buttonTableLayout.getChildCount(); ++row)
((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();
Collections.shuffle(fileNameList);
int correct = fileNameList.indexOf(correctAnswer);
fileNameList.add(fileNameList.remove(correct));
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
for (int row = 0; row < guessRows; row++)
{
TableRow currentTableRow = getTableRow(row);
for (int column = 0; column < 3; column++)
{
Button newGuessButton =
(Button) inflater.inflate(R.layout.guess_button, null);
String fileName = fileNameList.get((row * 3) + column);
newGuessButton.setText(getAnswerName(fileName));
newGuessButton.setOnClickListener(guessButtonListener);
currentTableRow.addView(newGuessButton);
}
}
int row = random.nextInt(guessRows);
int column = random.nextInt(3);
TableRow randomTableRow = getTableRow(row);
String answerName = getAnswerName(correctAnswer);
((Button)randomTableRow.getChildAt(column)).setText(answerName);
}
private TableRow getTableRow(int row)
{
return (TableRow) buttonTableLayout.getChildAt(row);
}
private String getAnswerName(String name)
{
return name.substring(name.indexOf('-') + 1).replace('_', ' ');
}
//called when user selects the answer
private void submitGuess(Button guessButton)
{
String guess = guessButton.getText().toString();
String answer = getAnswerName(correctAnswer);
++totalGuesses;//total guesses user made increment
//if guess correct
if (guess.equals(answer))
{
++correctAnswers;
//view jawapan dalam tulisan warna hijau
answerTextView.setText(answer + "!");
answerTextView.setTextColor(getResources().getColor(R.color.correct_answer));
disableButtons();// disable all answer buttons
// if the user has correctly identified 10 image
if (correctAnswers == 10)
{
//create a new AlerDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.taniah);
//set the AlertDialog's message to display game results
// %d means integer and not double, %s tuh dia ganti string,
builder.setMessage(String.format("%d %s",
totalGuesses, getResources().getString(R.string.guesses)
));
builder.setCancelable(false);
//add reset quiz
builder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
resetQuiz();
}
}
);
AlertDialog resetDialog = builder.create();
resetDialog.show();
}
else
{
handler.postDelayed(
new Runnable()
{
@Override
public void run()
{
loadNextImage();
}
}, 1000);
}
}
else
{
//play animation
imageImageView.startAnimation(shakeAnimation);
//display "Incorrect!" in red
answerTextView.setText(R.string.incorrect_answer);
answerTextView.setTextColor(getResources().getColor(R.color.incorrect_answer));
guessButton.setEnabled(false);//disable incorrect answer
}
}
private void disableButtons()
{
for (int row = 0; row < buttonTableLayout.getChildCount(); ++row)
{
TableRow tableRow = (TableRow) buttonTableLayout.getChildAt(row);
for (int i = 0; i < tableRow.getChildCount(); ++i)
tableRow.getChildAt(i).setEnabled(false);
}
}
//create constant for each menu id
private final int CHOICES_MENU_ID = Menu.FIRST;
private final int GAMES_MENU_ID = Menu.FIRST + 1;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, CHOICES_MENU_ID, Menu.NONE, R.string.choices);
menu.add(Menu.NONE, GAMES_MENU_ID, Menu.NONE, R.string.game);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId())
{
case CHOICES_MENU_ID:
final String[] possiblechoices = getResources().getStringArray(R.array.choicesList);
AlertDialog.Builder choicesBuilder = new AlertDialog.Builder(this);
choicesBuilder.setTitle(R.string.choices);
choicesBuilder.setItems(R.array.choicesList,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
guessRows = Integer.parseInt(possiblechoices[item].toString()) /3;
resetQuiz();
}
}
);
AlertDialog choicesDialog = choicesBuilder.create();
choicesDialog.show();
return true;
case GAMES_MENU_ID:
//get array of game
final String[] gameNames = gamesMap.keySet().toArray(new String[gamesMap.size()]);
//boolean array representing whether image game enabled
boolean[] gamesEnabled = new boolean[gamesMap.size()];
for (int i= 0 ; i < gamesEnabled.length; ++i)
gamesEnabled[i] = gamesMap.get(gameNames[i]);
AlertDialog.Builder gamesBuilder = new AlertDialog.Builder(this);
gamesBuilder.setTitle(R.string.game);
String[] displayNames = new String[gameNames.length];
for (int i = 0; i < gameNames.length; ++i)
displayNames[i] = gameNames[i].replace('_', ' ');
gamesBuilder.setMultiChoiceItems(
displayNames, gamesEnabled,
new DialogInterface.OnMultiChoiceClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked)
{
gamesMap.put(
gameNames[which].toString(), isChecked);
}
}
);
gamesBuilder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int button)
{
resetQuiz();
}
}
);
AlertDialog regionsDialog = gamesBuilder.create();
regionsDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
private OnClickListener guessButtonListener = new OnClickListener()
{
@Override
public void onClick(View v)
{
submitGuess((Button) v);
}
};
}