c++ get users cursor position in console "cells" - c++

System: Windows; Version c++23
Want to create an interactive button in a console application.
For this to work, I need to get where a user clicked 1) relative to console window 2) NOT IN PIXELS, but in CONSOLE CELL UNITS.
Things I tried:
using namespace std;
void GetMouseCursorPos(POINT *mC) {
*mC = POINT{0,0};
ScreenToClient(GetConsoleWindow(),mC);
mC->x = mC->x / font.dwFontSize.X;
mC->y = mC->y / font.dwFontSize.Y;
system("cls");
cout << mC->x << " " << mC->y;
}
int main (){
POINT mCoord;
while (true){
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_MOUSE_INPUT |
ENABLE_EXTENDED_FLAGS);
GetMouseCursorPos(&mCoord);
}
}
In fullscreen ALWAYS outputs 0 -4
Second try:
using namespace std;
void GetMouseCursorPos(POINT *mC) {
*mC = POINT{0,0};
ScreenToClient(GetConsoleWindow(),mC);
mC->x = mC->x / font.dwFontSize.X;
mC->y = LONG(mC->y - 22.5) / font.dwFontSize.Y;
system("cls");
cout << mC->x << " " << mC->y;
}
int main (){
POINT mCoord;
while (true){
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_MOUSE_INPUT |
ENABLE_EXTENDED_FLAGS);
GetMouseCursorPos(&mCoord);
}
}
Although 2nd try is better (but still not perfect)
Why the 2nd try is not perfect(Picture)
When you click on the red crosses
you select the slot leftside to it (not the slot itself)
Button class:
using namespace std;
class Button {
public:
int x;
int y;
int height;
int width;
string text;
string text1;
string text2;
int color = 7;
int itemColor = 7;
string getText() { return text; };
void setText(string text) { this->text = text; };
bool isPressed(int mX, int mY) {
if (mX >= this->x && mX <= this->x + width && mY >= this->y && mY <= this->y + height) {
return true;
}
return false;
};
void print() {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {static_cast<SHORT>(x + 1), static_cast<SHORT>(y)});
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
for (int i = 0; i < width - 1; i++) {
cout << "-";
}
for (int i = 0; i < (height - 2); i++) {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
{static_cast<SHORT>(x), static_cast<SHORT>(y + i + 1)});
cout << "|";
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
{static_cast<SHORT>(x + width), static_cast<SHORT>(y + i + 1)});
cout << "|";
}
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
{static_cast<SHORT>(x + 1), static_cast<SHORT>(y + height -
1)});
for (int i = 0; i < width - 1; i++) {
cout << "-";
}
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
{static_cast<SHORT>(x + 1),
static_cast<SHORT>(y + height / 2)});
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
for (int i = 0; i < width / 2 - text.length() / 2 - 1; i++) {
cout << " ";
}
cout << text;
for (int i = 0; i < width / 2 - text.length() / 2 - 1; i++) {
cout << " ";
}
if (!text1.empty()) {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
{static_cast<SHORT>(x + 1),
static_cast<SHORT>(y + height / 2 + 1)});
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
for (int i = 0; i < width / 2 - text1.length() / 2 - 1; i++) {
cout << " ";
}
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), itemColor);
cout << text1[0];
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
cout << text1.substr(1);
for (int i = 0; i < width / 2 - text1.length() / 2 - 1; i++) {
cout << " ";
}
}
if (!text2.empty()) {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
{static_cast<SHORT>(x + 1),
static_cast<SHORT>(y + height / 2 - 1)});
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
for (int i = 0; i < width / 2 - text2.length() / 2 - 1; i++) {
cout << " ";
}
cout << text2;
for (int i = 0; i < width / 2 - text2.length() / 2 - 1; i++) {
cout << " ";
}
}
}
};

By calling the function SetConsoleMode with the argument ENABLE_MOUSE_INPUT, you can set the console to report mouse events. These events can then be read using the function ReadConsoleInput.
When reading a mouse event, you will get a MOUSE_EVENT_RECORD structure. The dwMousePosition member of this structure is in character-cell coordinates, not pixels.
Here is an example program:
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD ir;
DWORD dwRead;
//set console to report mouse input events (but nothing else, including keyboard events)
if ( !SetConsoleMode( hInput, ENABLE_MOUSE_INPUT ) )
{
fprintf( stderr, "Error setting console mode!\n" );
exit( EXIT_FAILURE );
}
while ( ReadConsoleInput( hInput, &ir, 1, &dwRead ) && dwRead == 1 )
{
//ignore all non-mouse events, except for the key "q", which is a request to end the program
if ( ir.EventType != MOUSE_EVENT )
{
if (
ir.EventType == KEY_EVENT &&
ir.Event.KeyEvent.bKeyDown &&
ir.Event.KeyEvent.uChar.AsciiChar == 'q'
)
{
return 0;
}
continue;
}
//ignore all mouse events which don't involve mouse button presses
if ( ir.Event.MouseEvent.dwEventFlags != 0 && ir.Event.MouseEvent.dwEventFlags != DOUBLE_CLICK )
continue;
//determine whether mouse button was clicked or released
if ( ir.Event.MouseEvent.dwButtonState != 0 )
printf( "Mouse button clicked" );
else
printf( "Mouse button released" );
//print coordinates of mouse click/release
printf(
" at the following cell coordinates: [%u,%u]\n",
ir.Event.MouseEvent.dwMousePosition.X,
ir.Event.MouseEvent.dwMousePosition.Y
);
fflush( stdout );
}
fprintf( stderr, "Input error!\n" );
}
This program has the following output:
Mouse button clicked at the following cell coordinates: [24,9]
Mouse button released at the following cell coordinates: [24,9]
Mouse button clicked at the following cell coordinates: [46,10]
Mouse button released at the following cell coordinates: [60,12]
Mouse button clicked at the following cell coordinates: [45,17]
Mouse button released at the following cell coordinates: [31,10]
In order to quit the program, you must press the Q key.
Note that this program is only for demonstration purposes and is not optimized for performance. In a proper program in which performance may be an issue, it would probably be better to read more than one event at once using ReadConsoleInput.

Related

My character going left but not going right (CONSOLE GAME)

I working on my project this project have a frame to [100] x [25] matrix and i try to add animation but my character is going left but it's not going right.
i tried with "counter" variable but its not work.
int counter = 1;
int counter2 = 1;
int left_border = 1;
int matris1 = sizeof(map)/100;
int matris2 = sizeof(map[0])/4;
int startx = 19;
int starty = 8;
while (true)
...
int right = 0, left = 0;
...
for (int a = 0; a < matris2; a++)
cout << "\n#"; //i have this because i make it square map.
for (int k = 0; k < matris1 - 2; k++)
{
if (left == 1)
{
if (((startx+2)-counter) == left_border)
{
counter = 0;
//cout << "SINIR!!"<< endl ;
}
if (k == (startx-counter) and a == starty)
{
counter += 1;
cout << "O";
}
else {
cout << " ";
}
}
else if (right == 1)
{
if (k == (startx+counter2) and a == starty)
{
counter2 += 1;
cout << "O";
}
its need to be going right but its not.
if you need full code.
https://codeshare.io/UbKVU
[![This is the map and "O" is the character]
https://i.stack.imgur.com/uyGQo.png
The code is very difficult to follow - you should have a coordinate system. I've made a simple example below. Update the player coordinate when a key is pressed and redraw the map x by y position, if the player is there then draw the 'O', otherwise if its a wall draw an 'X' (in this case), otherwise draw a space ' '.
using namespace std;
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#define MAPW 15 // map width
#define MAPH 15 // map height
int map[MAPW][MAPH];
#define WALL 1
#define EMPTY 0
void initmap()
{
// just set the map to have walls around the border
for (int x = 0; x < MAPW; x++)
{
for (int y = 0; y < MAPH; y++)
{
if (x == 0 || y == 0 || x == (MAPW - 1) || y == (MAPH - 1))
map[x][y] = WALL;
else
map[x][y] = EMPTY;
}
}
}
int px = MAPW / 2; // player x
int py = MAPH / 2; // player y
void main()
{
initmap(); // initialize map
cout << "Press A/W/S/D to begin and move";
while (1)
{
if (kbhit()) // key pressed?
{
switch (getch()) // which key?
{
case 'a':
if (px > 0 && map[px - 1][py] != WALL) // can go left?
px--; // update x coordinate
break;
case 'd':
if (px < (MAPW-1) && map[px + 1][py] != WALL) // can go right?
px++; // update x coordinate
break;
case 'w':
if (py > 0 && map[px][py - 1] != WALL) // can go up?
py--; // update y coordinate
break;
case 's':
if (py < MAPH && map[px][py + 1] != WALL) // can go down?
py++; // update y coordinate
break;
}
// update map - clear screen and redraw
system("CLS");
// draw map each line
for (int y = 0; y < MAPH; y++)
{
for (int x = 0; x < MAPW; x++)
{
// its a wall?
if (map[x][y] == WALL)
cout << "X";
else
{
// is the player there?
if (x == px && y == py)
{
// draw the player
cout << "O";
}
else // empty space
cout << " ";
}
}
// next line
cout << "\n";
}
}
}
}

Error on program opening

When I try to start my C++ program it stops with error "5.exe has stopped working". This program supposed to calculate how many tiles you need for pool, if number of tiles on one side is non-round number, add one row of tiles to it. P.S. Sorry for my bad English.
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
int main()
{
int x,y,z;
int a,b;
cout << "Insert dimensions of pool in metres: " << endl;
cin >> x >> y >> z;
cout << "Insert dimensions of tile in centimeters: " << endl;
cin >> a >> b;
a=a/100;
b=b/100;
int brx = 0, brzx = 0, bry = 0, brzy = 0, bxpod = 0, bypod = 0;
if (x%a == 0) {
brx = x / a;
}
else {
brx = x / a + 1;
}
if (z%b == 0) {
brzx = z / b;
}
else {
brzx = z / b + 1;
}
if (y%a == 0) {
bry = y / a;
}
else {
bry = y / a + 1;
}
if (z%b == 0) {
brzy = z / b;
}
else {
brzy = z / b + 1;
}
if (x%a == 0) {
bxpod = x / a;
}
else {
bxpod = x / a + 1;
}
if (y%b == 0) {
bypod = y / b;
}
else {
bypod = y / b + 1;
}
int s = (brx*brzx + bry*brzy) * 2 + bxpod*bypod;
cout << "You need " << s << "tiles." << endl;
system("pause");
return 0;
}
Using a debugger, you can easily find that you have a division by 0 in the following lline:
if (x%a == 0) {
brx = x / a;
}
You are doing an integer division on "a":
a = a / 100;
So if a is lower than 100, a will be 0. 10 / 100 = 0.1 = 0 when cast as int.
You should use double instead of int

Wierd C++ Problems, OpenGL game

Aight so, I'm in the process of making a simple terrain program, not exactly a game, but hey maybe someday. I'll start with describing the basics of how my program works. I'm using an two-dimension array to store the coordinates of the vertexes which make up a grid of triangles. The x and z values are assigned in the follow code:
//Sets up the array for the vertexes
int e = 0;
int p = 0;
for (int r = 0; r < 10; r++) {
for (int x = 0; x < 5; x++) {
grid[p][0] = x * 2;
grid[p][2] = e;
p++;
}
e += 2;
}
Okay, so the grid array is the one I use for storing the values of all the vertexes in the program, the first argument (the value in the first set of []) is used to choose a point, the second set of [] is the x, y, and z values, the code snippet above only sets values for the x and z coordinates.
The y value, height, is randomised at the start of the program using the following code:
//Random heights for the terrain
if (fir == true) {
for (int h = 0; h < 64; h++) {
grid[h][1] = rand() % 3;
}
fir = false;
}
And the code for drawing the triangles:
for (int q = 0; q < 11; q++) {
a = q * 5;
b = a + 1;
c = a + 5;
glBegin(GL_TRIANGLE_STRIP);
for (int dw = 0; dw < 8; dw++) {
//a
glColor3f(grid[a][1], grid[a][1], grid[a][1]);
glVertex3f(grid[a][0], grid[a][1], grid[a][2]);
//b
glColor3f(grid[b][1], grid[b][1], grid[b][1]);
glVertex3f(grid[b][0], grid[b][1], grid[b][2]);
//c
glColor3f(1, 0, 0);
glVertex3f(grid[c][0], grid[c][1], grid[c][2]);
a = c;
t = b;
b = a + 1;
c = t;
}
glEnd();
}
glutSwapBuffers();
}
The problem I'm having is that I can't make the size of the grid bigger without the program breaking, I would like to be able to change the size of the grid of triangles to whatever I like. when I try to change the for loop which goes through the x values (first code snippet) the program breaks, my movement speed drastically increases, moving the mouse has no effect on the camera rotation. When I do manage to find a set of values to work the grid of triangles is messed up, any points after the 5th row are all set to 0, I'll post the whole program, I don't know if it will run for everyone, but I think the problem is something that requires the whole program to be looked at in order to solve.
I think the problem may be due to variables being shared by different parts of the program, I have looked and looked but can't seem to find any cause. This is my last resort to solving this nightmare of a problem...
main.cpp
/*
*/
#include <iostream>
#include <glut.h>
#include <gl\GL.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cstdlib>
#include "vector3f.h"
using namespace std;
//Variables
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
const char* WINDOW_TITLE = "Terrain";
const float WALKING_SPEED = 5.0;
const float MOUSE_SENSITIVITY = 0.3;
const float MAX_TILT = 90.0;
float grid[200][3];
float LAST_TIME;
float CURRENT_TIME;
float DELTA_TIME;
bool KEY[256];
int a;
int b;
int c;
int t;
int MOUSE_LAST_X;
int MOUSE_LAST_Y;
int MOUSE_CURRENT_X;
int MOUSE_CURRENT_Y;
int MOUSE_DELTA_X;
int MOUSE_DELTA_Y;
float red;
float green;
float blue;
bool fir = true;
//Object
vector3f CAMERA_POSITION;
vector3f CAMERA_ROTATION;
//Functions
void initialize();
void display();
void reshape(int w, int h);
void keyboardDown(unsigned char key, int x, int y);
void keyboardUp(unsigned char key, int x, int y);
void mouseMove(int x, int y);
void movement();
double degreesToRadians(double degrees);
double dsin(double theta);
double dcos(double theta);
double dtan(double theta);
void display() {
//cout << KEY[' '] << endl;
movement();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
//Camera transformations
glRotatef(CAMERA_ROTATION.x, 1, 0, 0);
glRotatef(CAMERA_ROTATION.y, 0, 1, 0);
glRotatef(CAMERA_ROTATION.z, 0, 0, 1);
glTranslatef(-CAMERA_POSITION.x, -CAMERA_POSITION.y, CAMERA_POSITION.z);
//Draw the basic triangle
glBegin(GL_TRIANGLES);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(-1.0, -1.0, -3.0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, -3.0);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(10.0, -1.0, -3.0);
glEnd();
/*
1 0,0,0
2 2,0,0
3 4,0,0
4 6,0,0
5 0,0,2
6 2,0,2
7 4,0,2
8 6,0,2
9 0,0,4
10 2,0,4
11 4,0,4
12 6,0,4
13 0,0,6
14 2,0,6
15 4,0,6
16 6,0,6
*/
/*//Option 1 (2 for loops, four if statements)
for (int p = 0; p < 16; p++) {
for (int x = 0; x < 7; x += 2) {
grid[p][0] = x;
}
grid[p][1] = 0;
if (p < 4) {
grid[p][2] = 0;
}
if (p < 8 && p >= 4) {
grid[p][2] = 2;
}
if (p < 12 && p >= 8) {
grid[p][2] = 4;
}
if (p < 16 && p >= 12) {
grid[p][2] = 6;
}
}
*/
//Option 2 (three for loops)
//Sets up the array for the vertexes
int e = 0;
int p = 0;
for (int r = 0; r < 10; r++) {
for (int x = 0; x < 5; x++) {
grid[p][0] = x * 2;
grid[p][2] = e;
p++;
}
e += 2;
}
//Random heights for the terrain
if (fir == true) {
for (int h = 0; h < 64; h++) {
grid[h][1] = rand() % 3;
}
fir = false;
}
//cout << "point 0: " << grid[0][0] << ", " << grid[0][1] << ", " << grid[0][2] << endl;
//cout << "point 1: " << grid[1][0] << ", " << grid[1][1] << ", " << grid[1][2] << endl;
//cout << "point 2: " << grid[2][0] << ", " << grid[2][1] << ", " << grid[2][2] << endl;
//cout << "point 3: " << grid[3][0] << ", " << grid[3][1] << ", " << grid[3][2] << endl;
//cout << "point 4: " << grid[4][0] << ", " << grid[4][1] << ", " << grid[4][2] << endl;
//cout << "point 5: " << grid[5][0] << ", " << grid[5][1] << ", " << grid[5][2] << endl;
//cout << "point 6: " << grid[6][0] << ", " << grid[6][1] << ", " << grid[6][2] << endl;
//cout << "point 7: " << grid[7][0] << ", " << grid[7][1] << ", " << grid[7][2] << endl;
//cout << "point 8: " << grid[8][0] << ", " << grid[8][1] << ", " << grid[8][2] << endl;
//cout << "point 9: " << grid[9][0] << ", " << grid[9][1] << ", " << grid[9][2] << endl;
//cout << "point 10: " << grid[10][0] << ", " << grid[10][1] << ", " << grid[10][2] << endl;
//cout << "point 11: " << grid[11][0] << ", " << grid[11][1] << ", " << grid[11][2] << endl;
//cout << "point 12: " << grid[12][0] << ", " << grid[12][1] << ", " << grid[12][2] << endl;
//cout << "point 13: " << grid[13][0] << ", " << grid[13][1] << ", " << grid[13][2] << endl;
//cout << "point 14: " << grid[14][0] << ", " << grid[14][1] << ", " << grid[14][2] << endl;
//cout << "point 15: " << grid[15][0] << ", " << grid[15][1] << ", " << grid[15][2] << endl;
for (int q = 0; q < 11; q++) {
a = q * 5;
b = a + 1;
c = a + 5;
glBegin(GL_TRIANGLE_STRIP);
for (int dw = 0; dw < 8; dw++) {
//a
glColor3f(grid[a][1], grid[a][1], grid[a][1]);
glVertex3f(grid[a][0], grid[a][1], grid[a][2]);
//b
glColor3f(grid[b][1], grid[b][1], grid[b][1]);
glVertex3f(grid[b][0], grid[b][1], grid[b][2]);
//c
glColor3f(1, 0, 0);
glVertex3f(grid[c][0], grid[c][1], grid[c][2]);
a = c;
t = b;
b = a + 1;
c = t;
}
glEnd();
}
glutSwapBuffers();
}
void keyboardDown(unsigned char key, int x, int y) {
KEY[key] = true;
}
void keyboardUp(unsigned char key, int x, int y) {
KEY[key] = false;
}
void movement() {
CURRENT_TIME = ((float)glutGet(GLUT_ELAPSED_TIME) / 1000);
DELTA_TIME = CURRENT_TIME - LAST_TIME;
LAST_TIME = CURRENT_TIME;
MOUSE_DELTA_X = MOUSE_CURRENT_X - MOUSE_LAST_X;
MOUSE_DELTA_Y = MOUSE_CURRENT_Y - MOUSE_LAST_Y;
MOUSE_LAST_X = MOUSE_CURRENT_X;
MOUSE_LAST_Y = MOUSE_CURRENT_Y;
CAMERA_ROTATION.y += (float)MOUSE_DELTA_X * MOUSE_SENSITIVITY;
CAMERA_ROTATION.x += (float)MOUSE_DELTA_Y * MOUSE_SENSITIVITY;
if (CAMERA_ROTATION.x > MAX_TILT) {
CAMERA_ROTATION.x = MAX_TILT;
}
if (CAMERA_ROTATION.x < -MAX_TILT) {
CAMERA_ROTATION.x = -MAX_TILT;
}
if (KEY['w'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y);
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.x + 180);
}
if (KEY['s'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 180);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 180);
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.x);
}
if (KEY['a'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 270);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 270);
}
if (KEY['d'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 90);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 90);
}
if (KEY[' '] == true) {
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME);
}
if (KEY['e'] == true) {
exit(1);
}
}
void mouseMove(int x, int y) {
MOUSE_CURRENT_X = x;
MOUSE_CURRENT_Y = y;
}
double degreesToRadians(double degrees){
return degrees * M_PI / 180;
}
double dsin(double theta) {
return sin(degreesToRadians(theta));
}
double dcos(double theta) {
return cos(degreesToRadians(theta));
}
double dtan(double theta) {
return tan(degreesToRadians(theta));
}
void reshape(int w, int h) {
//Stops the ratio from dividing by 0
if (h == 0) {
h = 1;
}
float fRatio = (float)w / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(60, fRatio, 0.1, 1000);
glMatrixMode(GL_MODELVIEW);
}
void initialize() {
glClearColor(0.0, 0.0, 102.0 / 255.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}
int main(int iArgc, char** cArgv) {
//Initialise OpenGL and GLUT
glutInit(&iArgc, cArgv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
//Setup window
glutInitWindowPosition(0, 0);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow(WINDOW_TITLE);
//Setup GLUT callback functions
initialize();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(display);
glutKeyboardFunc(keyboardDown);
glutKeyboardUpFunc(keyboardUp);
glutMotionFunc(mouseMove);
glutPassiveMotionFunc(mouseMove);
glEnable(GL_DEPTH_TEST);
//Enter main loop
glutMainLoop();
return 0;
}
Some quick remarks:
your loops access different number of points!
1st loop (r, x) initialize 50 points
2nd loop (h) initialize 64 points
3rd loop (q, dw) access 59 points
glColor3f values should be between 0 and 1 but, using your grid y values, you get 0, 1 or 2
beware of the gimbal lock problem when trying to rotate your view!

Print heart shape with words inside

I am trying to draw a heart shape with words inside as a surprise for a friend tomorrow but i cant figure out how to put the words inside the heart . I am only able to draw the heart shape
Code to draw Heart
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x,y;
double size=10;
for (x=0;x<size;x++)
{
for (y=0;y<=4*size;y++)
{
double dist1 = sqrt( pow(x-size,2) + pow(y-size,2) );
double dist2 = sqrt( pow(x-size,2) + pow(y-3*size,2) );
if (dist1 < size + 0.5 || dist2 < size + 0.5 )
cout<<"V";
else
cout<<" ";
}
cout<<endl;
}
for ( x=1;x<2*size;x++)
{
for(y=0;y<x;y++)
cout<<" ";
for (y=0; y<4*size + 1 - 2*x; y++)
cout<<"V";
cout<<endl;
}
system("PAUSE");
}
I need help putting words inside the heart shape
Pretty much the same as the other answer but I had already started so I thought I may as well finish. As a bonus you can specify what line of the "V" shape it prints on.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x, y, size=10;
string message(" hello there ");
int print_line = 4;
if (message.length() % 2 != 0) message += " ";
for (x=0;x<size;x++)
{
for (y=0;y<=4*size;y++)
{
double dist1 = sqrt( pow(x-size,2) + pow(y-size,2) );
double dist2 = sqrt( pow(x-size,2) + pow(y-3*size,2) );
if (dist1 < size + 0.5 || dist2 < size + 0.5 ) {
cout << "V";
}
else cout << " ";
}
cout<<"\n";
}
for (x=1;x<2*size;x++)
{
for(y=0;y<x;y++) cout << " ";
for (y=0; y<4*size + 1 - 2*x; y++)
{
if (x >= print_line - 1 && x <= print_line + 1) {
int idx = y - (4*size - 2*x - message.length()) / 2;
if (idx < message.length() && idx >= 0) {
if (x == print_line) cout<<message[idx];
else cout << " ";
}
else cout << "V";
}
else cout << "V";
}
cout<<endl;
}
}
You could just wait until you get to a pre-specified position in the heart and print out a message instead of the "V"s, like this:
char message[] = " MY MESSAGE ";
for ( x=1;x<2*size;x++)
{
for(y=0;y<x;y++)
cout<<" ";
for (y=0; y<4*size + 1 - 2*x; y++)
{
if (x == 1 && y == (2*size - strlen(message)/2))
{
cout << message;
y += strlen(message)-1;
}
else
cout<<"V";
}
cout<<endl;
}
The y += strlen(message)-1; is to advance the column index according to the number of characters printed. (2*size - strlen(message)/2) is a position which will center the string.
If you want to obfuscate the code as much as possible (so you don't know what the message is until the code runs), you could use a hash table to map positions to letters or something like that.
Try this code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
cout<<"Print Heart....C++\n";
int n=7; //size of heart
for(int i=-3*n/2;i<=n;i++){
for(int j=-3*n/2;j<=3*n/2;j++){
/* inside either diamond or two circles */
if((abs(i)+abs(j)<n)||((-n/2-i)*(-n/2-i)+(n/2-j)*(n/2-j)<=n*n/2)||((-n/2-i)*(-n/2-i)+(-n/2-j)*(-n/2-j)<=n*n/2)){
cout<<"v ";
}
else{
cout<<" ";
}
}
cout<<"\n";
}
cout<<"\n\n\nPlease don\'t forget to like.... :) :) :) \n";
cout<<"Credit: Heart Of Java : https://code.sololearn.com/caiu85u6tr30/#java";
return 0;
}
Demo here: https://code.sololearn.com/cuXe0axsK8R2/#cpp

How to check if mouseclick is in an area

Ok So I have a few images I am putting on a screen, Really all you would need to know is each glvertex2f() is a point, thus 4 points connected is an area. Each glVertex2f is created by and X,Y . I would like to save this area range so when i do a mouse click and get the x,y result, I can test to see if the mouseclick x,y is inside this area.
So here is where i create the area
for( int z = 0; z < 6; z++ )
{
if( game->player1.Blockbestand[z] > 0 )
{
glLoadIdentity();
xoff = (z/4.0f);
yoff = (floor(xoff))/4.0f;
glBegin(GL_QUADS);
glTexCoord2f(0/4 + xoff,0/4 + yoff); glVertex2f( x1,game->camera.height-y1);
glTexCoord2f(0/4 + xoff,1.0/4 + yoff); glVertex2f( x2,game->camera.height-y1 );
glTexCoord2f(1.0/4 + xoff,1.0/4 + yoff); glVertex2f( x2,game->camera.height-y2 );
glTexCoord2f(1.0/4 + xoff,0/4 + yoff); glVertex2f( x1,game->camera.height-y2 );
glEnd();
x1= x2+10;
x2 = x1+30;
xoff = (z/4.0f);
yoff = (floor(xoff))/4.0f;
}
}
and here is where i get the mouse click
for (std::list<MouseState>::iterator it = clicks->begin(); it != clicks->end(); it++) {
if (it->leftButton == true){
std::cout << "Left click!\n";
std::cout << "x: " << it->x << "\n";
std::cout << "y: " << it->y << "\n";
}
}
So i assume i can save the area in an array somehow. and then when ever a leftbutton click is true , i get the x, y and look in the array to see if its in the area.. but no clue how to do this..
First save the 4 points in an array
locationCheck[m][n] = x1;
locationCheck[m][n+1] = x2;
locationCheck[m][n+2] = game->camera.height-y1;
locationCheck[m][n+3] = game->camera.height-y2;
m++;
then check if the x/y of mouse is between the 4 points like so.
void GameScreen::menuClickCheck(int x,int y){
int m = 0;
int n=0;
while (m < 32){
if (locationCheck[m][n] < x && locationCheck[m][n+1] > x)
if (locationCheck[m][n+2] > y && locationCheck[m][n+3] < y)
{
switch (m)
{
case 0 : cout << "Type=DefaultLand \n";
break;
case 1 : cout << "Type=Lava \n";
break;
case 2 : cout << "Type=Stone \n";
break;
}//end switch
m=32;
}//endif
m++;
}//whileloop
}