[英]Selectively ignoring parts of a randomly generated sequence of numbers (in C)
我有一个可能难以理解的问题-但我会尽力解释。
我正在用C语言对Simon Game进行编程。此实现专门读取/写入硬件DAQ模块,该模块具有4个LED显示屏和4个相应的拨动开关。
根据游戏规则,我已经播种并生成了一个介于0到3之间的随机数字序列(序列长度任意为5)。 在游戏中,如果玩家按下错误的开关(即显示蓝色但您按下绿色),则游戏结束并重新启动。
我设置游戏的方式如下所示:
(我这里没有包括功能“ blinkLED”的代码,它可以打开/关闭实际的LED。)
void runSimon(void){
int sequence[MAX_SEQ_LEN];
int i;
int count = 0;
// Seeds the random number generator.
srand((unsigned)time(NULL));
// Generate the random LED sequence & store it as an array.
for (i = 0; i < MAX_SEQ_LEN; i++){
sequence[i] = (rand() % NUM_LEDS);
}
// The game begins!
while (continueSuperLoop() == TRUE){
// Loop the game while the sequence length is less than the pre-defined maximum (currently it's 5).
while (count < MAX_SEQ_LEN){
for (i = 0; i <= count; i++){
// Blink the first 'count' LEDs in the sequence, one at a time.
blinkLED(sequence[i], 1, ONE_SEC);
//
//
//THE ISSUE SHOULD BE HERE (!)
//
// Monitors whether or not the player has made a mistake...if so, blink the red LED thrice, then restart the game.
if (digitalRead(sequence[ !i ] == SWITCH_ON)){
blinkLED(LED_1_R, 3, HALF_SEC);
Sleep(3 * ONE_SEC);
continue;
}
// Monitors whether or not the correct switch is being pressed -- waits for it to be released
while (digitalRead(sequence[i]) == SWITCH_ON){}
}
count++;
}
// If 'count' is equal to 'MAX_SEQ_LEN', the green LED blinks 3x to indicate the player has won .
if (count == MAX_SEQ_LEN){
blinkLED(LED_0_G, 3, HALF_SEC);
Sleep(3 * ONE_SEC);
}
}
}
在出现问题的地方,我不确定“ digitalRead(sequence [!i]”)的行为;我需要此行来读取所有不应按下的开关。
不过,我认为编译器无法理解我要在此处执行的操作-例如,如果序列中的第一个数字为3(代表第四个LED),则需要指定其他每个数字(0, 1、2)及其相应的开关不应该被按下。
一种解决方案是将当前数字存储在序列中,每个LED具有一组四个TRUE / FALSE标志,并监视三个非当前数字及其对应关系。 开关看看是否被按下了?
我对编写此程序感到非常沮丧。 我是编程新手。 任何帮助表示赞赏。
我不确定我是否正确理解了该游戏的规则,但有一件事情会立即跳出来
digitalRead(sequence[ !i ]
我想你要
!digitalRead(sequence[ i ]
另外,您需要修正游戏流程。 现在是:
1. Light LED.
2. Check if user pressed the right button.
您需要等待一段时间才能检查开关,或者等待按下任意开关以查看其是否正确。 所以像这样:
1. Light LED.
2. Wait for timeout or ANY switch to be pressed.
3. If timeout: error
4. else: check if switch that was pressed is correct.
在C中, !
运算符是一元NOT。 当应用于整数i
,等效于if (i == 0) return 1; else return 0;
if (i == 0) return 1; else return 0;
。 然后,您将!i
用作sequence
数组的索引,因此它将是sequence[0]
或sequence[1]
,显然这不是您想要的。 您的==
也在digitalRead
调用中:)
我建议明确检查所有其他不被按下的按钮。 像这样:
int isOtherPressed = 0;
for (ledId = 0; ledId < NUM_LEDS; ledId++) {
if (ledId != sequence[i] && digitalRead(ledId) == SWITCH_ON) {
isOtherPressed = 1;
}
}
if (isOtherPressed) {
// restart the game
}
但是,我对您拥有的整个游戏方式感到怀疑,但这可能只是因为我不知道digitalRead
工作原理。 例如,您使用continue
的方式似乎并不能停止游戏。 也许你是想break
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.