Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 2021-11-28
- //
- // Bounces a square around a windows terminal.
- // I had a problem with flicker when trying to use system("cls") to clear the screen (I guess it's too slow?)
- // But after some suggestions from some other people, and a bit of copying from stack overflow, it turns out that
- // I can easily get any frame rate I could want with my current method, which is to reset the cursor to the top left
- // and reprint the whole buffer. It's also possible to update on a per character basis by moving the cursor
- // around to only update characters which have changed between two frames, but I like the full reprint method.
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdint.h>
- #include <conio.h>
- #define NOMINMAX
- #define WIN32_LEAN_AND_MEAN
- #include <Windows.h>
- #define COLS 60
- #define ROWS 40
- #define FRAMERATE 24
- int ToIndex(int x, int y){ return y * COLS + x; }
- char world[COLS*ROWS] = {0};
- char buffer[(COLS+1)*ROWS] = {0};
- void BufferPrint(char *world);
- void WorldClear(char clearCharacter);
- void setCursorPosition(int x, int y);
- void setCursorVisibility(int isShown);
- void PaintRect(int x, int y, int w, int h, char c);
- int posX = 20;
- int posY = 4;
- int width = 10;
- int height = 6;
- int velX = 1;
- int velY = 1;
- int main(void){
- setCursorVisibility(FALSE);
- system("cls");
- while(1){
- Sleep(1000/FRAMERATE);
- WorldClear('.');
- PaintRect(posX, posY, width, height, 'O');
- if(posX+width >= COLS-1 || posX <= 0){ velX *= -1; }
- if(posY+height >= ROWS || posY <= 0){ velY *= -1; }
- posX += velX;
- posY += velY;
- BufferPrint(world);
- }
- return 0;
- }
- void PaintRect(int x, int y, int w, int h, char c){
- for(int i = 0; i < h; ++i){
- for(int j = 0; j < w; ++j){
- world[ToIndex(x+j, y+i)] = c;
- }
- }
- }
- void WorldClear(char clearCharacter){
- for(int i = 0; i < COLS*ROWS; ++i){
- world[i] = clearCharacter;
- }
- }
- void BufferPrint(char *world){
- setCursorPosition(0,0);
- for(int i = 0; i < (COLS+1)*ROWS; ++i){
- buffer[i] = world[i];
- if(i % (COLS) == (COLS-1)){
- buffer[i] = '\n';
- }
- }
- buffer[COLS*ROWS] = '\0';
- fprintf(stdout, "%s", buffer);
- fflush(stdout);
- setCursorPosition(0,0);
- }
- void setCursorPosition(int x, int y){
- const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
- fflush(stdout);
- COORD coord = { (SHORT)x, (SHORT)y };
- SetConsoleCursorPosition(hOut, coord);
- }
- void setCursorVisibility(int isShown){
- HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
- CONSOLE_CURSOR_INFO info;
- info.dwSize = 100;
- info.bVisible = isShown;
- SetConsoleCursorInfo(consoleHandle, &info);
- }
Add Comment
Please, Sign In to add comment