algorytm.org

Implementacja w C/C++

Baza Wiedzy
wersja offline serwisu przeznaczona na urządzenia z systemem Android
Darowizny
darowiznaWspomóż rozwój serwisu
Nagłówki RSS
Artykuły
Implementacje
Komentarze
Forum
Bookmarki






Sonda
Implementacji w jakim języku programowania poszukujesz?

Arkanoid - Implementacja w C/C++
Ocena użytkownikóww: *****  / 16
SłabyŚwietny
Nadesłany przez Marek Rudolf, 08 grudnia 2005 01:00
Kod przedstawiony poniżej przedstawia główną część rozwiązania problemu.
Pobierz pełne rozwiązanie.

Jeżeli nie odpowiada Ci sposób formatowania kodu przez autora skorzystaj z pretty printer'a i dostosuj go automatycznie do siebie.

ARKANOID/main.cpp:
/*
 *  Arkanoid Created By Marek Rudolf
 *	Base Code Was Created By Jeff Molofee nehe.gamedev.net
 */

#include <windows.h>		// Header File For Windows
#include <stdio.h>											// Header File For Standard Input / Output
#include <gl\gl.h>			// Header File For The OpenGL32 Library
#include <gl\glu.h>			// Header File For The GLu32 Library
#include <gl\glaux.h>		// Header File For The Glaux Library
#include <math.h>
#include "images.h"

HDC			hDC=NULL;		// Private GDI Device Context
HGLRC		hRC=NULL;		// Permanent Rendering Context
HWND		hWnd=NULL;		// Holds Our Window Handle
HINSTANCE	hInstance;		// Holds The Instance Of The Application


GLuint	base;												// Base Display List For The Font
bool	keys[256];			// Array Used For The Keyboard Routine
bool	active=TRUE;		// Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;	// Fullscreen Flag Set To Fullscreen Mode By Default
int     balls=0; //ilosc pilek
int     score=0; //wynik
int     level=1; //etap
int     maxlevel=2;//ilosc etapow
bool    gamestate=false; //stan gry
rect    Box; //plansza
blocks  Blocks;//bloczki
bat     Bat;//paletka
ball    Ball;//pilka
//bool    zapisane=false;
typedef struct			// Create a structure
{
	GLubyte	*imageData;	// Image data (Up to 32 bits)
	GLuint	bpp;		// Image color depth in bits per pixel.
	GLuint	width;		// Image width
	GLuint	height;		// Image height
	GLuint	texID;		// Texture ID used to select a texture
} TextureImage;			// Structure name

TextureImage	texture[2];											// Font Texture Storage Space
GLYPHMETRICSFLOAT gmf[256];	// Storage For Information About Our Outline Font Characters

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

bool LoadTGA(TextureImage *texture, char *filename)			// Loads a TGA file into memory
{
	GLubyte		TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0};	// Uncompressed TGA header
	GLubyte		TGAcompare[12];		// Used to compare TGA header
	GLubyte		header[6];		// First 6 useful bytes from the header
	GLuint		bytesPerPixel;		// Holds number of bytes per pixel used in the TGA file
	GLuint		imageSize;		// Used to store the image size when setting aside ram
	GLuint		temp;			// Temporary variable
	GLuint		type=GL_RGBA;		// Set the default GL mode to RBGA (32 BPP)

	FILE *file = fopen(filename, "rb");	// Open the TGA file

	if(	file==NULL ||								// Does file even exist?
		fread(TGAcompare,1,sizeof(TGAcompare),file)!=sizeof(TGAcompare) ||	// Are there 12 bytes to read?
		memcmp(TGAheader,TGAcompare,sizeof(TGAheader))!=0 ||                    // Does the header match what we want?
		fread(header,1,sizeof(header),file)!=sizeof(header))			// If so read next 6 header bytes
	{
		if (file == NULL)			// Did the file even exist? *Added Jim Strong*
			return FALSE;			// Return false
		else					// Otherwise
		{
			fclose(file);	// If anything failed, close the file
			return FALSE;	// Return false
		}
	}

	texture->width  = header[1] * 256 + header[0];	// Determine the TGA width	(highbyte*256+lowbyte)
	texture->height = header[3] * 256 + header[2];	// Determine the TGA height	(highbyte*256+lowbyte)

 	if(	texture->width	<=0	||		// Is the width less than or equal to zero
		texture->height	<=0	||		// Is the height less than or equal to zero
		(header[4]!=24 && header[4]!=32))	// Is the TGA 24 or 32 bit?
	{
		fclose(file);				// If anything failed, close the file
		return FALSE;				// Return false
	}

	texture->bpp	= header[4];			// Grab the TGA's bits per pixel (24 or 32)
	bytesPerPixel	= texture->bpp/8;		// Divide by 8 to get the bytes per pixel
	imageSize		= texture->width*texture->height*bytesPerPixel;	// Calculate the memory required for the TGA data

	texture->imageData=(GLubyte *)malloc(imageSize);			// Reserve memory to hold the TGA data

	if(	texture->imageData==NULL ||					// Does the storage memory exist?
		fread(texture->imageData, 1, imageSize, file)!=imageSize)	// Does the image size match the memory reserved?
	{
		if(texture->imageData!=NULL)				// Was image data loaded
			free(texture->imageData);			// If so, release the image data

		fclose(file);						// Close the file
		return FALSE;						// Return false
	}

	for(GLuint i=0; i<int(imageSize); i+=bytesPerPixel)		// Loop through the image data
	{								// Swaps the 1st and 3rd bytes ('R'ed and 'B'lue)
		temp=texture->imageData[i];				// Temporarily store the value at image data 'i'
		texture->imageData[i] = texture->imageData[i + 2];	// Set the 1st byte to the value of the 3rd byte
		texture->imageData[i + 2] = temp;			// Set the 3rd byte to the value in 'temp' (1st byte value)
	}

	fclose (file);					// Close the file

	// Build a texture from the data
	glGenTextures(1, &texture[0].texID);		// Generate OpenGL texture IDs

	glBindTexture(GL_TEXTURE_2D, texture[0].texID);				// Bind our texture
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);	// Linear filtered
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);	// Linear filtered

	if (texture[0].bpp==24)		// Was the TGA 24 bits
	{
		type=GL_RGB;		// If so set the 'type' to GL_RGB
	}

	glTexImage2D(GL_TEXTURE_2D, 0, type, texture[0].width, texture[0].height, 0, type, GL_UNSIGNED_BYTE, texture[0].imageData);

	return true;		// Texture building went ok, return true
}


GLvoid BuildFont(GLvoid)									// Build Our Font Display List
{
	base=glGenLists(256);									// Creating 256 Display Lists
	glBindTexture(GL_TEXTURE_2D, texture[0].texID);				// Select Our Font Texture   
	for (int i=0; i<95; i++)						// Loop Through All 256 Lists
	{
		float cx=float(i%16)/16.0f;						// X Position Of Current Character
		float cy=float(i/16)/7.88f;						// Y Position Of Current Character

		glNewList(base+i,GL_COMPILE);					// Start Building A List
			glBegin(GL_QUADS);								// Use A Quad For Each Character
				glTexCoord2f(cx,         1.0f-cy-0.120f); glVertex2i(0,14);	// Texture / Vertex Coord (Bottom Left)
				glTexCoord2f(cx+0.0625f, 1.0f-cy-0.120f); glVertex2i(14,14);	// Texutre / Vertex Coord (Bottom Right)
				glTexCoord2f(cx+0.0625f, 1.0f-cy);		  glVertex2i(14,0);// Texture / Vertex Coord (Top Right)
				glTexCoord2f(cx,         1.0f-cy);		  glVertex2i(0,0);	// Texture / Vertex Coord (Top Left)
   			glEnd();										// Done Building Our Quad (Character)
			glTranslated(15,0,0);							// Move To The Right Of The Character
		glEndList();										// Done Building The Display List
	}														// Loop Until All 256 Are Built	
}

GLvoid KillFont(GLvoid)										// Delete The Font From Memory
{
	glDeleteLists(base,256);								// Delete All 256 Display Lists
}

GLvoid glPrint(GLint x, GLint y, int set, const char *fmt, ...)	// Where The Printing Happens
{
	char		text[256];									// Holds Our String
	va_list		ap;											// Pointer To List Of Arguments

	if (fmt == NULL)										// If There's No Text
		return;												// Do Nothing

	va_start(ap, fmt);										// Parses The String For Variables
	    vsprintf(text, fmt, ap);							// And Converts Symbols To Actual Numbers
	va_end(ap);												// Results Are Stored In Text

	if (set>1)												// Did User Choose An Invalid Character Set?
	{
		set=1;												// If So, Select Set 1 (Italic)
	}
    glEnable(GL_BLEND);	
	glEnable(GL_TEXTURE_2D);								// Enable Texture Mapping
	glLoadIdentity();										// Reset The Modelview Matrix
	glTranslated(x,y,0);									// Position The Text (0,0 - Bottom Left)
	glListBase(base-32+(128*set));							// Choose The Font Set (0 or 1)
	if (set==0)												// If Set 0 Is Being Used Enlarge Font
	{
		glScalef(1.0f,1.2f,1.0f);							// Enlarge Font Width And Height
	}
	glCallLists(strlen(text),GL_UNSIGNED_BYTE, text);		// Write The Text To The Screen
	glDisable(GL_TEXTURE_2D);								// Disable Texture Mapping
    glDisable(GL_BLEND);	    
}

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)		// Resize And Initialize The GL Window
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	glViewport(0,0,width,height);						// Reset The Current Viewport

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	// Calculate The Aspect Ratio Of The Window
    glOrtho(0.0f,width,height,0.0f,-1.0f,1.0f);				// Create Ortho 640x480 View (0,0 At Top Left)
    Bat.x=width/2-Bat.width/2;
	Bat.y=height-Bat.height;	
	Bat.maxx=width;
	Box.left=0;
	Box.right=width;
	Box.top=0;
	Box.bottom=height;
	Ball.x=width/2-Bat.width/2;
	Ball.y=height-Bat.height-Ball.size;
    Blocks.width=(width/Blocks.sizex())-0.1f;	
	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();									// Reset The Modelview Matrix   	   	
}

int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{
  	if (!LoadTGA(&texture[0],"Data/font.tga"))									// Jump To Texture Loading Routine
	{
		return FALSE;										// If Texture Didn't Load Return FALSE
	}

	BuildFont();											// Build The Font    
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup
	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);     		
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations	
	glEnable(GL_LIGHT0);								// Enable Default Light (Quick And Dirty)
	glEnable(GL_LIGHTING);								// Enable Lighting
	glEnable(GL_COLOR_MATERIAL);						// Enable Coloring Of Material
	
	return TRUE;										// Initialization Went OK
}

int DrawGLScene(GLvoid)									// Here's Where We Do All The Drawing
{
    //glowna petla gry    
    bool ychange=false;
    bool xchange=false;
    float increase=0;
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	// Clear Screen And Depth Buffer
    glLoadIdentity();		
    
    if (balls<1){
     gamestate=false;            
     glPrint(int(Box.right/2-100),int(Box.bottom/2),0,"F5 - Nowa gra");                       
    }
    else
    if (Blocks.won()){
      if (gamestate==true)
      {                    
        gamestate=false;
      }      
      else
      {        
        if (level>maxlevel)               
        glPrint(int(Box.right/2-50),int(Box.bottom/2),0,"Wygrales");               
        else
        {
         level++;  
         Blocks.read(level,Box.right);        
        }
      }
    }
    else
    {
      if (gamestate==false)
      {
        char txt[7];
        sprintf(txt,"Etap %d",level);	         
        glPrint(int(Box.right/2-30),int(Box.bottom/2),0,txt);                             
      }
    }
 
    if(gamestate==false)
    {
       Ball.y=Bat.y-Ball.size;                        
       Ball.x=Bat.x+Bat.width/2;
       Ball.xspeed=0;                                                                     
       Ball.yspeed=0;            
    }
    


    Blocks.draw();        
    Ball.draw();
    Bat.draw();
    glColor3f(0.4f,1.0f,0.2f);  
     char txt[30];
    sprintf(txt,"Wynik: %d Pilki: %d",score,balls);	 
    glPrint(10,int(Box.bottom-18),0,txt);            
    
    if (Ball.colisiontest(0.0f,-10.0f,Box.right,0.0f)==2)
    ychange=true;
    
    if (Ball.colisiontest(0.0f,Box.bottom,Box.right,Box.bottom+10.0f)==2)    
    {
       balls--;        
       gamestate=false;
    }
    
    if (Ball.colisiontest(-10.0f,0.0f,0.0f,Box.bottom)==1)
    xchange=true;
    
    if (Ball.colisiontest(Box.right,0.0f,Box.right+10.0f,Box.bottom)==1)
    xchange=true;    
    int paddle=Ball.colisiontest(Bat.x,Bat.y,Bat.x+Bat.width,Bat.y+Bat.height);

    switch(paddle)
    {
       case 1: xchange=true; break;
       case 2: ychange=true; break;   
       case 3: xchange=true; ychange=true; break;
    };         
        
      
    increase=0;
    for(int i=0;i<Blocks.sizey();i++)
     for(int j=0;j<Blocks.sizex();j++)
      if (Blocks.blockexistst(i,j))
      {
       rect tmp;
       col tmp1;
       tmp=Blocks.getblockrect(i,j);
       int blok=Ball.colisiontest(tmp.left,tmp.top,tmp.right,tmp.bottom);
       if (blok>0){
         Blocks.blockhit(i,j);         
         increase+=0.2;
         score+=abs(int(10*(Ball.yspeed)));
       }
       switch(blok)
       {
         case 1: xchange=true; break;
         case 2: ychange=true; break;   
         case 3: xchange=true; ychange=true; break;
       };         
    
      }
    if (Ball.yspeed>5)
     Ball.yspeed=5;
    if (Ball.xspeed>5)
     Ball.xspeed=5;    
    if (ychange)    
     Ball.yspeed*=-1-increase;
    if (xchange)
     Ball.xspeed*=-1-increase;

    Ball.move();            
	return TRUE;										// Keep Going
}

GLvoid KillGLWindow(GLvoid)								// Properly Kill The Window
{
	if (fullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(NULL,0);					// If So Switch Back To The Desktop
		ShowCursor(TRUE);								// Show Mouse Pointer
	}

	if (hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(NULL,NULL))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		hRC=NULL;										// Set RC To NULL
	}

	if (hDC && !ReleaseDC(hWnd,hDC))					// Are We Able To Release The DC
	{
		MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hDC=NULL;										// Set DC To NULL
	}

	if (hWnd && !DestroyWindow(hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hWnd=NULL;										// Set hWnd To NULL
	}

	if (!UnregisterClass("OpenGL",hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;									// Set hInstance To NULL
	}
	KillFont();												// Kill The Font We Built	
}

/*	This Code Creates Our OpenGL Window.  Parameters Are:					*
 *	title			- Title To Appear At The Top Of The Window				*
 *	width			- Width Of The GL Window Or Fullscreen Mode				*
 *	height			- Height Of The GL Window Or Fullscreen Mode			*
 *	bits			- Number Of Bits To Use For Color (8/16/24/32)			*
 *	fullscreenflag	- Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE)	*/
 
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	fullscreen=fullscreenflag;			// Set The Global Fullscreen Flag

	hInstance			= GetModuleHandle(NULL);				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) WndProc;					// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(NULL, IDI_WINLOGO);			// Load The Default Icon
	wc.hCursor			= LoadCursor(NULL, IDC_ARROW);			// Load The Arrow Pointer
	wc.hbrBackground	= NULL;									// No Background Required For GL
	wc.lpszMenuName		= NULL;									// We Don't Want A Menu
	wc.lpszClassName	= "OpenGL";								// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;											// Return FALSE
	}
	
	if (fullscreen)												// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= bits;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","Arkanoid",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				fullscreen=FALSE;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (fullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style
		ShowCursor(FALSE);										// Hide Mouse Pointer
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(hWnd=CreateWindowEx(	dwExStyle,							// Extended Style For The Window
								"OpenGL",							// Class Name
								title,								// Window Title
								dwStyle |							// Defined Window Style
								WS_CLIPSIBLINGS |					// Required Window Style
								WS_CLIPCHILDREN,					// Required Window Style
								0, 0,								// Window Position
								WindowRect.right-WindowRect.left,	// Calculate Window Width
								WindowRect.bottom-WindowRect.top,	// Calculate Window Height
								NULL,								// No Parent Window
								NULL,								// No Menu
								hInstance,							// Instance
								NULL)))								// Dont Pass Anything To WM_CREATE
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		bits,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};
	
	if (!(hDC=GetDC(hWnd)))							// Did We Get A Device Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!SetPixelFormat(hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if (!(hRC=wglCreateContext(hDC)))				// Are We Able To Get A Rendering Context?
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	if(!wglMakeCurrent(hDC,hRC))					// Try To Activate The Rendering Context
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	ShowWindow(hWnd,SW_SHOW);						// Show The Window
	SetForegroundWindow(hWnd);						// Slightly Higher Priority
	SetFocus(hWnd);									// Sets Keyboard Focus To The Window
	ReSizeGLScene(width, height);					// Set Up Our Perspective GL Screen

	if (!InitGL())									// Initialize Our Newly Created GL Window
	{
		KillGLWindow();								// Reset The Display
		MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return FALSE;								// Return FALSE
	}

	return TRUE;									// Success
}

LRESULT CALLBACK WndProc(	HWND	hWnd,			// Handle For This Window
							UINT	uMsg,			// Message For This Window
							WPARAM	wParam,			// Additional Message Information
							LPARAM	lParam)			// Additional Message Information
{
	switch (uMsg)									// Check For Windows Messages
	{
		case WM_ACTIVATE:							// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))					// Check Minimization State
			{
				active=TRUE;						// Program Is Active
//           		ShowCursor(FALSE);								// Hide Mouse Pointer				
			}
			else
			{
				active=FALSE;						// Program Is No Longer Active
//           		ShowCursor(TRUE);								// Show Mouse Pointer								
			}

			return 0;								// Return To The Message Loop
		}

		case WM_SYSCOMMAND:
		{
			switch (wParam)
			{
				case SC_SCREENSAVE:
				case SC_MONITORPOWER:
					return 0;
			}
			break;
		}
		case WM_CLOSE:								// Did We Receive A Close Message?
		{
			PostQuitMessage(0);						// Send A Quit Message
			return 0;								// Jump Back
		}

		case WM_KEYDOWN:							// Is A Key Being Held Down?
		{
			keys[wParam] = TRUE;					// If So, Mark It As TRUE
			return 0;								// Jump Back
		}

		case WM_KEYUP:								// Has A Key Been Released?
		{
			keys[wParam] = FALSE;					// If So, Mark It As FALSE
			return 0;								// Jump Back
		}
        case WM_MOUSEMOVE:
        {                 
            
            Bat.movemouse((int)LOWORD(lParam));
            return 0;
        }        
        case WM_LBUTTONDOWN:
             if (gamestate==false)
             {
               gamestate=true;
               Ball.yspeed=-1.0f;
               Ball.xspeed=1.0f;
             }
            return 0;
		case WM_SIZE:								// Resize The OpenGL Window
		{
			ReSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
			return 0;								// Jump Back
		}
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done=FALSE;								// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Uruchomic na pelnym ekranie?", "Pelny ekran?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("Arkanoid",640,480,16,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done=TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(hDC);					// Swap Buffers (Double Buffering)
			}
            if (keys[VK_LEFT])
            {                              
               Bat.move(-5);
            }
            if (keys[VK_RIGHT])
            {                              
               Bat.move(5);             
            }       
            /*if (keys[VK_F2])            
            {
               if (zapisane==false){
                 Blocks.save();
                 zapisane=true;
               }
            }
            if (keys[VK_F3])
            {
               //generowanie etapu                
               Blocks.generate(5,28,Box.right);
            }*/
            if (keys[VK_F5])
            {
               gamestate=false; 
               balls=3;
               score=0;
               level=1;
               Blocks.read(level,Box.right);               
            }     
            if (keys[VK_SPACE])
            if (gamestate==false)
            {
               gamestate=true;
               Ball.yspeed=-1.0f;
               Ball.xspeed=1.0f;
            }            
			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("Arkanoid",640,480,16,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}


ARKANOID/images.cpp:
//Arkanoid Created By Marek Rudolf
#include "images.h"
#include <math.h>
#include <iostream.h>
#include <fstream.h>

ball::ball()
{
  size=8;
  x=0;
  y=0;            
}

void ball::draw()
{
   glLoadIdentity();
   glColor3f(0.4f,1.0f,0.2f);                                    
   glBegin(GL_TRIANGLE_FAN); 
   for (GLfloat a = 0; a<=2*M_PI; a+=2*M_PI/50)
   { 
      glVertex2f(x+cos(a)*size,y+sin(a)*size);
   } 
   glEnd();      
}

void ball::move()
{
   y+=yspeed;
   x+=xspeed;
}

int ball::colisiontest(GLfloat x1,GLfloat y1,GLfloat x2,GLfloat y2)
{

    int coll=0;   
    if ((x + xspeed + size >= x1
		 && x + xspeed - size <= x2)
		 && (y + yspeed + size >= y1
		 && y + yspeed - size <= y2))
		 {              
  		   if (x + size < x1 &&
					    x + xspeed + size >= x1)              
			  coll|=1;
           if (x - size > x2 &&
		 	   x + xspeed - size <= x2)                	    	                
              coll|=1;
          if (y + size < y1&&
					    y + yspeed + size >= y1)              
              coll|=2;					    
   		  if (y - size > y2 &&
				   y + yspeed - size <= y2)              
              coll|=2;								                 
         }
    return coll;
}

blocks::blocks()
{
    x=4;
    y=10;
    matrix=new int*[x];
    for(int i=0;i<x;i++)                   
    matrix[i]=new int[y];
    
    for(int i=0;i<x;i++)               
    for(int j=0;j<y;j++)
    matrix[i][j]=0;    
}

blocks::~blocks()
{
for (int i=0; i<x; i++) delete matrix[i];
delete[] matrix;
}

void blocks::blockhit(int i,int j)
{ 
   matrix[i][j]=0;                  
}

bool blocks::blockexistst(int i,int j)
{
  if (matrix[i][j]>0)
  return true;
  else 
  return false;
}

bool blocks::won()
{
int count=0;
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
if (blockexistst(i,j))
count++;
if (count>0)
return false;
else
return true;
}

rect blocks::getblockrect(int i,int j)
{
 rect blok;
 blok.left = j*width;
 blok.top = i*20;
 blok.right = (j*width)+width;
 blok.bottom = (i*20)+20;                
 return blok;
}

void blocks::draw()
{       
    GLfloat x1,x2,y1,y2;
    glLoadIdentity();
    for(int i=0;i<x;i++)                   
    for(int j=0;j<y;j++)
    {
       if (matrix[i][j]!=0)
       {                      
          x1=j*width+1; 
          x2=j*width+width;
          y1=(GLfloat)i*20.0f+1;
          y2=(GLfloat)i*20.0f+20.0f;  

          switch(matrix[i][j]){
          case 1:glColor3f(1.0f,0.0f,0.0f);break;                               
          case 2:glColor3f(0.0f,1.0f,0.0f);break;                               
          case 3:glColor3f(0.0f,0.0f,1.0f);break;                                                   
          }      
          glBegin(GL_QUADS);                                       
           glVertex3f(x1, y1, 0.0f);           // Top Left
           glVertex3f(x2, y1, 0.0f);       // Top Right
           glVertex3f(x2, y2, 0.0f);// Bottom Right
           glVertex3f(x1, y2, 0.0f);    // Bottom Left
          glEnd();           
       }          
    }
}

void blocks::read(int level,GLfloat boxwidth)
{
 int tmp;  
 ifstream infile;
 if (level<1)
 level=1;
 infile.open("levels.dat",ios::binary);
 if(infile.is_open())
 {
    for (int i=0; i<x; i++) delete matrix[i];
    delete[] matrix;                     
    for(int z=0;z<level;z++){    
     infile.read((char*)&tmp,sizeof(int));
     x=tmp;
     infile.read((char*)&tmp,sizeof(int));    
     y=tmp;
     if (z!=level-1)
     infile.seekg(x*y*sizeof(int),ios::cur);
    }
    matrix=new int*[x];
    for(int i=0;i<x;i++)                   
    matrix[i]=new int[y];        
    for(int i=0;i<x;i++)
    for(int j=0;j<y;j++)
    infile.read((char*)&(matrix[i][j]),sizeof(int));;    
    width=(boxwidth/y)-0.1f;	                         
 }     
}

void blocks::save()
{
  ofstream outfile;     
  outfile.open("levels.dat",ios::binary|ios::app);
  if(outfile.is_open()){
    outfile.write((char*)&x,sizeof(int));;
    outfile.write((char*)&y,sizeof(int));;    
    for(int i=0;i<x;i++)
    for(int j=0;j<y;j++)
    outfile.write((char*)&(matrix[i][j]),sizeof(int));;    
    outfile.close();
  }
}

/*
int blocks::generate(int mx, int my,GLfloat boxwidt)
{
    for (int i=0; i<x; i++) delete matrix[i];
    delete[] matrix;             
    matrix=new int*[mx];
    for(int i=0;i<mx;i++)                   
    matrix[i]=new int[my];          
    x=mx;
    y=my;
    for(int i=0;i<mx;i++)
    for(int j=0;j<my;j++)                 
    matrix[i][j]=3;
    //A  
    matrix[0][2]=2;
    matrix[1][2]=2;
    matrix[2][2]=2;    
    matrix[4][2]=2;        
    matrix[2][3]=2;
    matrix[0][3]=2;    
    matrix[0][4]=2;    
    matrix[1][4]=2;        
    matrix[2][4]=2;            
    matrix[3][4]=2;    
    matrix[4][4]=2;        
    matrix[3][2]=2;        
    //L
    matrix[0][5]=3;            
    matrix[1][5]=3;                
    matrix[2][5]=3;                
    matrix[3][5]=3;                    
    matrix[4][5]=3;                
    matrix[4][6]=3;            
    matrix[4][7]=3;                
    //G
    matrix[0][8]=2;            
    matrix[1][8]=2;            
    matrix[2][8]=2;                    
    matrix[3][8]=2;                
    matrix[4][8]=2;                    
    matrix[0][9]=2;                        
    matrix[0][10]=2;
    matrix[4][9]=2;                            
    matrix[4][10]=2;                                
    matrix[3][10]=2;    
    //O
    matrix[0][11]=3;            
    matrix[1][11]=3;            
    matrix[2][11]=3;            
    matrix[3][11]=3;        
    matrix[4][11]=3;            
    matrix[4][12]=3;            
    matrix[4][13]=3;                
    matrix[0][13]=3;                
    matrix[0][12]=3;                    
    matrix[1][13]=3;                    
    matrix[2][13]=3;                    
    matrix[3][13]=3;                    
    //R
    matrix[0][14]=2;              
    matrix[1][14]=2;              
    matrix[2][14]=2;              
    matrix[3][14]=2;                            
    matrix[4][14]=2;                  
    matrix[0][15]=2;                  
    matrix[0][16]=2;                      
    matrix[1][16]=2;                          
    matrix[3][16]=2;                          
    matrix[2][15]=2;                      
    matrix[4][16]=2;                          
    //Y
    matrix[0][17]=3;                          
    matrix[1][17]=3;    
    matrix[0][19]=3;    
    matrix[1][19]=3;
    matrix[2][18]=3;
    matrix[3][18]=3;    
    matrix[4][18]=3;    
    //T
    matrix[0][20]=2;
    matrix[0][21]=2;
    matrix[0][22]=2;        
    matrix[1][21]=2;    
    matrix[2][21]=2;    
    matrix[3][21]=2;    
    matrix[4][21]=2;                
    //M
    matrix[0][23]=3;    
    matrix[1][24]=3;
    matrix[0][25]=3;
    matrix[1][23]=3;    
    matrix[2][23]=3;    
    matrix[3][23]=3;        
    matrix[4][23]=3;            
    matrix[1][25]=3;        
    matrix[2][25]=3;        
    matrix[3][25]=3;                
    matrix[4][25]=3;            
    width=(boxwidt/my)-0.1f;    
}    */


void bat::draw()
{         
  glLoadIdentity();          
  glColor3f(1.0f,0.2f,0.3f);                                              
  glBegin(GL_QUADS);                                       
      glVertex3f(x, y, 0.0f);           // Top Left
      glVertex3f(x+width, y, 0.0f);       // Top Right
      glVertex3f(x+width, y+height, 0.0f);// Bottom Right
      glVertex3f(x, y+height, 0.0f);    // Bottom Left
  glEnd();        
}

bat::bat()
{
 x=0;
 y=0; 
 width=40;          
 height=15;
 maxx=0;
}

void bat::move(int i)
{ 
 x+=i;
 if (x<0)
 x=0;
 if (x+width>maxx)
 x=maxx-width;
}

void bat::movemouse(int i)
{     
 x=i-width/2;
 if (x<0)
 x=0;
 if (x+width>maxx)
 x=maxx-width;
}

Dodaj komentarz