我写了一个简单的记忆游戏。您单击 16 张卡片中的一张(图像按钮),将其翻转以显示水果(例如香蕉的图片),然后单击另一张卡片将其翻转并显示为水果。然后,如果图像匹配,则在一两秒后,这两个图块被替换为空白(即从板上移除)。这种情况会一直发生,直到所有内容都被删除。水果的名称也被口头读出。提到的一切都完美无缺,第一张卡片被翻转并显示图像,除了点击第二张卡片时,它从不显示水果。说出了正确的水果名称,并且我在第二张卡片点击时使用了与第一张卡片点击类似的代码。你能找到我哪里出错了吗?
我下面代码中的关键部分如下所示:“//因此选择了两个图像!它们匹配吗?”
第一个图像在单击时更新。但是,无论点击的第一个水果 = 点击的第二个水果,空白图块都不会“转动”以显示图像。
代码:....继续
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
int fruitselected = (int)FruitToChooseFromImages.get(position);
// start
if (position == firstfruitselpos && imagesSelectedThusFar == 1 || fruitselected == R.drawable.blank)
{
// (if blank icon clicked) then DO NOTHING
}
else
{ // a valid fruit has been selected, so firstly, say the fruit's name
int soundtoplaynow = getrightsound(position, fruitselected);
SoundManager.playSound(soundtoplaynow, 1);
// next
if (imagesSelectedThusFar == 0)
{
imagesSelectedThusFar = 1;
firstfruitselected = fruitselected; firstfruitselpos = position;
FruitToDisplayImages.set(position, fruitselected);
MyGridviewAdapter1.notifyDataChanged();
gridview.invalidateViews();
}
else // so two images have been selected! do they match?
{
imagesSelectedThusFar = 0; // has reached 2, so reset to zero
secondfruitselected = fruitselected; secondfruitselpos = position;
FruitToDisplayImages.set(position, fruitselected);
MyGridviewAdapter1.notifyDataChanged();
gridview.invalidateViews();
try{ Thread.sleep(1500); }catch(InterruptedException e){ }
if (firstfruitselected == secondfruitselected) //yes they match
{
SoundManager.playSound(50, 1);// play happy sound
//switch fruit image to blank and display blank at position clicked **
FruitToDisplayImages.set(position, R.drawable.blank);
FruitToChooseFromImages.set(position, R.drawable.blank);
FruitToDisplayImages.set(firstfruitselpos, R.drawable.blank);
FruitToChooseFromImages.set(firstfruitselpos, R.drawable.blank);
MyGridviewAdapter1.notifyDataChanged();
gridview.invalidateViews();
fruitleft = (fruitleft - 2);
}
else // nope, dont match
{ // you selected the wrong fruit, sorry.
SoundManager.playSound(60, 1); // play UNhappy sound
try{ Thread.sleep(1500); }catch(InterruptedException e){ }
FruitToChooseFromImages.set(firstfruitselpos, firstfruitselected);
FruitToDisplayImages.set(firstfruitselpos, R.drawable.blanktile);
FruitToDisplayImages.set(secondfruitselpos, R.drawable.blanktile);
MyGridviewAdapter1.notifyDataChanged();
gridview.invalidateViews();
}
}
}
// end
if (fruitleft == 0)
{ //end game - add code here
SoundManager.playSound(70, 1); // play big happy congrats sound
} }
});
ETC