Jump to content
  • Advertisement
Sign in to follow this  
Reilz

Input question

This topic is 4880 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

so I have this code which is based on one of the projects in the Tricks windows book, which could draw random rectangles to the screen, so I decided to try and see if i could put together a little pong. so first a changed the code to draw 3 boxes: a player, a computer(I’m treating this as a one player game right now, I’m not really worrying about the other paddle yet), and a "ball." next i wanted to make the player paddle move, so i put together some input code, which sees if the up or down key has been pressed, and if so changes the coordinates of the paddle, but when I run the program the paddle responds very poorly, it jumps to the top of the screen and barley moves form there. Here’s the main game code:
void Game::GetInput()
{
	//if User hits up key we move the paddle up
	if (KEYDOWN(VK_UP))
	{
	   PlayerRect.top =- 1;
	   PlayerRect.bottom   = PlayerRect.top + 200;
	}

	if (KEYDOWN(VK_DOWN))
	{
	   PlayerRect.top =+ 1;
	   PlayerRect.bottom   = PlayerRect.top + 200;
	}
	return;
}



/////////////////////////////////////////////////////////////////////




Game::Init()
{
// this is called once after the initial window is created and
// before the main event loop is entered, do all your initialization
// here


	PlayerRect.top      = 200;
	PlayerRect.bottom   = PlayerRect.top + 200;
	PlayerRect.left     = 20;
	PlayerRect.right    = PlayerRect.left + 20;

	CPURect.top			= 200;
	CPURect.bottom		= CPURect.top + 200;
	CPURect.left		= 760;
	CPURect.right		= CPURect.left + 20;

	BallRect.top		 = 310;
	BallRect.bottom		 = BallRect.top + 20;
	BallRect.left		 = 390;
	BallRect.right	     = BallRect.left + 20;


pRenderer = new DDrawObj();

pRenderer->Init();

return 1;


} // end Game_Init


///////////////////////////////////////////////////////////



Game::Main()
{
// this is the main loop of the game, do all your processing
// here

	GetInput();

pRenderer->Render(PlayerRect, CPURect, BallRect );


// for now test if user is hitting ESC and send WM_CLOSE
if (KEYDOWN(VK_ESCAPE))
   SendMessage(main_window_handle,WM_CLOSE,0,0);

// return success or failure or your own return code here
return(1);

} // end Game_Main




/////////////////////////////////////////////////////////////



Game::Shutdown()
{
// this is called after the game is exited and the main event
// loop while is exited, do all you cleanup and shutdown here

	


	pRenderer->Shutdown();
	delete pRenderer;


// return success or failure or your own return code here
return(1);

} // end Game_Shutdown


here's the DDraw code if it matters
//DDraw Stuff///////////////////////////////////////////////


		LPDIRECTDRAW7         lpdd         = NULL;   // dd object
		LPDIRECTDRAWSURFACE7  lpddsPrimary = NULL;   // dd primary surface
		LPDIRECTDRAWSURFACE7  lpddsBack    = NULL;   // dd back surface
		LPDIRECTDRAWPALETTE   lpddpal      = NULL;   // a pointer to the created dd palette
		LPDIRECTDRAWCLIPPER   lpddClipper  = NULL;   // dd clipper
		PALETTEENTRY          palette[256];          // color palette
		PALETTEENTRY          save_palette[256];     // used to save palettes
		DDSURFACEDESC2        ddsd;                  // a direct draw surface description struct
		DDBLTFX               ddbltfx;               // used to fill
		DDSCAPS2              ddscaps;               // a direct draw surface capabilities struct
		HRESULT               ddrval;                // result back from dd calls
		DWORD                 start_clock_count = 0; // used for timing




//INTI FUNCTIONS////////////////////////////////////////////////



DDrawObj::ClipperSetup()
{
	



	LPRGNDATA      RgnData;

	lpdd->CreateClipper(0, &lpddClipper, NULL);

	RgnData = (LPRGNDATA)malloc(sizeof(RGNDATAHEADER)+
				sizeof(RECT));


	
	
	//RECT rect={win->ReturnX(),win->ReturnY(),win->ReturnWidth(),win->ReturnHeight()};
	RECT rect={0,0,SCREEN_WIDTH,SCREEN_HEIGHT};

	memcpy(RgnData->Buffer,&rect,sizeof(RECT));
	
	RgnData->rdh.dwSize=sizeof(RGNDATAHEADER);

	RgnData->rdh.iType=RDH_RECTANGLES;

	RgnData->rdh.nCount=1;

	RgnData->rdh.nRgnSize=sizeof(RECT);

	RgnData->rdh.rcBound.left=64000;

	RgnData->rdh.rcBound.top=64000;

	RgnData->rdh.rcBound.right=-64000;

	RgnData->rdh.rcBound.bottom=-64000;

	
	if(rect.left<RgnData->rdh.rcBound.left)

	RgnData->rdh.rcBound.left=rect.left;

	
	if(rect.top<RgnData->rdh.rcBound.top)

	RgnData->rdh.rcBound.top=rect.top;

	
	if(rect.right>RgnData->rdh.rcBound.right)

	RgnData->rdh.rcBound.right=rect.right;

	
	if(rect.bottom>RgnData->rdh.rcBound.bottom)

	RgnData->rdh.rcBound.bottom=rect.bottom;
	
	
	
	//set the Clip List
	lpddClipper->SetClipList(RgnData, 0);



	//attach the clipper
	lpddsBack->SetClipper(lpddClipper);
	
	
	//free the memeory
	delete RgnData;
	RgnData = NULL;

	
	return 1;
}



///////////////////////////////////////////////////////////




DDrawObj::SurfaceSetup()
{

	//Microsoft Says to Clear memory
	memset(&ddsd, 0, sizeof(ddsd));
	

	//fill in the stuct

	ddsd.dwSize = sizeof(ddsd);

	//enable data fields with values that will send valid data in
	//in this case  ddsCaps is used and DDSD_BACKBUFFER to say we want a back buffer
	
	ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;


	//set the nuber of back buffers
	ddsd.dwBackBufferCount = 1;


	//Request a Complex, flipable
	ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
						  DDSCAPS_COMPLEX|
						  DDSCAPS_FLIP;
	


	lpdd->CreateSurface(&ddsd, &lpddsPrimary, NULL);


	//this is needed by the call
	ddsd.ddsCaps.dwCaps = DDSCAPS_BACKBUFFER;

	//request the attached back buffer
	lpddsPrimary->GetAttachedSurface(&ddsd.ddsCaps, &lpddsBack);


	return 1;
}



//RGB Setup
DDrawObj::RGBModeSetup()
{

	
	//setup the surface
	SurfaceSetup();



	DDPIXELFORMAT ddpixel;  //used to hold info

	
	//clear mem and enter the size
	memset(&ddpixel, 0, sizeof(ddpixel));

	ddpixel.dwSize = sizeof(ddpixel);


   lpddsPrimary->GetPixelFormat(&ddpixel);

   
   if (ddpixel.dwFlags & DDPF_RGB)
   switch(ddpixel.dwRGBBitCount)

	{



	case 15://5.5.5 mode
		{
			//use "RGB16BIT555(r, g, b)   ((b & 31) + ((g & 31) << 5) + ((r & 31) << 10))" Macro
			BitMode = 555;
		} break;

	case 16:
		{
			//use the "RGB16BIT565(r, g, b)   ((b & 31) + ((g & 63) << 5) + ((r & 31) << 11))" Macro
			BitMode = 565;
		} break;
	
	case 24:
		{
			//use the "RGB16BIT565(r, g, b)   ((b & 31) + ((g & 63) << 5) + ((r & 31) << 11))" Macro
			BitMode = 24;
		} break;
	
	case 32:
		{
			//use the "RGB16BIT565(r, g, b)   ((b & 31) + ((g & 63) << 5) + ((r & 31) << 11))" Macro
			BitMode = 32;
		} break;
	
	default: break;
	
	
	}
	
	
	
	return 1;
}
	





//Palette Mode Setup////////////////////////////////////////

DDrawObj::PaletteSetUp()
{


/////Set Up the Paletted Mode////////////////////

		//Fill 'em With Colors

		for(int color=1; color < 255; color++)
		{
		//fill with a random value

			palette[color].peRed = rand()%256;
			palette[color].peGreen = rand()%256;
			palette[color].peBlue = rand()%256;

			palette[color].peFlags = PC_NOCOLLAPSE;
		}


		palette[0].peRed   = 0;
		palette[0].peGreen = 0;
		palette[0].peBlue  = 0;
		palette[0].peFlags = PC_NOCOLLAPSE;

		palette[255].peRed = 255;
		palette[255].peGreen = 255;
		palette[255].peBlue  = 255;
		palette[255].peFlags = PC_NOCOLLAPSE;


		//create the interface
		lpdd->CreatePalette(DDPCAPS_8BIT|
						    DDPCAPS_ALLOW256|
							DDPCAPS_INITIALIZE,
							palette,
							&lpddpal,
							NULL);



///////////////////////////////////////////////

	
	//setup the surface	
	SurfaceSetup();


	//attach the palette to the surface
	lpddsPrimary->SetPalette(lpddpal);

	return 1;
		
	}





/////////////////////////////////////////////////////////////


DDrawObj::Init()
{
// this is called once after the initial window is created and
// before the main event loop is entered, do all your initialization
// here


		//clear the pointer in the unlikely event it's been used before
		if(lpdd)
		{
		lpdd->Release();
		lpdd = NULL;
		}





		//Create the interface
		if(FAILED(DirectDrawCreateEx(NULL, (void **)&lpdd, IID_IDirectDraw7, NULL)))
		{MessageBox(NULL, "Failed to create interface", "Error", MB_OK);}
	
		//set cooperation level to normal for a windowed app
	
		if(FAILED(lpdd->SetCooperativeLevel(main_window_handle, DDSCL_FULLSCREEN|
													  DDSCL_ALLOWMODEX|
												      DDSCL_EXCLUSIVE|
												      DDSCL_ALLOWREBOOT)))
			MessageBox(NULL, "Failed to set co-op level", "Error", MB_OK);

		//set the display mode to the values defined in the header file
		if(FAILED(lpdd->SetDisplayMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, 0, 0)))
			MessageBox(NULL, "Failed to set display mode", "Error", MB_OK);



		//set var BitMode to the default 8 bits
		BitMode = 8;

/////////////////////////////////////////





//if it's 8 bit set up the palette		
if (SCREEN_BPP==8)
{	

	PaletteSetUp();	
	
}
		
if (SCREEN_BPP==16 || SCREEN_BPP==24 || SCREEN_BPP==32)
{
	
	
	if(FAILED(RGBModeSetup()))
	MessageBox(NULL, "Failed to setup RGB Mode", "Error", MB_OK);
}
		

	//flip buffers
	lpddsPrimary->Flip(NULL, DDFLIP_WAIT);
	
	WindowRect.top   = 100;
	WindowRect.left  = 100;
	WindowRect.right = SCREEN_WIDTH;
	WindowRect.bottom= SCREEN_HEIGHT;



	//setup the clipper
	ClipperSetup();

// return success or failure or your own return code here
return(1);

} // end DDRawObj::Init



////////////////////////////////////////////////////////////////////


DDrawObj::Shutdown()
{
// this is called after the game is exited and the main event
// loop while is exited, do all you cleanup and shutdown here


//Release the Palette
if (lpddpal)
   {
   lpddpal->Release();
   lpddpal = NULL;
   } // end if

// now the primary surface
if (lpddsPrimary)
   {
   lpddsPrimary->Release();
   lpddsPrimary = NULL;
   } // end if

// now blow away the IDirectDraw7 interface
if (lpdd)
   {
   lpdd->Release();
   lpdd = NULL;
   } // end if


// return success or failure or your own return code here
return(1);

} // end DDrawObj::Shutdown
 

////////////////////////////////////////////////////////////////////


//RENDERER FUNCTIONS////////////////////////////////////////////////


DDrawObj::Load_Bitmap_File(BITMAP_FILE_PTR bitmap, char *filename)
{

	
	// this function opens a bitmap file and loads the data into bitmap

	int file_handle,  // the file handle
		index;        // looping index




	UCHAR   *temp_buffer = NULL; // used to convert 24 bit images to 16 bit
	OFSTRUCT file_data;          // the file data information



	// open the file if it exists
	if ((file_handle = OpenFile(filename,&file_data,OF_READ))==-1)
		return(0);



	// now load the bitmap file header
	_lread(file_handle, &bitmap->bitmapfileheader,sizeof(BITMAPFILEHEADER));

	// test if this is a bitmap file
	if (bitmap->bitmapfileheader.bfType!=BITMAP_ID)
	{
	// close the file
   _lclose(file_handle);

   // return error
   return(0);
   
	} // end if

// now we know this is a bitmap, so read in all the sections



// first the bitmap infoheader

// now load the bitmap file header
_lread(file_handle, &bitmap->bitmapinfoheader,sizeof(BITMAPINFOHEADER));


// now load the color palette if there is one
if (bitmap->bitmapinfoheader.biBitCount == 8)
   {

	
	_lread(file_handle, &bitmap->palette,MAX_COLORS_PALETTE*sizeof(PALETTEENTRY));


   
   // now set all the flags in the palette correctly and fix the reversed 
   // BGR RGBQUAD data format
   for (index=0; index < MAX_COLORS_PALETTE; index++)
       {

	   
	   
	   // reverse the red and green fields
       int temp_color                = bitmap->palette[index].peRed;
       bitmap->palette[index].peRed  = bitmap->palette[index].peBlue;
       bitmap->palette[index].peBlue = temp_color;
       
       // always set the flags word to this
       bitmap->palette[index].peFlags = PC_NOCOLLAPSE;
       } // end for index


    } // end if



// finally the image data itself
_lseek(file_handle,-(int)(bitmap->bitmapinfoheader.biSizeImage),SEEK_END);



// now read in the image, if the image is 8 or 16 bit then simply read it
// but if its 24 bit then read it into a temporary area and then convert
// it to a 16 bit image

if (bitmap->bitmapinfoheader.biBitCount==8 || bitmap->bitmapinfoheader.biBitCount==16 || 
    bitmap->bitmapinfoheader.biBitCount==24)
   {
   // delete the last image if there was one
   if (bitmap->buffer)
       free(bitmap->buffer);

   // allocate the memory for the image
   if (!(bitmap->buffer = (UCHAR *)malloc(bitmap->bitmapinfoheader.biSizeImage)))
      {
      // close the file
      _lclose(file_handle);

      // return error
      return(0);
      } // end if

   // now read it in
   _lread(file_handle,bitmap->buffer,bitmap->bitmapinfoheader.biSizeImage);

   } // end if


else
   {

	// serious problem
   return(0);

   } // end else




#if 0
// write the file info out 
printf("\nfilename:%s \nsize=%d \nwidth=%d \nheight=%d \nbitsperpixel=%d \ncolors=%d \nimpcolors=%d",
        filename,
        bitmap->bitmapinfoheader.biSizeImage,
        bitmap->bitmapinfoheader.biWidth,
        bitmap->bitmapinfoheader.biHeight,
		bitmap->bitmapinfoheader.biBitCount,
        bitmap->bitmapinfoheader.biClrUsed,
        bitmap->bitmapinfoheader.biClrImportant);
#endif

// close the file
_lclose(file_handle);

// flip the bitmap
Flip_Bitmap(bitmap->buffer, 
            bitmap->bitmapinfoheader.biWidth*(bitmap->bitmapinfoheader.biBitCount/8), 
            bitmap->bitmapinfoheader.biHeight);

// return success
return(1);

} // end Load_Bitmap_File

///////////////////////////////////////////////////////////

DDrawObj::Unload_Bitmap_File(BITMAP_FILE_PTR bitmap)
{
// this function releases all memory associated with "bitmap"
if (bitmap->buffer)
   {
   // release memory
   free(bitmap->buffer);

   // reset pointer
   bitmap->buffer = NULL;

   } // end if

// return success
return(1);

} // end Unload_Bitmap_File

///////////////////////////////////////////////////////////



DDrawObj::Flip_Bitmap(UCHAR *image, 
				int bytes_per_line, 
				int height)
{
// this function is used to flip bottom-up .BMP images



UCHAR *buffer; // used to perform the image processing
int index;     // looping index



// allocate the temporary buffer
if (!(buffer = (UCHAR *)malloc(bytes_per_line*height)))
   return(0);




// copy image to work area
memcpy(buffer,image,bytes_per_line*height);



// flip vertically
for (index=0; index < height; index++)
    memcpy(&image[((height-1) - index)*bytes_per_line],
           &buffer[index*bytes_per_line], bytes_per_line);



// release the memory
free(buffer);


// return success
return(1);


} // end Flip_Bitmap



///////////////////////////////////////////////////////////////



DDrawObj::PlotPixel24(int x, int y, 
					  int red, int green, int blue, 
					  UCHAR *VideoBuffer, int lPitch)
{


	DWORD pixel_addr = (x+x+x) + y*lPitch;

	
	VideoBuffer[pixel_addr] = blue;

	VideoBuffer[pixel_addr+1] = green;

	VideoBuffer[pixel_addr+2] = red;

	
	return 1;
}

//Plot 16 bit pixel int 5.6.5//////////////////////////////

DDrawObj::PlotPixel565(int x, int y,
				       int red, int green, int blue,
				       USHORT *VideoBuffer, int lPitch)
{
		
	
		USHORT pixel = RGB16BIT565(red, green, blue);


		VideoBuffer[x+y*(lPitch >> 1)] = pixel;

		return 1;

}


//Plot 16 bit pixel int 5.5.5//////////////////////////////


DDrawObj::PlotPixel555(int x, int y,
				       int red, int green, int blue,
				       USHORT *VideoBuffer, int lPitch)
{
		
	
		USHORT pixel = RGB16BIT555(red, green, blue);


		VideoBuffer[x+y*(lPitch >> 1)] = pixel;

		return 1;

}


//Plot Pixel in 8 Bit Mode//////////////////////////////////


DDrawObj::Plot8(int x, int y, //Pos' of pixel
					  UCHAR color,
					  UCHAR *buffer,
					  int mempitch)
{

	//this function plots a single pixel
	buffer[x+y*mempitch] = color;

	return 1;
}//end Plot8




///////////////////////////////////////////////////////////////


DDrawObj::Render( RECT Player, RECT CPU, RECT Ball )
{


	//clear the struct
	memset(&ddsd, 0, sizeof(ddsd));
	

	//always tell it how big it is
	ddsd.dwSize = sizeof(ddsd);

	//clear the struct
	memset(&ddbltfx, 0, sizeof(ddbltfx));
	

	//always tell it how big it is
	ddbltfx.dwSize = sizeof(ddbltfx);

	//set soem aliases to make the code cleaner
	int mempitch           = (int)ddsd.lPitch;
	UCHAR* VideoBuffer     = (UCHAR *)ddsd.lpSurface;
	USHORT* VideoBuffer16  = (USHORT *)ddsd.lpSurface;	
	

	//clear screan
	ddbltfx.dwFillColor = 0;
	lpddsBack->Blt(NULL,NULL,NULL,DDBLT_WAIT|DDBLT_COLORFILL,&ddbltfx);


//////////////////////////////////////////////
	if(BitMode == 565)
	ddbltfx.dwFillColor =RGB16BIT565( 31, 63, 31);

	
	if(BitMode == 555)
	ddbltfx.dwFillColor =RGB16BIT555( 31, 31, 31);

//////////////////////////////////////////////





	lpddsBack->Blt(&Player, 
		NULL, NULL, 
		DDBLT_COLORFILL | 
		DDBLT_WAIT,
		&ddbltfx);	

	lpddsBack->Blt(&CPU, 
		NULL, NULL, 
		DDBLT_COLORFILL | 
		DDBLT_WAIT,
		&ddbltfx);	

	lpddsBack->Blt(&Ball, 
		NULL, NULL, 
		DDBLT_COLORFILL | 
		DDBLT_WAIT,
		&ddbltfx);	

	lpddsPrimary->Flip(NULL, DDFLIP_WAIT);

	
	lpddsBack->Lock(NULL, &ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT, NULL);




	lpddsBack->Unlock(NULL);


		
	Sleep(500);

return(1);

} // end DDRawObj::Render


/////////////////////////////////////////////////////////////


Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by Reilz
the paddle responds very poorly, it jumps to the top of the screen and barley moves form there.

That's because you mixed up -= with =-


PlayerRect.top =- 1; // sets the variable to -1
PlayerRect.top -= 1; // decreases the variable by 1

Share this post


Link to post
Share on other sites
You wrote =+ & =- instead of += & -=
so instead of an increment & decrement it was an assigment to the positive & negative values shown on the right ;]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!