So, I'm, trying to be able to correctly resize my console window using ncurse in C++. I've been able to catch when the window is resize, the problem is that I'm not 100% sure how should I proceed after that. Let's say I have this loop in my main function (after initializing ncurse and those things...):
while(ch = getch())
{
if(ch == KEY_RESIZE)
{
DoSometing();
}
}
As I said the DoSomething in that example is called. But if I try to use ncurse's functions to get the new size of the window with
getmaxyx(stdscr, yMax, xMax);
I'm get the same values (the initial values) over and over again. I guess that's because when I do initscr(), the window size is stored somewhere and that's the value that the getmaxyx function provides. I've tried to do something like call endwin() and the again initscr() to restore those values, but that doesn't seem to work, the value that getmaxyx returns is fixed.
After searching for alternative solutions, I kind of solve the problem, using some other libraries. That's an small example, which actually works as I wanted:
#include <cstdlib>
#include <ncurses.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
initscr();
noecho();
box(stdscr, 0, 0);
struct winsize w;
int ch, x, y;
while(ch = getch())
{
if(ch == KEY_RESIZE)
{
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
resize_term(w.ws_row, w.ws_col);
clear();
box(stdscr, 0, 0);
}
refresh();
}
}
The thing is I'm kind of worried about portability while using this new libraries (I'm not completely sure, because I haven't started testing yet, but I understand that ncurse programs can be port to Windows).
I would really appreciate any information about how to do this in ncurse without using any other library (if it's possible), if what I'm doing now is OK or if I should be doing it in any other way. Any hint in the right direction is what I'm looking for :)
I'm using Arch Linux (kind of noobie) and qtile as a window manager. If you need any other relevant information, just ask me. Thanks for the help!
This is causing the example to produce bogus results:
if(ch = KEY_RESIZE)
since it is always true (not a comparison, but an assignment). The "something" is not doing anything useful, because the condition is incorrect.
Change that to
if(ch == KEY_RESIZE)
and get rid of
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
resize_term(w.ws_row, w.ws_col);
Related
Is it possible to use C++ to simulate keypress? What I mean by that I mean is it possible to use C++ to emulate your keyboard to type out a word. If you are still confused about what I am talking about (Like the rest of the internet) then what I am trying to say is if there is a way to copy something like pyautogui and pynput in C++. I've looked everywhere for an answer but all I saw was key detection. I want to know how to do this because my friends keep spamming me so I want to get my revenge by making a spam bot. Here's the code so far..
#include <iostream>
#include <windows.h>
using namespace std;
string message = "Lol";
float delay = 0.2f;
void click_to_location()
{
Sleep(5000);
SetCursorPos(525, 665);
Sleep(10);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
Sleep(10);
}
int main()
{
while (true)
{
if (GetAsyncKeyState(0x51))
{
exit(0);
}
// Help with key Press here
Sleep(10);
// Help with key Release here
}
return 0;
}
Also ignore my bad programming skills.
From my experience, simulate keystroke is not language specific.
Can simulate keystroke on windows using win32 api and c++. https://learn.microsoft.com/en-us/windows/win32/learnwin32/keyboard-input
I'm trying to create an application with the SDL, and would like the window to be resized.
For now, if I try to maximize the window, it works, if I place it in the left or right half of the screen, it works and take the right size.
But, when I resize the window by dragging one of it sides (vertical or horizontal), something really strange happen : the height grow until it's equal to the height of the screen.
When it grows, I can see that it's not instantaneous, in fact it takes many times times, growing each time of 37 pixels.
It's really strange, and I really don't know what to do.
I created a minimalist code to test if the problem was due to something special in my code, but it doesn't change anything, the problem is still the same.
Here is my minimalist code :
#include <SDL/SDL.h>
using namespace std;
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* surface=SDL_SetVideoMode(100, 100, 32, SDL_HWSURFACE|SDL_RESIZABLE);
SDL_Event event;
while (true)
{
SDL_Flip(surface);
SDL_PollEvent(&event);
if (event.type==SDL_QUIT) break;
else if (event.type==SDL_VIDEORESIZE)
{
surface=SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_HWSURFACE|SDL_RESIZABLE);
}
SDL_Delay(30);
}
}
So the problem don't seem to be in my code. (To verify that, I installed a game that use the SDL (Briquolo), and it has the same problem)
I searched on the web, but it seems that I'm the only person who got this problem (or it's maybe that I don't use the good keywords), so it seems that it's not the SDL.
The problem is probably caused by my system.
For information, got Ubuntu 16.10 64-bit, with the Gnome desktop.
How can I solve this problem, without having side effects ?
Finally found a way to avoid this (but I don't really understand why the first way didn't work) :
If I store the new sizes, process all events, and then resize, it works. Here's the working code :
#include <SDL/SDL.h>
#include <iostream>
using namespace std;
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* surface=SDL_SetVideoMode(100, 100, 32, SDL_HWSURFACE|SDL_RESIZABLE);
SDL_Event event;
bool resized=false;
int newW, newH;
while (true)
{
while (SDL_PollEvent(&event))
{
if (event.type==SDL_QUIT) return 0;
else if (event.type==SDL_VIDEORESIZE)
{
resized=true;
newW=event.resize.w;
newH=event.resize.h;
}
}
}
if (resized)
{
resized=false;
surface=SDL_SetVideoMode(newW, newH, 32, SDL_HWSURFACE|SDL_RESIZABLE);
}
SDL_Flip(surface);
}
So I am making a game, an ASCII dungeon explorer and I had a plan to get the window size and scale the display the inventory beside the dungeon. I went on google to find a function that would return the window size so I can print the inv on the side... The parts that are commented out is the code that I found and so I tried to put it in my main.cpp just to try it out. I planned to use other functions that I found to get the max size of the window and to set the size. This code that I pasted into my code was giving me loads of errors when I went to run the game, somewhere around 180 errors from a header file called wingdi.h. I googled a bit more and found people changing some definitions in the project properties which I tried and it gave me about 130 errors from different headers included in . Someone said that one of the variables is already declared in windows.h and the person that asked that question should change it to something else so I changed csbi to my_csbi, both didn't work. Some people also said it was a problem with the code so I decided to just leave it for now, and go back to my old code and do something else for now (I was getting frustrated, lol). I commented it all out, hoping to come back to it later. When I tried to run my game with all of that code gone, it gave me the same errors. Do I have to reinstall Visual Studio 2015? Starting my code from scratch or changing some definitions?
#include <iostream>
#include <conio.h>
//#include <Windows.h>
#include "GameSystem.h"
using namespace std;
int main()
{
//int x = 0;
//int y = 0;
//CONSOLE_SCREEN_BUFFER_INFO my_csbi;
//GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &my_csbi);
//x = my_csbi.srWindow.Right -my_csbi.srWindow.Left + 1;
//y = my_csbi.srWindow.Bottom -my_csbi.srWindow.Top + 1;
//printf("columns: %d\n", x);
//printf("rows: %d\n", y);
GameSystem gameSystem("level1.txt");
gameSystem.playGame();
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
I am fairly new to programming so I'm sorry if my question is stupid or "simple" and if that offended you in some shape or form. :)
Thanks, Bulky.
EDIT: All the "solutions" others got didn't work for me and I decided to ask this because after I commented out all that code, my old code didn't even run (it was perfect before).
You never include <WinGdi.h> directly. You always include <Windows.h>, which pulls in the required headers implicitly.
The GDI functions (from <WinGdi.h>) aren't going to do you any good if you are writing a console application. The GetConsoleScreenBufferInfo function is probably what you want to be using, but it is not a GDI function. It is a kernel function. Again, although it is technically declared in <WinCon.h>, you are not supposed to include that header directly. Just include <Windows.h>.
The following code works fine for me
(other than the fact that std::cin doesn't actually work for "enter any key to exit..."):
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
int main()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
int x = csbi.srWindow.Right - csbi.srWindow.Left + 1;
int y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
printf("columns: %d\n", x);
printf("rows: %d\n", y);
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
Output:
columns: 90
rows: 33
Enter any key to exit...
If it does not work for you, one of the following must be true:
1. The problem resides in "GameSystem.h", which you have not shown us.
(It is fineāin the future, please post code as text, not pictures.)
2. You have created the wrong type of project (recreate a new project using the Win32 Console Application template).
3. There is something wrong with your installation of Visual Studio (try reinstalling).
I am currently writing a program in c++ that is very similar to the classic "snake" program with a few changes. I am writing it so that it will update the screen five times a second, based on ctime, possibly more if it can be handled. One thing that I would like to do is make it so that the program has a variable in the .h file "currkeypressed." This variable will hold the key that the user is currently holding down and the snake head will go in that direction. Each node in the snake will be a separate object so the currkeypressed will only affect the head. Directional and locational data will be passed down the snake from node to node at each update.
My question is: how can I get the program to keep this data constantly, rather than updating only with a cin when the key is pressed or at a certain interval? I know that I can accept the ascii value for the arrow keys in some sort of for loop, but that doesn't seem to work if the key is held down and if the loop is very long it can miss a press. Does anybody know how to do this?
EDIT: I am using a Linux OS, Ubuntu to be more precise
The simplest method is to use ncurse library.
However, if you prefer "raw" linux programming, you can use select and getchar:
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
fd_set readfs;
struct timeval timeout;
int res, key;
while (1) {
/* .. do something else .. */
FD_SET(0, &readfs); /* 0 is STDIN */
timeout.tv_usec = 10; /* milliseconds */
timeout.tv_sec = 0; /* seconds */
res = select(maxfd, &readfs, NULL, NULL, &timeout);
if (res) {
/* key pressed */
key = getchar();
if (key == 'A') { /* blar */ }
}
}
}
Once you are looking beyond simple line oriented or character orient input, you are into the details of the user input device. Each operating system has a particular mechanism for notifying a program of events like keydown and keyup.
To get an answer, add a tag for which programming environment you are in: MSWindows, Linux, Android, MacOS, etc.
You can use the library conio.h and you can use the function _getch() in a loop to get live input without any restriction.
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
char n='a';//Just for initialization
while(n!='e')
{
n=_getch();
}
return 0;
}
The simplest (although really not that simple) way would be to have a thread to capture the user input and then either have some kind of event driven system that can alert the head of the snake or the snake can poll for the current key.
Here's an oddity from the past!
I'm writing an ASCII Pong game for the command prompt (Yes yes oldschool) and I'm writing to the video memory directly (Add. 0xB8000000) so I know I'm rendering quickly (As opposed to gotoxy and then printf rendering)
My code works fine, the code compiles fine under Turbo C++ V1.01 BUT the animation lags... now hold on hold on, there's a cavaet! Under my super fast boosted turbo Dell Core 2 Duo this seems logical however when I hold a key on the keyboard the animation becomes smooth as a newly compiled baby's bottom.
I thought maybe it was because I was slowing the computer down by overloading the keyboard buffer (wtf really? come on...) but then I quickly smartened up and tried compiling for DJGPP and Tiny C Compiler to test if the results are the same. On Tiny C Compiler I found I coulnd't compile 'far' pointer types... still confused on that one but I was able to compile for DJGPP and it the animation ran smoothly!
I want to compile this and have it work for Turbo C++ but this problem has been plagueing me for the past 3 days to no resolve. Does anyone know why the Turbo C++ constant calls to my rendering method (code below) will lag in the command prompt but DJGPP will not? I don't know if I'm compiling as debug or not, I don't even know how to check if I am. I did convert the code to ASM and I saw what looked to be debugging data at the header of the source so I don't know...
Any and all comments and help will be greatly appreciated!
Here is a quick example of what I'm up against, simple to compile so please check it out:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<time.h>
#define bX 80
#define bY 24
#define halfX bX/2
#define halfY bY/2
#define resolution bX*bY
#define LEFT 1
#define RIGHT 2
void GameLoop();
void render();
void clearBoard();
void printBoard();
void ballLogic();
typedef struct {
int x, y;
}vertex;
vertex vertexWith(int x, int y) {
vertex retVal;
retVal.x = x;
retVal.y = y;
return retVal;
}
vertex vertexFrom(vertex from) {
vertex retVal;
retVal.x = from.x;
retVal.y = from.y;
return retVal;
}
int direction;
char far *Screen_base;
char *board;
vertex ballPos;
void main() {
Screen_base = (char far*)0xB8000000;
ballPos = vertexWith(halfX, halfY);
direction = LEFT;
board = (char *)malloc(resolution*sizeof(char));
GameLoop();
}
void GameLoop() {
char input;
clrscr();
clearBoard();
do {
if(kbhit())
input = getch();
render();
ballLogic();
delay(50);
}while(input != 'p');
clrscr();
}
void render() {
clearBoard();
board[ballPos.y*bX+ballPos.x] = 'X';
printBoard();
}
void clearBoard() {
int d;
for(d=0;d<resolution;d++)
board[d] = ' ';
}
void printBoard() {
int d;
char far *target = Screen_base+d;
for(d=0;d<resolution;d++) {
*target = board[d];
*(target+1) = LIGHTGRAY;
++target;
++target;
}
}
void ballLogic() {
vertex newPos = vertexFrom(ballPos);
if(direction == LEFT)
newPos.x--;
if(direction == RIGHT)
newPos.x++;
if(newPos.x == 0)
direction = RIGHT;
else if(newPos.x == bX)
direction = LEFT;
else
ballPos = vertexFrom(newPos);
}
First, in the code:
void printBoard() {
int d;
char far *target = Screen_base+d; // <-- right there
for(d=0;d<resolution;d++) {
you are using the variable d before it is initialized.
My assumption is that if you are running this in a DOS window, rather than booting into DOS and running it, is that kbhit is having to do more work (indirectly -- within the DOS box's provided environment) if there isn't already a keypress queued up.
This shouldn't effect your run time very much, but I suggest that in the event that there is no keypress you explicitly set the input to some constant. Also, input should really be an int, not a char.
Other suggestions:
vertexFrom doesn't really do anything.
A = vertexFrom(B);
should be able to be replaced with:
A = B;
Your macro constants that have operators in them should have parenthisis around them.
#define Foo x/2
should be:
#define Foo (x/2)
so that you never ever have to worry about operator precedence no matter what code surrounds uses of Foo.
Under 16 bit x86 PCs there are actually 4 display areas that can be switched between. If you can swap between 2 of those for your animation, and your animations should appear to happen instantaneously. It's called Double Buffering. You have one buffer that acts as the current display buffer and one that is the working buffer. Then when you are satisfied with the working buffer (and the time is right, if you are trying to update the screen at a certain rate) then you swap them. I don't remember how to do this, but the particulars shouldn't be too difficult to find. I'd suggest that you might leave the initial buffer alone and restore back to it upon exit so that the program would leave the screen in just about the state that it started in. Also, you could use the other buffer to hold debug output and then if you held down the space bar or something that buffer could be displayed.
If you don't want to go that route and the 'X' is the only thing changing then you could forgo clearing the screen and just clear the last location of the 'X'.
Isn't the screen buffer an array of 2 byte units -- one for display character, and the other for the attributes? I think so, so I would represent it as an array of:
struct screen_unit {
char ch;
unsigned char attr;
}; /* or reverse those if I've got them backwards */
This would make it less likely for you to make mistakes based on offsets.
I'd also probably read and write them to the buffer as the 16 bit value, rather than the byte, though this shouldn't make a big difference.
I figured out why it wasn't rendering right away, the timer that I created is fine the problem is that the actual clock_t is only accurate to .054547XXX or so and so I could only render at 18fps. The way I would fix this is by using a more accurate clock... which is a whole other story