Visual C++ Debug Assertion Fail - c++

When Ever I compile my program it say "Debug Assertion Failed".
And when I click ignore twice my app shows up.
How can I fix it?
The whole code is below in case you want to test it for your self. The app increases in number as the scroll bar is moved to the right and decreases as the scroll bar is moved to the left. But my main problem is the debug assertion failed. If you can please post the part of the code that has problem and how I can fix it or fix it and post the code. Is there any way to get rid of that run time error with out using a try and catch. I mean to fix that problem please. This is a project and I have only a week and a half to do it. If you can help me with this project your help would be greatly appreciated. I am fairly new to visual c++. Part of the error is:
Program E:\BHCCHardwareStore\Debug\BHCCHardwareStore.exe FIle:f\dd\vctools\vc7libs\ship\atlmfc\src\mfc\appcore.cpp Line: 196. For information on how your program can cause an assertion failure see the Visual C++ documentation on asserts.
(Press Retry to debug the application).
Now when I click ignore it kind of displays the app perfectly fine. And the app seems to work just fine. How can I fix this error This code is not the entire code I am cutting and pasting?
#include "stdafx.h"
#include <strstream>
#include <afxwin.h>
#include <string.h>
const int IDC_SB1 = 100;
const int IDC_CS1 = 101;
const int IDC_CS2 = 102;
const int IDC_BUTTON = 103;
const int MIN_RANGE = 0;
const int MAX_RANGE = 100;
class CApp :public CWinApp
{
public:
virtual BOOL InitInstance();
};
CApp App;
class CSource :public CFrameWnd
{
CScrollBar*sb1;
CStatic* cs1;
CStatic* cs2;
CButton* button;
public:
CSource();
afx_msg void OnHScroll(UINT nSBCode,
UINT nPos, CScrollBar* pSccrollBar);
afx_msg void handleButton();
DECLARE_MESSAGE_MAP();
};
BEGIN_MESSAGE_MAP(CSource, CFrameWnd)
ON_WM_HSCROLL()
ON_BN_CLICKED(IDC_BUTTON, handleButton)
END_MESSAGE_MAP()
//Window cONSTRUCTOR
CSource::CSource()
{
}
void CSource::OnHScroll(UINT nSBCode,
UINT nPos, CScrollBar* pScrollBar)
{
int pos, dividend = 0, holder = 0, x = 0;
char array[9];
//;
pos = pScrollBar->GetScrollPos();
switch (nSBCode)
{
case SB_LINEUP:
pos -= 1;
break;
case SB_LINEDOWN:
pos += 1;
break;
case SB_PAGEUP:
pos -= 10;
break;
case SB_PAGEDOWN:
pos += 10;
break;
case SB_TOP:
pos = MIN_RANGE;
break;
case SB_BOTTOM:
pos = MAX_RANGE;
break;
case SB_THUMBTRACK:
pos = nPos;
break;
default:
return;
}
if (pos < MIN_RANGE)
pos = MIN_RANGE;
else if (pos > MAX_RANGE)
pos = MAX_RANGE;
sb1->SetScrollPos(pos, TRUE);
//Set the labels to the new values
char s[100];
TCHAR s1[100];
std::ostrstream ostr(s, 100);
ostr << "Decimal Value = " << pos << std::ends;
for (int i = 0; i < 100; i++){
s1[i] = (TCHAR) s[i];
}
SetDlgItemText(IDC_CS1, s1);
ostr.seekp(std::ios::beg);
dividend = pos;
for (int y = 0; y < 9; y++)
array[y] = '0';
int remainder = dividend % 2;
int quotient = dividend / 2;
array[x] = (char)(remainder + 48);
do
{
remainder = quotient % 2;
quotient = quotient / 2;
array[++x] = (char)(remainder + 48);
} while (quotient != 0);
array[8] = '\0';
ostr << "Binary Value = " << _strrev(array) << std::ends;
SetDlgItemText(IDC_CS2, s1);
}
void CSource::handleButton()
{
int result;
result = MessageBox(_T("Are you sure?"), _T("Exiting"),
MB_ICONQUESTION | MB_YESNO);
if (result == IDYES)
{
Beep(1000, 100);
DestroyWindow();
}
else
Beep(200, 100);
}
//Initialize the application and the main window
BOOL CApp::InitInstance()
{
m_pMainWnd = new CSource();
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}

Your code (in VS2013) produces assertion in MFC code:
BOOL CWnd::ShowWindow(int nCmdShow)
{
ASSERT(::IsWindow(m_hWnd) || (m_pCtrlSite != NULL));
From your call:
m_pMainWnd->ShowWindow(m_nCmdShow);
You must create your window first, before you can show it.

Related

Mouse Does Not Move Automatically When Pressing Left Button

I'm coding a C++ program that makes a certain movement with the mouse by itself when I press the left mouse button, it has F1, F2, F3 keys and each key has a different movement, and then I press the left mouse button to execute that movement , but what is happening is that I have to hold down the F1 key and the left mouse button at the same time for it to work, I wanted to press the F1 key just once and then just hold down the left mouse button !
#include <iostream>
#include <string>
#include <Windows.h>
#include "patterns.h"
#define getLen(x) (sizeof(x)/sizeof(x[0]))
using namespace std;
typedef struct $ {
string name;
long **pattner;
int len;
int rpm;
}weapon_t;
weapon_t *LoadWeapon(string name, long recoil[][2], int len, int rpm);
float GetK(float dpi, float sensi);
DWORD GetTime(float rpm);
void ExecControl(weapon_t gun);
float K;
int main()
{
K = GetK(800, 0.95);
weapon_t *ak47 = LoadWeapon("AK-47", ak47_pattern, getLen(ak47_pattern), 600);
weapon_t *m4a4 = LoadWeapon("M4A4", m4a4_pattern, getLen(m4a4_pattern), 666);
weapon_t *ump45 = LoadWeapon("UMP-45", ump45_pattern, getLen(ump45_pattern), 666);
weapon_t* m4a1s = LoadWeapon("M4A1S", m4a1s_pattern, getLen(m4a1s_pattern), 600);
weapon_t* famas = LoadWeapon("FAMAS", famas_pattern, getLen(famas_pattern), 600);
while (true) {
if (GetAsyncKeyState(VK_F1)) {
ExecControl(*ak47);
}
if (GetAsyncKeyState(VK_F2)) {
ExecControl(*m4a4);
}
if (GetAsyncKeyState(VK_F3)) {
ExecControl(*m4a1s);
}
if (GetAsyncKeyState(VK_F4)) {
ExecControl(*ump45);
}
if (GetAsyncKeyState(VK_F5)) {
ExecControl(*famas);
}
Sleep(150);
}
return 0;
}
void ExecControl(weapon_t gun) {
system("cls");
cout << "Weapon:\t" << gun.name << "\nShots:\t" << gun.len << "\nVelocity:\t" << gun.rpm << "\n\n\n";
DWORD delay = GetTime(gun.rpm);
int index = 0;
while (GetAsyncKeyState(VK_LBUTTON) && index != gun.len) {
mouse_event(MOUSEEVENTF_MOVE, long(gun.pattner[index][0] * K), long(gun.pattner[index][1] * K), 0, 0);
index++;
Sleep(delay);
}
index = 0;
}
weapon_t *LoadWeapon(string name, long recoil[][2], int len, int rpm) {
int i;
weapon_t *gun = new weapon_t();
gun->name = name;
gun->len = len;
gun->rpm = rpm;
gun->pattner = new long*[len];
for (i = 0; i < len; i++) {
gun->pattner[i] = new long[2];
}
for (i = 0; i < len; i++) {
gun->pattner[i][0] = recoil[i][0];
gun->pattner[i][1] = recoil[i][1];
}
return gun;
}
float GetK(float dpi, float sensi) {
return (1140 / (dpi*sensi));
}
DWORD GetTime(float rpm) {
return DWORD((60 / rpm) * 1000);
}
The problem is that your code is looking at the mouse left button only while any F1..F5 key is currently held down, and then you are not looking at the keyboard again until the left button is released or the current gun is exhausted.
You need a different approach, such as a state machine. Keep track of the current gun that is equipped at any given time. On each iteration of the main loop, check for state changes first (ie, check if any F1..F5 key is held down, and if so then equip the associated gun), and then act on the current state (ie, regardless of the keyboard state, if the left button is down, and a gun is equipped, then advance the gun to its next position). Let the loop handle the repetitive work for you. This will allow you to check the keyboard for gun changes while the left button is held down.
Try something more like this:
#include <iostream>
#include <string>
#include <Windows.h>
#include "patterns.h"
#define getLen(x) (sizeof(x)/sizeof(x[0]))
using namespace std;
typedef struct $ {
string name;
long **pattner;
int len;
int rpm;
}weapon_t;
weapon_t* LoadWeapon(string name, long recoil[][2], int len, int rpm);
float GetK(float dpi, float sensi);
DWORD GetTime(float rpm);
float K = GetK(800, 0.95);
int main()
{
weapon_t *ak47 = LoadWeapon("AK-47", ak47_pattern, getLen(ak47_pattern), 600);
weapon_t *m4a4 = LoadWeapon("M4A4", m4a4_pattern, getLen(m4a4_pattern), 666);
weapon_t *ump45 = LoadWeapon("UMP-45", ump45_pattern, getLen(ump45_pattern), 666);
weapon_t *m4a1s = LoadWeapon("M4A1S", m4a1s_pattern, getLen(m4a1s_pattern), 600);
weapon_t *famas = LoadWeapon("FAMAS", famas_pattern, getLen(famas_pattern), 600);
weapon_t* guns[] = {ak47, m4a4, m4a1s, ump45, famas};
int gun_keys[] = {VK_F1, VK_F2, VK_F3, VK_F4, VK_F5};
weapon_t *gun = nullptr;
int gun_index = -1;
DWORD gun_delay = 150;
bool is_mouse_down = false;
while (true) {
for(int i = 0; i < 5; ++i) {
if (GetAsyncKeyState(gun_key[i]) && (gun != guns[i])) {
gun = guns[i];
system("cls");
cout << "Weapon:\t" << gun->name << "\nShots:\t" << gun->len << "\nVelocity:\t" << gun->rpm << "\n\n\n";
gun_delay = GetTime(gun->rpm);
gun_index = 0;
break;
}
}
if (GetAsyncKeyState(VK_LBUTTON) < 0) {
if (!is_mouse_down) {
is_mouse_down = true;
if (gun != nullptr)
gun_index = 0;
}
if (gun != nullptr && gun_index != gun->len) {
mouse_event(MOUSEEVENTF_MOVE, long(gun->pattner[gun_index][0] * K), long(gun->pattner[gun_index][1] * K), 0, 0);
++gun_index;
Sleep(gun_delay);
continue;
}
}
else
is_mouse_down = false;
Sleep(150);
}
return 0;
}
weapon_t* LoadWeapon(string name, long recoil[][2], int len, int rpm) {
weapon_t *gun = new weapon_t();
gun->name = name;
gun->len = len;
gun->rpm = rpm;
gun->pattner = new long*[len];
for (int i = 0; i < len; i++) {
gun->pattner[i] = new long[2];
gun->pattner[i][0] = recoil[i][0];
gun->pattner[i][1] = recoil[i][1];
}
return gun;
}
float GetK(float dpi, float sensi) {
return (1140 / (dpi*sensi));
}
DWORD GetTime(float rpm) {
return DWORD((60 / rpm) * 1000);
}

C++ How to make that a function runs only one

I use a C++\CLR project in Visual Studio 2017.At the time i try to manipulate the memory so i create a hack for a no name game and try to manipulate the game.
My problem is that I try to create a random integer and for that i use the function rand() in combination with firstSetRand srand().
using namespace System;
int * randomName()
{
srand((unsigned)time(0));
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
}
std::cout << name << std::endl;
return name;
}
This is my function for the random counts and here i call it:
int main(array<System::String ^> ^args)
{
while (true)
{
switch (inputCheat) //check which case match with the user input
{
case 4:
Console::WriteLine("test: ");
random:: randomName(firstSetRand);
//WriteProcessMemory(handle, (LPVOID)localName, &inputNumber, sizeof(), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
}
}
Sleep(200);
}
The problem is because that´s a while(true) loop and I call the function multiple times. And I don't know how to make that srand() function is only called once time i get always the same random number.
I am coming from Java. In Java i would do the whole code in a class and than i would write the variable in the constructor but i think that's not possible in C++. Because when i do the whole code in a class i get the error:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main##YAHXZ) AssaultCubeHack C:\Users\schup\source\repos\AssaultCubeHack\AssaultCubeHack\MSVCRTD.lib(exe_main.obj) 1
Here is the full code of my project:
// AssaultCubeWithClr.cpp: Hauptprojektdatei.
#include "stdafx.h"
using namespace System;
struct InitRandHelper
{
InitRandHelper() { srand((unsigned)time(0)); }
};
int * randomName()
{
static InitRandHelper init;
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
}
std::cout << name << std::endl;
return name;
}
void StartText()
{
//Text to See in the Console
Console::ForegroundColor = System::ConsoleColor::Green;
Console::WriteLine("Welcome to my Cheat for AssaultCube!");
Console::WriteLine("------------------------------------");
Console::WriteLine("1. For More Health type in: 1.");
Console::WriteLine("2. For More Ammo type in: 2");
Console::WriteLine("3. For More Armor type in: 3");
Console::WriteLine("4. For Turn on Name changer: 4");
}
int main(array<System::String ^> ^args)
{
DWORD playerBaseAdress = 0x00509b74;
DWORD offsePrimaryAmmo = 0x128;
DWORD offsetPistolAmmo = 0x13C;
DWORD offsetArmor = 0xFC;
DWORD offsetHealth = 0xF8;
DWORD offsetRoll = 0x0080;
DWORD baseforName = 0x005028FC;
static bool firstSetRand = true;
int inputCheat;
int inputNumber;
DWORD processId;
DWORD localPlayer;
DWORD localName;
DWORD primaryAmmo;
DWORD pistolAmmo;
DWORD health;
DWORD armor;
DWORD roll;
bool firstExecute = true;
HWND hwnd = FindWindowA(NULL, "AssaultCube"); //Find Window with Name AssaultCube
StartText(); //function call
while (true)
{
if (hwnd == NULL) //Check if the game exists
{
if (firstExecute == true)
{
Console::ForegroundColor = System::ConsoleColor::Red;
Console::WriteLine("ERROR: The Game couldn´t found!");
firstExecute = false;
}
}
else
{
GetWindowThreadProcessId(hwnd, &processId); //Get Process id from the Window
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, false, processId);
if (handle == NULL) //check if process id exsits
{
Console::ForegroundColor = System::ConsoleColor::Red;
Console::WriteLine("ERROR: Wrong Process Id!");
Console::ForegroundColor = System::ConsoleColor::Green;
}
else
{
ReadProcessMemory(handle, (LPCVOID)playerBaseAdress, &localPlayer, sizeof(playerBaseAdress), NULL); //Read the local adresse and save it in localPlayer
ReadProcessMemory(handle, (LPCVOID)baseforName, &localName, sizeof(playerBaseAdress), NULL);
primaryAmmo = localPlayer + offsePrimaryAmmo;
pistolAmmo = localPlayer + offsetPistolAmmo;
health = localPlayer + offsetHealth;
armor = localPlayer + offsetArmor;
roll = localPlayer + offsetRoll;
std::cin >> inputCheat; //wait for user input
switch (inputCheat) //check which case match with the user input
{
case 1:
Console::WriteLine("Write how much Health you want: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)health, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 2:
Console::WriteLine("Write how much Ammo you want: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)primaryAmmo, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 3:
Console::WriteLine("Write how much Armor you want: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)armor, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 4:
Console::WriteLine("Random Number: ");
randomName();
//WriteProcessMemory(handle, (LPVOID)localName, &inputNumber, sizeof(), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
case 5:
Console::WriteLine("test: ");
std::cin >> inputNumber;
WriteProcessMemory(handle, (LPVOID)roll, &inputNumber, sizeof(inputNumber), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
default:
Console::ForegroundColor = System::ConsoleColor::Red;
Console::WriteLine("ERROR: Wrong Entry!");
Console::WriteLine("Try a other input :D");
Console::ForegroundColor = System::ConsoleColor::Green;
break;
}
}
}
Sleep(200);
}
return 0;
}
Here you can see it doesn't work.
Solution 1
You can use a function static variable for that.
static bool firstTime = true;
if ( firstTime )
{
srand((unsigned)time(0));
firstTime = false;
}
Solution 2
If you don't want to pay the price of the check for each call of the function, you can use a helper class/struct.
struct InitRandHelper
{
InitRandHelper() { srand((unsigned)time(0)); }
};
int* randomName()
{
// Initialize the random number generator.
static InitRandHelper init;
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
}
std::cout << name << std::endl;
return name;
}
Solution 3
Call srand in main before the while loop begins.
int main(array<System::String ^> ^args)
{
srand((unsigned)time(0));
while (true)
{
switch (inputCheat) //check which case match with the user input
{
case 4:
Console::WriteLine("test: ");
random:: randomName(firstSetRand);
//WriteProcessMemory(handle, (LPVOID)localName, &inputNumber, sizeof(), NULL); //Write to the local adress memory and change the value
Console::WriteLine("\nWhat did you want to cheat up: ");
break;
}
}
Sleep(200);
}
and remove the call from random::randomName.
okay here the answer i found. Ther problem is this line:
std::cout << name << std::endl;
The Ouput in the console is not the value rather its the adress from the array. To do it proper i have to it so:
int i = 1;
static int name[5];
for (int i = 1; i < 5; i++)
{
name[i] = 97 + rand() % 122;
std::cout << name[i] << std::endl; //this line is the right thing to do it
}
return name;

C++ Win32: HDC's and debugging

I'm writing code for what should be a tetris game. It's early on, and right now it only displays a single piece (the piece that would be "falling" at that point), which is all it should do. The up arrow allows you to cycle forward (specifically only) through a randomly generated sequence of pieces (using the "bag" method). And, using the left and right arrows, you can rotate the pieces. Anyways, it's coded on a win32 platform, and I've found that after a certain number of frames (running WM_PAINT) the main HDC turns null and everything stops. It takes roughly twice as many frames of holding down the right or left arrow keys to achieve this as it does to hold down the up arrow key. Something odd is that after about 1000 frames the area of the console that I'm actively painting over (a 600x600 px frame) will go black (the hdc has not been nullified yet), and it's only when the up arrow is pressed that the hdc is nullified. What I suspect to be the problem is that the methods called when the up arrow key is pressed pass the hdc as a parameter to the in-class methods (tell me if this is poor practice or there's something I should be doing instead). I think the hdc might be corrupting or something (honestly I have no idea). The left and right arrow keys don't directly call methods with HDC's as a parameter. Because of case labels and how the win32 template is designed, I have to store an HDC who's scope falls out of any case-label, so that I can access the window's handle outside of the paint case (I feel like this is poor practice, but I'd like to understand why before I go out of my way to find a new way). I'll post the code, the stored HDC is called mainHDC, and it's defined just before the main case statement. To clue you in, I'll give an overview of the code structure:
The main .cpp file, which contains the basic win32 program, calls the Tetris class constructor in WM_PAINT and stores it universally like the mainHDC is and, when prompted, the "next" method (which brings the next piece), the "turnPiece" method (which rotates the piece clockwise or counter-clockwise based on the paramter), and the "paint" method which updates the screen, repainting the current piece. In the tetris class (which is in it's own header file), there is a sub-class called "pieces" which contain information about its objects, that are defined by another level of sub-classes named with a single character depicted by the pieces shape. The shape, color, and size of the pieces are stored in a 2d array of pointers (using COLORREF). "Pieces" contains its own "DrawObject" method which draws the object that calls it (which like all of the drawing/painting methods have an HDC as an argument). There's also a method that rotates the shape called "turnTet" (the "turnPiece" method relays the call from the main .cpp file to "pieces"). The only other applicable methods are those found in the "tetris" class which are "paint" and "next" (they ultimately paint the object). The WM_KEY cases, excluding the VK_UP case, don't use the saved hdc but rather use InvalidateRect().
Here's the applicable part of the .cpp file
int tempt = 2;
int tempvar = 0;
tetris *mainOBJ;
HDC mainHDC;
HDC testHDC;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_KEYDOWN:
switch (wParam) {
case VK_LEFT:
mainOBJ->turnPiece(false);
InvalidateRect(hWnd, 0, FALSE);
break;
case VK_RIGHT:
mainOBJ->turnPiece(true);
InvalidateRect(hWnd, 0, FALSE);
break;
case VK_UP:
mainOBJ->next(mainHDC);
InvalidateRect(hWnd, 0, FALSE);
break;
}
break;
case WM_COMMAND:
//Non-applicable & has not been changed
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
mainHDC = hdc;
HPEN oldP;
HPEN newP;
COLORREF qLC;
qLC = RGB(0, 0, 0);
newP = CreatePen(PS_SOLID, 1, qLC);
oldP = (HPEN) SelectObject(hdc, newP);
tempt++;
//USED FOR COUNTING FRAMES WITH DEBUGGER
if (tempt % 1 == 0) {
if (tempvar == 0) {
//CONSTRUCTOR CALL
mainOBJ = new tetris(hdc);
tempvar++;
}
//PAINT METHOD CALL
mainOBJ->paint(hdc);
}
if (hdc == NULL) {
int x = 3;
int y = x + 3; //SET DEBUG_BREAK POINT HERE
}
testHDC = hdc;
SelectObject(hdc, oldP);
DeleteObject(newP);
EndPaint(hWnd, &ps);
}
break;
}
}
The header file, which contains the Tetris and piece classes
class tetris {
public:
class pieces {
private:
COLORREF **test;
int size;
public:
//Abbreviated for space
class O {};
class I {};
class S {};
class Z {};
class T {};
class L {};
class J {};
void setSize(int a) {
//Initializing the piece-array
test = new COLORREF*[a];
size = a;
int i = 0;
while (i < a) {
test[i] = new COLORREF[a];
i++;
}
}
void setShape(COLORREF **shape) {
test = shape;
}
void setColor(HDC hdc, COLORREF rgb) {
HPEN Penn = CreatePen(PS_SOLID, 1, rgb);
HPEN Peno = (HPEN)SelectObject(hdc, Penn);
}
static pieces getObject(char type) {
pieces Gen;
switch (type) {
case 'O':
{
//Identical (almost) to the other cases
O pcs = O();
Gen = *pcs.getObject();
return Gen;
}
break;
case 'I':
case 'S':
case 'Z':
case 'T':
case 'L':
case 'J':
return pieces();
}
void turnTet(bool clockwise) {
int i = 0;
int s;
COLORREF **shape;
int ter = size - 1;
shape = new COLORREF*[2];
while (i < size) {
shape[i] = new COLORREF[2];
s = 0;
while (s < size) {
shape[i][s] = def;
s++;
}
i++;
}
i = 0;
while (i < size) {
s = 0;
while (s < size) {
if (clockwise) {
shape[s][ter - i] = test[i][s];
}
else {
shape[ter - s][i] = test[i][s];
}
s++;
}
i++;
}
test = shape;
}
void drawObject(HDC hWnd) {
int i = 0;
int s;
while (i < size) {
s = 0;
while (s < size) {
setColor(hWnd, test[i][s]);
int scaleOfBox = 90;
DrawBox((s + 1) * scaleOfBox, (i + 1) * scaleOfBox, scaleOfBox - 1, scaleOfBox - 1, hWnd);
s++;
}
i++;
}
}
void DrawBox(int x, int y, int w, int h, HDC hdc) {
if (h < 0) {
h *= -1;
}
if (w < 0) {
w *= -1;
}
int i = 0;
while (i < h) {
MoveToEx(hdc, x, y + i, NULL);
LineTo(hdc, x + w, y + i);
i++;
}
}
};
tetris(HDC hdc) {
refresh();
bagp[cur].drawObject(hdc);
}
void next(HDC hdc) {
bagp[cur].DrawBox(0, 0, 600, 600, hdc);
bagp[cur].drawObject(hdc);
cur++;
if (cur > 6) {
refresh();
}
}
void turnPiece(bool clockwise) {
bagp[cur].turnTet(clockwise);
}
void refresh() {
srand(time(NULL));
bag[0] = rand() % 7;
int i = 1;
while (i < 7) {
bool open = false;
cur = i;
while (!open) {
bag[i] = rand() % 7;
int s = 1;
open = true;
while (s <= i) {
if (bag[i] == bag[i - s]) {
open = false;
}
s++;
}
}
i++;
}
cur = 0;
while (cur < 7) {
switch (bag[cur]) {
case 0:
bagp[cur] = pieces::getObject('O');
break;
case 2:
bagp[cur] = pieces::getObject('T');
break;
case 1:
bagp[cur] = pieces::getObject('I');
break;
case 3:
bagp[cur] = pieces::getObject('S');
break;
case 4:
bagp[cur] = pieces::getObject('Z');
break;
case 5:
bagp[cur] = pieces::getObject('L');
break;
case 6:
bagp[cur] = pieces::getObject('J');
break;
}
cur++;
}
cur = 0;
}
void paint(HDC hdc) {
COLORREF temp = def;
bagp[cur].setColor(hdc, temp);
bagp[cur].DrawBox(0, 0, 600, 600, hdc);
bagp[cur].drawObject(hdc);
}
private:
int bag[7];
int cur;
pieces bagp[7];
};
I don't understand why the HDC nullifies like it does. Once again I suspect it's related to how the hdc is passed as a parameter or maybe how I'm saving the hdc. Help...please (and thank you).
Ooh, old school windows programming...
This may not be the entirety of the problem, but in your setColor function you're creating a Pen with CreatePen but never calling DeleteObject on it. This will leak the resource and eventually cause problems when Windows runs out of resource handles for objects.
Also, the Device Context returned by BeginPaint is (generally) only valid until EndPaint is called (unless you specify otherwise in the CreateWindow call, if I remember rightly). This can be another source of handle leakage.
In the Process tab of Task Manager, you can add the "GDI objects" column which will have an increasing number as your program runs if you're leaking handles. I saw this once with something I wrote way back when.

detecting a hard drive in the IDE

I am trying to detect the drive letter in Windows. Drive is a primary drive in second IDE channel. I am using GetLogicalDrives().
But this does not tell me I am accessing IDE primary drive.
Here is an example:
#include <cstdint>
#include <windows.h>
#include <cstdio>
const char* GetTypeOfDrive(const char* Drive)
{
const char* Result = NULL;
unsigned int DriveType = GetDriveType(Drive);
switch(DriveType)
{
case DRIVE_FIXED:
Result = "Hard disk";
break;
case DRIVE_CDROM:
Result = "CD/DVD";
break;
case DRIVE_REMOVABLE:
Result = "Removable";
break;
case DRIVE_REMOTE:
Result = "Network";
break;
default:
Result = "Unknown";
break;
}
return Result;
}
int GetLogicalDrivesList(char Drives[26])
{
int Res = 0;
DWORD DrivesMask = GetLogicalDrives();
for (int I = 0; I < 26; ++I)
{
if (DrivesMask & (1 << I))
{
Drives[Res++] = 'A' + I;
}
}
return Res;
}
int main()
{
char temp[4];
char drives[26];
int drive_count = GetLogicalDrivesList(drives);
for (int i = 0; i < drive_count; ++i)
{
sprintf(temp, "%c:/", drives[i]);
printf("%c is a %s\n", drives[i], GetTypeOfDrive(temp));
}
}

Getting Eclipse's C++ parser to work with Emscripten

I'm having a few problems with Eclipse's C++ parser. I've been using it with Emscripten and found the code completion, call hierarchy, documentation popup, code analysis and related features to be very useful, but it's been bothering me that the parser isn't totally working. Especially with this new problem with using vectors.
The first parsing error is on std::vector<SDL_Rect> box; with the error being:
Symbol 'vector' could not be resolved
And then on emscripten_set_main_loop(game_loop, 60, 1); I get this error:
Function 'usleep' could not be resolved
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <emscripten.h>
#include <stdarg.h>
#include <libcxx/vector>
///GLOBAL VARIABLES
SDL_Surface* bitmap;
SDL_Surface* screen;
SDL_Rect source;
SDL_Rect destination;
///second sprite
SDL_Surface* bitmap2;
SDL_Rect source2;
SDL_Rect destination2;
/// Side Scrolling variables:
SDL_Rect camera;
SDL_Rect offset;
SDL_Rect offset2;
int level_width = 480 * 5;
int level_height = 640;
bool gameRunning = true;
class buttonpresses {
public:
bool leftButton;
bool rightButton;
bool jumpButton;
};
int movementspeed = 5;
int jumpspeed = 2;
bool jumpenabled = false;
int jumpduration = 0;
int maxjump = 20;
int leftmomentum = 1;
int rightmomentum = 1;
int lastdestination;
int countDestination = 0;
int maxmomentum = 5;
buttonpresses charactermovement;
/// Collision detection
std::vector<SDL_Rect> box;
///MAIN LOOP
void game_loop() {
// EVENT HANDLING
SDL_PumpEvents();
Uint8 *keystate = SDL_GetKeyboardState(NULL);
if (keystate[SDLK_ESCAPE]) {
gameRunning = false;
printf("Game Stopping!!!!!!\n");
SDL_Quit();
exit(0);
}
if (keystate[SDLK_LEFT]) {
// printf("Left Key\n");
charactermovement.leftButton = true;
}
if (keystate[SDLK_LEFT] == false) {
charactermovement.leftButton = false;
}
if (keystate[SDLK_RIGHT]) {
// printf("Right Key\n");
charactermovement.rightButton = true;
}
if (keystate[SDLK_RIGHT] == false) {
charactermovement.rightButton = false;
}
if (keystate[SDLK_SPACE]) {
// printf("Space Key\n");
charactermovement.jumpButton = true;
}
if (keystate[SDLK_SPACE] == false) {
charactermovement.jumpButton = false;
}
// printf("Game Running..\n");
// LOGIC
//character movement
if (charactermovement.rightButton) {
destination.x = destination.x + movementspeed;
}
if (charactermovement.leftButton) {
destination.x = destination.x - movementspeed;
}
if (charactermovement.jumpButton && jumpenabled) {
destination.y = destination.y - jumpspeed;
jumpduration++;
}
destination.x = destination.x + rightmomentum - leftmomentum;
if (destination.y >= 200) {
jumpenabled = true;
// printf ("jump enabled\n");
}
if (jumpduration >= maxjump) {
jumpenabled = false;
}
if (destination.y >= 200) {
// printf ("destination y:");
// printf ("%d\n", destination.y);
jumpduration = 0;
}
//if (jumpenabled != true){
// printf ("jump disabled\n");
//}
//if (jumpenabled == true){
// printf ("jump enabled\n");
// printf ("jump duration: ");
// printf ("%d\n", jumpduration);
//}
//momentum
//save position every 5 interations
if (countDestination > 5) {
lastdestination = destination.x;
countDestination = 0;
} else {
countDestination++;
}
//printf ("last location: ");
//printf ("%d\n", destination.x);
//
//printf ("current location: ");
//printf ("%d\n", lastdestination);
// increase momentum in direction your moving in (relative to previous location)
if (lastdestination > destination.x) {
// printf ("right if running \n ");
if (rightmomentum > 0) {
rightmomentum--;
} else if (leftmomentum < maxmomentum) {
leftmomentum++;
}
}
if (lastdestination < destination.x) {
// printf ("left if running \n ");
if (leftmomentum > 0) {
leftmomentum--;
} else if (rightmomentum < maxmomentum) {
rightmomentum++;
}
}
if (lastdestination == destination.x) {
if (leftmomentum > 0) {
leftmomentum--;
}
if (rightmomentum > 0) {
rightmomentum--;
}
}
printf("left momentum: ");
printf("%d\n", rightmomentum);
printf("right momentum: ");
printf("%d\n", leftmomentum);
//gravity
if (destination.y <= 200) {
destination.y++;
}
offset.x = destination.x - camera.x;
offset2.x = destination2.x - camera.x;
offset.y = destination.y - camera.y;
offset2.y = destination2.y - camera.y;
// RENDERING
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
SDL_BlitSurface(bitmap, &source, screen, &offset);
// RENDER SECOND SPRITE
SDL_BlitSurface(bitmap2, &source2, screen, &offset2);
//blank screen
SDL_Flip(screen);
camera.x++;
}
int main() {
SDL_Init( SDL_INIT_VIDEO);
// LOAD FILES
bitmap = IMG_Load("ninjagaiden3sheet1.png");
screen = SDL_SetVideoMode(640, 480, 0, SDL_HWSURFACE | SDL_DOUBLEBUF);
/// camera variables
camera.x = 0;
camera.y = 0;
camera.w = 640;
camera.h = 480;
/// end camera variables
// Part of the bitmap that we want to draw
source.x = 37;
source.y = 4;
source.w = 17;
source.h = 32;
// Part of the screen we want to draw the sprite to
destination.x = 100;
destination.y = 100;
destination.w = 65;
destination.h = 44;
//// second sprite
bitmap2 = IMG_Load("bat_transparent.png");
source2.x = 24;
source2.y = 63;
source2.w = 65;
source2.h = 44;
destination2.x = 940;
destination2.y = 100;
destination2.w = 65;
destination2.h = 44;
//// end second sprite
lastdestination = destination.x;
offset = destination;
offset2 = destination2;
charactermovement.leftButton = false;
charactermovement.rightButton = false;
charactermovement.jumpButton = false;
//START MAIN LOOP
emscripten_set_main_loop(game_loop, 60, 1);
return 0;
}
My includes tab for C++ in the "Paths and Symbols" properties looks like:
C:\Program Files\Emscripten\emscripten\1.12.0\system\include
C:\Program Files\Emscripten\emscripten\1.12.0\system\include\libc
C:\Program Files\Emscripten\emscripten\1.12.0\system\include\emscripten
C:\Program Files\Emscripten\emscripten\1.12.0\system\include\libcxx
In the Indexer settings I have the following enabled:
Index source files not included in the build
Index unused headers
Index all header variants
Index source and header files opened in editor
Allow heuristic resolution of includes
Skip files larger than: 8 MB
Does anyone know what's going on? Or what I can do to fix it?
Update:
I've fixed the error on parsing std::vector. It turns out that some of llvm/clang libraries use _LIBCPP_BEGIN_NAMESPACE_STD and _LIBCPP_END_NAMESPACE_STD definitions instead of using namespace std; and those defines are invisible to the parser unless __clang__ is defined.
So the solution is to go into the "Symbols" tab for C++ in the "Paths and Symbols" properties and add:
__clang__
In the "Add" dialog that pops up just put it in the Name: input field and press OK. This will also add many of the missing std namespace functions like cout cin etc.
I haven't found a fix for the usleep/emscripten_set_main_loop issue yet but this should be good enough to get the IDE's code completion and several related features to work. Though I'm still having some weird complicated parser issues with Eclipse so I think I'm going to abandon the search for a solution here and work with NetBeans for which I think I have every thing set up.