c - C 编程的骰子模拟器

标签 c dice

我正在尝试为基本的骰子模拟器程序编写代码。当按下开关时,两个七段显示器将在 1-6 之间快速变化。释放按钮时,随机数将显示在两个七段显示屏上。

此代码将连接到 ISIS 中的 pic16F877,我使用 MPLAB 进行 C 编程。

我对这个编程东西真的很陌生,所以我很难理解它。

#include <pic.h>
const char patterns[]={0X3F, 0X06, 0X5B, 0x4F, 0X66, 0X6D, 0X7D}
char rand_num1=0;
char rand_num2=0;

void main(void)

{
     TRISB=0x00;
     TRISC=0x01;
     TRISD=0x00;

     for(;;)
            {
                if(RCO==0)
                {
                         rand_num1=rand()%6+1;
                         rand_num2=rand()%6+1;
                }

                if (RC0==1)
                  {
                         const char patterns[];
                  }
            }
}

最佳答案

让我澄清一下我上面的评论:

首先,您不需要调用rand()。用户将按下按钮一段时间(精度为 10 或 20 纳秒,这对于微 Controller 来说是一个合理的时钟)。在给定精度的情况下,此间隔可能比调用 rand() 更加随机。因此,您可以有一个计数器(即最多 256)并从此计数器中获取两个随机数。在代码中,这将类似于:

int counter = 0;
int lo_chunk, hi_chunk;
if(RCO == 0) { // assuming that RCO == 0 means the button is pressed
    counter = (counter + 1) % 256; // keep one byte out of the int
                                   // we'll use that byte two get 2 4-bit
                                   // chunks that we'll use as our randoms
    lo_chunk = (counter & 0xF) % 6; // keep 4 LSBits and mod them by 6
    hi_chunk = ((counter >> 4) & 0xF) % 6; // shift to get next 4 bits and mod them by 6
    // Now this part is tricky.
    // since you want to display the numbers in the 7seg display, I am assuming 
    // that you will need to write the respective patterns "somewhere"
    // (either a memory address or output pins). You'll need to check the
    // documentation of your board on this. I'll just outline them as 
    // "existing functions"
    write_first_7segment(patterns[lo_chunk]);
    write_second_7segment(patterns[hi_chunk]);

 } else if(RCO == 1) { // assuming that this means "key released" 
     rand_num1 = lo_chunk;
     rand_num2 = hi_chunk;
     // probably you'll also need to display the numbers.
 }

我希望我在上面的评论中写的内容现在更有意义。

请记住,由于不知道您董事会的确切详细信息,我无法 告诉你如何实际将模式写入 7 段显示器,但我 假设会有某种功能。

关于c - C 编程的骰子模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14259751/

相关文章:

使用 arm-eabi-gcc 交叉编译模块

c - 在不同调用中接收指向不同结构的指针作为参数(或类似的东西)

javascript - 显示与点击时生成的随机数对应的骰子元素

c# - 基本的 C# 骰子游戏

c - 浮点异常: 8

c - 在 C 代码中循环输入并使用终端一次将数据写入不同的文件

c - 文本和分隔符的操作

java - 如何让我的百分比在我的 Dice 计划中发挥作用?

JavaScript:多个骰子滚轮,每个滚轮都有自己的骰子总数

c++ - msvcrt.dll 是否为其 rand() 函数使用线性同余生成器?