我用九个按钮做了一个简单的打地鼠游戏。按钮从黑色开始。如果在黑色时按下它们,则会记录错误。这些按钮将随机闪烁淡蓝色或深蓝色。他们需要在淡蓝色时按下一次才能记录分数。深蓝色时,需要按两次。
当按钮正常工作时,它们会记录一个点,并在按下正确次数时发出提示音并变黑。
在游戏过程中,九个按钮中的一个会随机失灵。它会记录错误,但不会记录点数(它们也不会发出声音或变黑)。
我不明白这是为什么。如果我结束游戏并重新加载,该按钮将再次正常工作,但其他一些按钮会出现故障。
我想也许我应该使用按钮侦听器而不是 onClick,所以我更改了代码但并没有解决问题。
我的下一个猜测是我在一个处理程序上放置了太多线程。我现在已经在三个处理程序中拆分了 10 个线程,但这也没有解决问题。
当我按下故障按钮时,我在 logcat 中收到的消息是:
ViewPostIme 指针 0
ViewPostIme 指针 1
有谁知道为什么按钮会随机失灵?
谢谢
这是每个按钮的代码
button9.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFlashing9.get()) {
clicked9++;
//code for when button pressed for correct number of times
if (clicked9 == req9) {
isFlashing9.set(false);
button9.setBackgroundColor(Color.rgb(0, 0, 0));
streak++;
correct();
if (streak > bestScore) {
bestScore = streak;
best.setText("HI SCORE \n " + bestScore);
saveData();
}
currentStreak.setText("SCORE\n" + streak);
clicked9 = 0;
}
} else {
playError(); //play error sound
mistakesSO++;
mistakes.setText("MISTAKES \n" + mistakesSO);
if (mistakesSO == 3) {
}
}
}
});
这是更改按钮颜色的可运行程序:
public Runnable B9 = new Runnable() {
public void run() {
ender9++;
timerInt9++;
if (timerInt9 % 10 == 1) {
int colour = ThreadLocalRandom.current().nextInt(1, 3); // sets button colour
if (colour == 1) {
button9.setBackgroundColor(Color.rgb(78, 162, 245));
req9 = 1; // sets number of button presses required
isFlashing9.set(true);
} else {
button9.setBackgroundColor(Color.rgb(56, 98, 173));
req9 = 2; // sets number of button presses required
isFlashing9.set(true);
}
}
if (timerInt9 % 10 == 3) {
button9.setBackgroundColor(Color.rgb(0, 0, 0)); // resets button to black after it has flashed for 2 seconds.
isFlashing9.set(false);
timerInt9 = 110;
}
handler3.postDelayed(this, 1000);
if (ender9 >= 3) {
handler3.removeCallbacks(this);
ender9=0;
}
}
};
这是可运行的选择哪个按钮闪烁:
public Runnable ButtonChooser = new Runnable() {
public void run() {
// sets random time between buttons flashing
int time = ThreadLocalRandom.current().nextInt(100, 600);
//picks the next button to flash
int which = ThreadLocalRandom.current().nextInt(1, 10);
if (which ==1){
if(!isFlashing1.get())handler.postDelayed(B1, 0);
}
if (which ==2){
if(!isFlashing2.get())handler.postDelayed(B2, 0);
}
if (which ==3){
if(!isFlashing3.get())handler.postDelayed(B3, 0);
}
if (which ==4){
if(!isFlashing4.get()) handler2.postDelayed(B4, 0);
}
if (which ==5){
if(!isFlashing5.get())handler2.postDelayed(B5, 0);
}
if (which ==6){
if(!isFlashing6.get())handler2.postDelayed(B6, 0);
}
if (which ==7){
if(!isFlashing7.get())handler3.postDelayed(B7, 0);
}
if (which ==8){
if(!isFlashing8.get())handler3.postDelayed(B8, 0);
}
if (which ==9){
if(!isFlashing9.get())handler3.postDelayed(B9, 0);
}
handler.postDelayed(this, time);
}
};