多骰子滚动游戏:如何实现骰子图形横向并排输出?
怎么让骰子图形横向并排显示
你现在的代码每次调用diceImage都会直接输出完整的骰子,所以会纵向堆在一起。要改成横向并排,得换个思路——先把所有骰子的点数都生成好,然后按行输出:先输出所有骰子的顶部边框行,再输出所有骰子的上点行,以此类推,直到所有骰子的底部边框行。
修改后的完整代码:
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; // 根据骰子点数和行号,返回该行的字符串 string getDiceLine(int num, int line) { switch(line) { case 0: return " ------- "; case 1: if(num == 1 || num == 3 || num ==5) return "| |"; else return "|* |"; case 2: if(num ==1) return "| * |"; else if(num ==2 || num ==3) return "| |"; else return "|* *|"; case 3: if(num ==1 || num ==2 || num ==4) return "| |"; else if(num ==3 || num ==5) return "| * |"; else return "|* *|"; case 4: if(num ==1 || num ==3 || num ==5) return "| |"; else return "| *|"; case 5: return " ------- "; default: return ""; } } int main() { srand(time(0)); int target_num; int d1, d2, d3, d4, d5, total; int tries = 0; // 输入目标数字并验证 do { cout << "输入5到30之间的数字:"; cin >> target_num; if(target_num <5 || target_num>30) { cout << "输入无效,请输入5到30之间的数字。" << endl; } } while(target_num <5 || target_num>30); // 循环掷骰子直到总和匹配目标 do { // 先把五个骰子的点数都生成好 d1 = rand()%6 +1; d2 = rand()%6 +1; d3 = rand()%6 +1; d4 = rand()%6 +1; d5 = rand()%6 +1; // 逐行输出所有骰子的对应行,实现横向并排 for(int i=0; i<6; i++) { cout << getDiceLine(d1, i) << " " << getDiceLine(d2, i) << " " << getDiceLine(d3, i) << " " << getDiceLine(d4, i) << " " << getDiceLine(d5, i) << endl; } total = d1+d2+d3+d4+d5; cout << "骰子1:" << d1 << ",骰子2:" << d2 << ",骰子3:" << d3 << ",骰子4:" << d4 << ",骰子5:" << d5 << ",总和:" << total << endl; tries++; } while(total != target_num); cout << "总共掷了" << tries << "次,得到目标数字" << target_num << "。" << endl; return 0; }
改动说明:
- 把原来的
diceImage拆成getDiceLine函数,只返回骰子某一行的内容,不直接输出 - 主循环里先一次性生成所有骰子的点数,再用循环逐行拼接每个骰子的对应行,这样所有骰子的同一行就会横向排列
- 修复了原代码中骰子1最后一行的空格错误,保证所有骰子宽度一致,排版整齐
内容的提问来源于stack exchange,提问作者semajamos
相关产品推荐
相关产品推荐

