【发布时间】:2018-12-06 05:50:05
【问题描述】:
为了学习和娱乐,我在业余时间做了三个月的 C 程序。我第一次尝试在 C 中创建一个 curses 文件,但老实说,我什至不知道 curses 和 ncurses 是什么,因为它们无论如何都是一样的......所以我想用猜测做一个简单的方框盒子里有一个正确的数字只是为了测试它。我已经成功创建了一个盒子,它包含在下面。我想制作我刚刚在框内添加的字符键,Q 键用于退出,C 键用于清除或重置getchar使用 while-do 循环来猜测正确或错误的数字,包括计算你的次数已经猜到了。顺便说一句:我在 Linux 系统中使用indent 格式化代码。
所以首先我刚刚学会了如何在屏幕显示中创建一个框,如下所示(包含代码):
lqqqqqqqqqqqqqqqqqqk
xthis is my box x
x x
x x
x x
x x
x x
x x
x x
mqqqqqqqqqqqqqqqqqqj
“这是我的盒子”的代码:
#include <stdio.h>
#include <ncurses.h>
int
main (int argc, char **argv)
{
initscr ();
int height, width, start_y, start_x;
height = 10;
width = 20;
start_y = start_x = 10;
WINDOW *win = newwin (height, width, start_y, start_x);
refresh ();
box (win, 0, 0);
mvwprintw (win, 1, 1, "this is my box");
wrefresh (win);
int c = getch ();
endwin ();
return 0;
}
我工作了将近三天的代码源:
#include <stdio.h>
#include <ncurses.h> /*This is similar as curses file*/
//using namespace std;
int
main (int argc, char **argv)
{
initscr ();
int height, width, start_y, start_x;
int tries, num, guess;
srand(time(0)); //random number generator
num = rand() % 100 +1; //only 1 through 100
height = 10;
width = 20;
start_y = start_x = 10;
WINDOW *win = newwin (height, width, start_y, start_x);
refresh ();
box (win, 0, 0);
mvwprintw (win, 1, 1, "Guess the correct number!\n");
do {
while((ch = getch()) != ERR) {
switch(ch) {
case 'Q': shutdown();
case 'C': clear(); break;
}
printf("Enter your guess number (1-100): ");
scanf("%d", &guess);
tries++;
if (guess > num){
printf("Try Again Next Time! Press any key to exit!\n");
} else if (guess < num){
printf("Try again...\n");
} else {
printf("\nCORRECT! You got it right after %d guesses!", tries);
}
}
wrefresh (win);
endwin ();
return 0;
}
这是我对我的想法的期望(例如,我复制了输出并对其进行了编辑):
lqqqqqqqqqqqqqqqqqqk
xGuess the correct x
xnumber! x
x x
xEnter your guess x
xnumber (1-100):___x
x x
xTry again... x
x x
mqqqqqqqqqqqqqqqqqqj
对于预期的输出,我仍然可以编辑尺寸,但现在使用当前尺寸。除非您想添加“自动调整大小”,否则会很甜蜜。感谢阅读和帮助。
【问题讨论】:
-
不太清楚你在问什么。也许将您的问题编辑为更少的故事和更多的问题。不管你是编码新手,不知道 curses 和 ncurses 之间的区别,或者你如何缩进你的代码。
-
你唯一要做的就是最后的条件在哪里。
-
@RetiredNinja,我正在尝试制作一个带有诅咒的游戏,我刚刚创建了在屏幕上绘制一个框并且代码工作正常,然后我有了一个想法,我想在里面添加一个游戏将盒子放入一个名为“猜对数字”的迷你游戏中,因此您只需在框内输入正确的数字,消息(“正确的数字或再试一次”)应该出现在框外,您猜对了多少次数字。我想解释一下,因为我的英语不好,顺便说一句。我只是想练习和学习更多的 C 程序代码。希望这是有道理的。