connect4.h
///////////////////////////////////////////////////////////////////////////////////////////////////////// File: Connect4.h// Desc: declaration of the game class// Author: Chris Miller// Date: 6/12/08///////////////////////////////////////////////////////////////////////////////////////////////////////#ifndef __CONNECT4_H#define __CONNECT4_H#include "Global.h"class Connect4 : public D3DApp{public: Connect4(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP); ~Connect4(); bool checkDeviceCaps(); void onLostDevice(); void onResetDevice(); void updateScene(float dt); void drawScene(); // helper draw functions void drawPieces(); void drawBackground(); // game functions void humanMove(); void computerMove(); int opponent(int turn); void announceWinner(); void winner(); // general helper function int getTurn();private: ID3DXSprite* mSprite; // application sprite IDirect3DTexture9* mTexture; // game texture D3DXVECTOR3 mBkgrdCntr; // center of the background texture RECT mBkgrdRect; // source rectangle for drawing background D3DXVECTOR3 mBlackCntr; // center of the black piece RECT mBlackRect; // source rectangle for drawing black piece D3DXVECTOR3 mRedCntr; // center of the red piece RECT mRedRect; // source rectangle for drawing red piece int mBoard[6][7]; // game board static const int NUM_ROWS = 6; // number of rows static const int NUL_COLS = 7; // number of columns int mPlayer; // number that represents the player int mComputer; // number to represent the computer int mTurn; // current persons turn};#endif
d3dapp.h
//=============================================================================// d3dApp.h by Frank Luna (C) 2005 All Rights Reserved.//// Contains the base Direct3D application class which provides the// framework interface for the sample applications. Clients are to derive // from D3DApp, override the framework methods, and instantiate only a single// instance of the derived D3DApp class. At the same time, the client should// set the global application pointer (gd3dApp) to point to the one and only// instance, e.g., gd3dApp = new HelloD3DApp(hInstance);// //=============================================================================#ifndef D3DAPP_H#define D3DAPP_H#include "d3dUtil.h"#include <string>class D3DApp{public: D3DApp(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP); virtual ~D3DApp(); HINSTANCE getAppInst(); HWND getMainWnd(); // Framework methods. Derived client class overrides these methods to // implement specific application requirements. virtual bool checkDeviceCaps() { return true; } virtual void onLostDevice() {} virtual void onResetDevice() {} virtual void updateScene(float dt) {} virtual void drawScene() {} // Override these methods only if you do not like the default window creation, // direct3D device creation, window procedure, or message loop. In general, // for the sample programs of this book, we will not need to modify these. virtual void initMainWindow(); virtual void initDirect3D(); virtual int run(); virtual LRESULT msgProc(UINT msg, WPARAM wParam, LPARAM lParam); void enableFullScreenMode(bool enable); bool isDeviceLost();protected: // Derived client class can modify these data members in the constructor to // customize the application. std::string mMainWndCaption; D3DDEVTYPE mDevType; DWORD mRequestedVP; // Application, Windows, and Direct3D data members. HINSTANCE mhAppInst; HWND mhMainWnd; IDirect3D9* md3dObject; bool mAppPaused; D3DPRESENT_PARAMETERS md3dPP;};// Globals for convenient access.extern D3DApp* gd3dApp;extern IDirect3DDevice9* gd3dDevice;#endif // D3DAPP_H
d3dutil.h
//=============================================================================// d3dUtil.h by Frank Luna (C) 2005 All Rights Reserved.//// Contains various utility code for DirectX applications, such as, clean up// and debugging code.//=============================================================================#ifndef D3DUTIL_H#define D3DUTIL_H// Enable extra D3D debugging in debug builds if using the debug DirectX runtime. // This makes D3D objects work well in the debugger watch window, but slows down // performance slightly.#if defined(DEBUG) | defined(_DEBUG)#ifndef D3D_DEBUG_INFO#define D3D_DEBUG_INFO#endif#endif#include <d3d9.h>#include <d3dx9.h>#include <dxerr9.h>#include <string>#include <sstream>//===============================================================// Globals for convenient access.class D3DApp;extern D3DApp* gd3dApp;extern IDirect3DDevice9* gd3dDevice;//===============================================================// Clean up#define ReleaseCOM(x) { if(x){ x->Release();x = 0; } }//===============================================================// Debug#if defined(DEBUG) | defined(_DEBUG) #ifndef HR #define HR(x) { HRESULT hr = x; if(FAILED(hr)) { DXTrace(__FILE__, __LINE__, hr, #x, TRUE); } } #endif#else #ifndef HR #define HR(x) x; #endif#endif #endif // D3DUTIL_H
directinput.h
//=============================================================================// DirectInput.h by Frank Luna (C) 2005 All Rights Reserved.//// Wraps initialization of immediate mode Direct Input, and provides // information for querying the state of the keyboard and mouse.//=============================================================================#ifndef DIRECT_INPUT_H#define DIRECT_INPUT_H#define DIRECTINPUT_VERSION 0x0800#include <dinput.h>class DirectInput{public: DirectInput(DWORD keyboardCoopFlags, DWORD mouseCoopFlags); ~DirectInput(); void poll(); bool keyDown(char key); bool keyUp(char key); bool mouseButtonDown(int button); float mouseDX(); float mouseDY(); float mouseDZ();private: // Make private to prevent copying of members of this class. DirectInput(const DirectInput& rhs); DirectInput& operator=(const DirectInput& rhs); private: IDirectInput8* mDInput; IDirectInputDevice8* mKeyboard; char mKeyboardState[256]; IDirectInputDevice8* mMouse; DIMOUSESTATE2 mMouseState;};extern DirectInput* gDInput;#endif // DIRECT_INPUT_H
global.h
///////////////////////////////////////////////////////////////////////////////////////////////////////// File: Global.h// Desc: includes all headers for convience// Author: Chris Miller// Date: 6/13/08///////////////////////////////////////////////////////////////////////////////////////////////////////#ifndef __GLOBAL_H#define __GLOBAL_H#include "d3dApp.h"#include "Tools.h"#include "d3dUtil.h"#include "DirectInput.h"#include "Connect4.h"#include <crtdbg.h>#include <tchar.h>#include <iostream>#include <fstream>#include <string>#include <windows.h>#endif
tools.h
////////////////////////////////////////////////////////////////////////////////////////// File: Tools.h// Desc: declaration of common used functions// Author: Chris Miller// Date: 6/12/08////////////////////////////////////////////////////////////////////////////////////////#ifndef __TOOLS_H#define __TOOLS_H#include <iostream>#include <fstream>#include <string>void logError(std::string);void logKey(std::string);void logTurn(std::string);void logTurn(std::string, int);void logBoard(int mBoard[6][7]);#endif
connect4.cpp
////////////////////////////////////////////////////////////////////////////////////////// File: Connect4.cpp// Desc: main application file for the connect 4 game// Author: Chris Miller// Date: 6/12/08////////////////////////////////////////////////////////////////////////////////////////#include "Global.h"#define DEBUGint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd){ // enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif Connect4 app(hInstance, "Connect 4 - v.0.5", D3DDEVTYPE_HAL, D3DCREATE_HARDWARE_VERTEXPROCESSING); gd3dApp = &app; DirectInput di(DISCL_NONEXCLUSIVE|DISCL_FOREGROUND, DISCL_NONEXCLUSIVE|DISCL_FOREGROUND); gDInput = &di; return gd3dApp->run();}Connect4::Connect4(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP):D3DApp(hInstance, winCaption, devType, requestedVP){ if (!checkDeviceCaps()) { logError("checkDeviceCaps - FAILED"); return; } HR(D3DXCreateSprite(gd3dDevice, &mSprite)); HR(D3DXCreateTextureFromFile(gd3dDevice, "background.tga", &mTexture)); mBkgrdCntr = D3DXVECTOR3(353.0f, 303.0f, 1.0f); mBlackCntr = D3DXVECTOR3(50.0f, 50.0f, 0.0f); mRedCntr = D3DXVECTOR3(50.0, 50.0f, 0.0f); SetRect(&mBkgrdRect, 0, 0, 707, 606); SetRect(&mBlackRect, 924, 100, 1024, 199); SetRect(&mRedRect, 924, 0, 1024, 99); mPlayer = 1; mComputer = 2; mTurn = mPlayer; // initiaze the board for(int i = 0; i < NUM_ROWS; i++) { for (int j = 0; j < NUL_COLS; j++) { mBoard[j] = 0; } } onResetDevice();}Connect4::~Connect4(){ // release resources ReleaseCOM(mTexture); ReleaseCOM(mSprite);}bool Connect4::checkDeviceCaps(){ // Nothing to check return true;}void Connect4::onLostDevice(){ // reset any device that needs to be reset HR(mSprite->OnLostDevice());}void Connect4::onResetDevice(){ // Call the onResetDevice of other objects. HR(mSprite->OnResetDevice()); // Sets up the camera 1000 units back looking at the origin. D3DXMATRIX V; D3DXVECTOR3 pos(0.0f, 0.0f, -1000.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXVECTOR3 target(0.0f, 0.0f, 0.0f); D3DXMatrixLookAtLH(&V, &pos, &target, &up); HR(gd3dDevice->SetTransform(D3DTS_VIEW, &V)); // The following code defines the volume of space the camera sees. D3DXMATRIX P; RECT R; GetClientRect(mhMainWnd, &R); float width = (float)R.right; float height = (float)R.bottom; D3DXMatrixPerspectiveFovLH(&P, D3DX_PI*0.25f, width/height, 1.0f, 5000.0f); HR(gd3dDevice->SetTransform(D3DTS_PROJECTION, &P)); // This code sets texture filters, which helps to smooth out distortions // when you scale a texture. HR(gd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR)); HR(gd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR)); HR(gd3dDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR)); // This line of code disables Direct3D lighting. HR(gd3dDevice->SetRenderState(D3DRS_LIGHTING, false)); // The following code specifies an alpha test and reference value. HR(gd3dDevice->SetRenderState(D3DRS_ALPHAREF, 10)); HR(gd3dDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER)); // The following code is used to setup alpha blending. HR(gd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE)); HR(gd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1)); HR(gd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA)); HR(gd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA)); // Indicates that we are using 2D texture coordinates. HR(gd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2));}void Connect4::updateScene(float dt){ // see who's turn it is and get input if player turn gDInput->poll(); if (mTurn == mPlayer) { humanMove(); } else { computerMove(); }}void Connect4::drawBackground(){ // Turn on the alpha state HR(gd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, true)); // draw the background sprite HR(mSprite->Draw(mTexture, &mBkgrdRect, &mBkgrdCntr, 0, D3DCOLOR_XRGB(255,255,255))); HR(mSprite->Flush()); // Turn off the alpha state HR(gd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false));}void Connect4::drawPieces(){ // variable to keep track of the positon D3DXVECTOR3 temp; // loop and draw board for (int col = 0; col <= 6; ++col) { for (int row = 0; row <= 5; ++row) { temp = D3DXVECTOR3((float)((col*101)-302), (float)((row*101)-252), 0.0f); // check and see who is where, 1 is red, 2 is black, 0 is blank if (mBoard[row][col] == 1) { HR(mSprite->Draw(mTexture, &mRedRect, &mRedCntr, &temp, D3DCOLOR_XRGB(255,255,255))); } else if(mBoard[row][col] == 2) { HR(mSprite->Draw(mTexture, &mBlackRect, &mBlackCntr, &temp, D3DCOLOR_XRGB(255,255,255))); } } } logBoard(mBoard); HR(mSprite->Flush());}void Connect4::drawScene(){ HR(gd3dDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(255,255,255), 1.0f, 0)); //white HR(gd3dDevice->BeginScene()); HR(mSprite->Begin(D3DXSPRITE_OBJECTSPACE | D3DXSPRITE_DONOTMODIFY_RENDERSTATE)); // pieces must be drawn first otherwise the board will look funny drawPieces(); drawBackground(); HR(mSprite->End()); HR(gd3dDevice->EndScene()); HR(gd3dDevice->Present(0, 0, 0, 0));}void Connect4::humanMove(){ // see if player is pressing the 1 key if (gDInput->keyDown(DIK_1)) { // log it for debug logKey("Key 1 pressed."); // key one pressed, see if the top of the column is empty if (mBoard[5][0] == 0) { // column has empty space, find bottommost open spot and move there for (int i = 0; i < NUM_ROWS; i++) { // see if the current spot is open if (mBoard[0] == 0) { // empty, put player piece there and change to computer move mBoard[0] = mPlayer; mTurn = opponent(mTurn); logTurn("Player has moved to column 1 and space ", i); return; } else { // space is full move on } // continue to loop till spot found. } // space is occupied can't go in this column mTurn = mPlayer; } // key wasn't pressed move on }}void Connect4::computerMove(){ // wrtie computer turn to file logTurn("Computer turn."); mTurn = opponent(mTurn);}int Connect4::opponent(int turn){ if (turn == 1) return 2; else return 1;}void Connect4::announceWinner(){}void Connect4::winner(){}int Connect4::getTurn(){ return mTurn;}
d3dapp.cpp
//=============================================================================// d3dApp.h by Frank Luna (C) 2005 All Rights Reserved.//=============================================================================#include "Global.h"D3DApp* gd3dApp = 0;IDirect3DDevice9* gd3dDevice = 0;LRESULT CALLBACKMainWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ // Don't start processing messages until the application has been created. if( gd3dApp != 0 ) return gd3dApp->msgProc(msg, wParam, lParam); else return DefWindowProc(hwnd, msg, wParam, lParam);}D3DApp::D3DApp(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP){ mMainWndCaption = winCaption; mDevType = devType; mRequestedVP = requestedVP; mhAppInst = hInstance; mhMainWnd = 0; md3dObject = 0; mAppPaused = false; ZeroMemory(&md3dPP, sizeof(md3dPP)); initMainWindow(); initDirect3D();}D3DApp::~D3DApp(){ ReleaseCOM(md3dObject); ReleaseCOM(gd3dDevice);}HINSTANCE D3DApp::getAppInst(){ return mhAppInst;}HWND D3DApp::getMainWnd(){ return mhMainWnd;}void D3DApp::initMainWindow(){ WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = MainWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = mhAppInst; wc.hIcon = LoadIcon(0, IDI_APPLICATION); wc.hCursor = LoadCursor(0, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = "D3DWndClassName"; if( !RegisterClass(&wc) ) { MessageBox(0, "RegisterClass FAILED", 0, 0); PostQuitMessage(0); } // Default to a window with a client area rectangle of 700x600. RECT R = {0, 0, 800, 600}; AdjustWindowRect(&R, WS_OVERLAPPEDWINDOW, false); mhMainWnd = CreateWindow("D3DWndClassName", mMainWndCaption.c_str(), WS_OVERLAPPEDWINDOW, 100, 100, R.right, R.bottom, 0, 0, mhAppInst, 0); if( !mhMainWnd ) { MessageBox(0, "CreateWindow FAILED", 0, 0); PostQuitMessage(0); } ShowWindow(mhMainWnd, SW_SHOW); UpdateWindow(mhMainWnd);}void D3DApp::initDirect3D(){ // Step 1: Create the IDirect3D9 object. md3dObject = Direct3DCreate9(D3D_SDK_VERSION); if( !md3dObject ) { MessageBox(0, "Direct3DCreate9 FAILED", 0, 0); PostQuitMessage(0); } // Step 2: Verify hardware support for specified formats in windowed and full screen modes. D3DDISPLAYMODE mode; md3dObject->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &mode); HR(md3dObject->CheckDeviceType(D3DADAPTER_DEFAULT, mDevType, mode.Format, mode.Format, true)); HR(md3dObject->CheckDeviceType(D3DADAPTER_DEFAULT, mDevType, D3DFMT_X8R8G8B8, D3DFMT_X8R8G8B8, false)); // Step 3: Check for requested vertex processing and pure device. D3DCAPS9 caps; HR(md3dObject->GetDeviceCaps(D3DADAPTER_DEFAULT, mDevType, &caps)); DWORD devBehaviorFlags = 0; if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) devBehaviorFlags |= mRequestedVP; else devBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; // If pure device and HW T&L supported if( caps.DevCaps & D3DDEVCAPS_PUREDEVICE && devBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) devBehaviorFlags |= D3DCREATE_PUREDEVICE; // Step 4: Fill out the D3DPRESENT_PARAMETERS structure. md3dPP.BackBufferWidth = 0; md3dPP.BackBufferHeight = 0; md3dPP.BackBufferFormat = D3DFMT_UNKNOWN; md3dPP.BackBufferCount = 1; md3dPP.MultiSampleType = D3DMULTISAMPLE_NONE; md3dPP.MultiSampleQuality = 0; md3dPP.SwapEffect = D3DSWAPEFFECT_DISCARD; md3dPP.hDeviceWindow = mhMainWnd; md3dPP.Windowed = true; md3dPP.EnableAutoDepthStencil = true; md3dPP.AutoDepthStencilFormat = D3DFMT_D24S8; md3dPP.Flags = 0; md3dPP.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; md3dPP.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Step 5: Create the device. HR(md3dObject->CreateDevice( D3DADAPTER_DEFAULT, // primary adapter mDevType, // device type mhMainWnd, // window associated with device devBehaviorFlags, // vertex processing &md3dPP, // present parameters &gd3dDevice)); // return created device}int D3DApp::run(){ MSG msg; msg.message = WM_NULL; __int64 cntsPerSec = 0; QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec); float secsPerCnt = 1.0f / (float)cntsPerSec; __int64 prevTimeStamp = 0; QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp); while(msg.message != WM_QUIT) { // If there are Window messages then process them. if(PeekMessage( &msg, 0, 0, 0, PM_REMOVE )) { TranslateMessage( &msg ); DispatchMessage( &msg ); } // Otherwise, do animation/game stuff. else { // If the application is paused then free some CPU cycles to other // applications and then continue on to the next frame. if( mAppPaused ) { Sleep(20); continue; } if( !isDeviceLost() ) { __int64 currTimeStamp = 0; QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp); float dt = (currTimeStamp - prevTimeStamp)*secsPerCnt; updateScene(dt); drawScene(); // Prepare for next iteration: The current time stamp becomes // the previous time stamp for the next iteration. prevTimeStamp = currTimeStamp; } } } return (int)msg.wParam;}LRESULT D3DApp::msgProc(UINT msg, WPARAM wParam, LPARAM lParam){ // Is the application in a minimized or maximized state? static bool minOrMaxed = false; RECT clientRect = {0, 0, 0, 0}; switch( msg ) { // WM_ACTIVE is sent when the window is activated or deactivated. // We pause the game when the main window is deactivated and // unpause it when it becomes active. case WM_ACTIVATE: if( LOWORD(wParam) == WA_INACTIVE ) mAppPaused = true; else mAppPaused = false; return 0; // WM_SIZE is sent when the user resizes the window. case WM_SIZE: if( gd3dDevice ) { md3dPP.BackBufferWidth = LOWORD(lParam); md3dPP.BackBufferHeight = HIWORD(lParam); if( wParam == SIZE_MINIMIZED ) { mAppPaused = true; minOrMaxed = true; } else if( wParam == SIZE_MAXIMIZED ) { mAppPaused = false; minOrMaxed = true; onLostDevice(); HR(gd3dDevice->Reset(&md3dPP)); onResetDevice(); } // Restored is any resize that is not a minimize or maximize. // For example, restoring the window to its default size // after a minimize or maximize, or from dragging the resize // bars. else if( wParam == SIZE_RESTORED ) { mAppPaused = false; // Are we restoring from a mimimized or maximized state, // and are in windowed mode? Do not execute this code if // we are restoring to full screen mode. if( minOrMaxed && md3dPP.Windowed ) { onLostDevice(); HR(gd3dDevice->Reset(&md3dPP)); onResetDevice(); } else { // No, which implies the user is resizing by dragging // the resize bars. However, we do not reset the device // here because as the user continuously drags the resize // bars, a stream of WM_SIZE messages is sent to the window, // and it would be pointless (and slow) to reset for each // WM_SIZE message received from dragging the resize bars. // So instead, we reset after the user is done resizing the // window and releases the resize bars, which sends a // WM_EXITSIZEMOVE message. } minOrMaxed = false; } } return 0; // WM_EXITSIZEMOVE is sent when the user releases the resize bars. // Here we reset everything based on the new window dimensions. case WM_EXITSIZEMOVE: GetClientRect(mhMainWnd, &clientRect); md3dPP.BackBufferWidth = clientRect.right; md3dPP.BackBufferHeight = clientRect.bottom; onLostDevice(); HR(gd3dDevice->Reset(&md3dPP)); onResetDevice(); return 0; // WM_CLOSE is sent when the user presses the 'X' button in the // caption bar menu. case WM_CLOSE: DestroyWindow(mhMainWnd); return 0; // WM_DESTROY is sent when the window is being destroyed. case WM_DESTROY: PostQuitMessage(0); return 0; case WM_KEYDOWN: if( wParam == VK_ESCAPE ) enableFullScreenMode(false); else if( wParam == 'F' ) enableFullScreenMode(true); return 0; } return DefWindowProc(mhMainWnd, msg, wParam, lParam);}void D3DApp::enableFullScreenMode(bool enable){ // Switch to fullscreen mode. if( enable ) { // Are we already in fullscreen mode? if( !md3dPP.Windowed ) return; int width = GetSystemMetrics(SM_CXSCREEN); int height = GetSystemMetrics(SM_CYSCREEN); md3dPP.BackBufferFormat = D3DFMT_X8R8G8B8; md3dPP.BackBufferWidth = width; md3dPP.BackBufferHeight = height; md3dPP.Windowed = false; // Change the window style to a more fullscreen friendly style. SetWindowLongPtr(mhMainWnd, GWL_STYLE, WS_POPUP); // If we call SetWindowLongPtr, MSDN states that we need to call // SetWindowPos for the change to take effect. In addition, we // need to call this function anyway to update the window dimensions. SetWindowPos(mhMainWnd, HWND_TOP, 0, 0, width, height, SWP_NOZORDER | SWP_SHOWWINDOW); } // Switch to windowed mode. else { // Are we already in windowed mode? if( md3dPP.Windowed ) return; RECT R = {0, 0, 800, 600}; AdjustWindowRect(&R, WS_OVERLAPPEDWINDOW, false); md3dPP.BackBufferFormat = D3DFMT_UNKNOWN; md3dPP.BackBufferWidth = 800; md3dPP.BackBufferHeight = 600; md3dPP.Windowed = true; // Change the window style to a more windowed friendly style. SetWindowLongPtr(mhMainWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW); // If we call SetWindowLongPtr, MSDN states that we need to call // SetWindowPos for the change to take effect. In addition, we // need to call this function anyway to update the window dimensions. SetWindowPos(mhMainWnd, HWND_TOP, 100, 100, R.right, R.bottom, SWP_NOZORDER | SWP_SHOWWINDOW); } // Reset the device with the changes. onLostDevice(); HR(gd3dDevice->Reset(&md3dPP)); onResetDevice();}bool D3DApp::isDeviceLost(){ // Get the state of the graphics device. HRESULT hr = gd3dDevice->TestCooperativeLevel(); // If the device is lost and cannot be reset yet then // sleep for a bit and we'll try again on the next // message loop cycle. if( hr == D3DERR_DEVICELOST ) { Sleep(20); return true; } // Driver error, exit. else if( hr == D3DERR_DRIVERINTERNALERROR ) { MessageBox(0, "Internal Driver Error...Exiting", 0, 0); PostQuitMessage(0); return true; } // The device is lost but we can reset and restore it. else if( hr == D3DERR_DEVICENOTRESET ) { onLostDevice(); HR(gd3dDevice->Reset(&md3dPP)); onResetDevice(); return false; } else return false;}
directinput.cpp
//=============================================================================// DirectInput.cpp by Frank Luna (C) 2005 All Rights Reserved.//=============================================================================#include "Global.h"DirectInput* gDInput = 0;DirectInput::DirectInput(DWORD keyboardCoopFlags, DWORD mouseCoopFlags){ ZeroMemory(mKeyboardState, sizeof(mKeyboardState)); ZeroMemory(&mMouseState, sizeof(mMouseState)); HR(DirectInput8Create(gd3dApp->getAppInst(), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&mDInput, 0)); HR(mDInput->CreateDevice(GUID_SysKeyboard, &mKeyboard, 0)); HR(mKeyboard->SetDataFormat(&c_dfDIKeyboard)); HR(mKeyboard->SetCooperativeLevel(gd3dApp->getMainWnd(), keyboardCoopFlags)); HR(mKeyboard->Acquire()); HR(mDInput->CreateDevice(GUID_SysMouse, &mMouse, 0)); HR(mMouse->SetDataFormat(&c_dfDIMouse2)); HR(mMouse->SetCooperativeLevel(gd3dApp->getMainWnd(), mouseCoopFlags)); HR(mMouse->Acquire());}DirectInput::~DirectInput(){ ReleaseCOM(mDInput); mKeyboard->Unacquire(); mMouse->Unacquire(); ReleaseCOM(mKeyboard); ReleaseCOM(mMouse);}void DirectInput::poll(){ // Poll keyboard. HRESULT hr = mKeyboard->GetDeviceState(sizeof(mKeyboardState), (void**)&mKeyboardState); if( FAILED(hr) ) { // Keyboard lost, zero out keyboard data structure. ZeroMemory(mKeyboardState, sizeof(mKeyboardState)); // Try to acquire for next time we poll. hr = mKeyboard->Acquire(); } // Poll mouse. hr = mMouse->GetDeviceState(sizeof(DIMOUSESTATE2), (void**)&mMouseState); if( FAILED(hr) ) { // Mouse lost, zero out mouse data structure. ZeroMemory(&mMouseState, sizeof(mMouseState)); // Try to acquire for next time we poll. hr = mMouse->Acquire(); }}bool DirectInput::keyDown(char key){ return (mKeyboardState[key] & 0x80) != 0;}bool DirectInput::mouseButtonDown(int button){ return (mMouseState.rgbButtons[button] & 0x80) != 0;}float DirectInput::mouseDX(){ return (float)mMouseState.lX;}float DirectInput::mouseDY(){ return (float)mMouseState.lY;}float DirectInput::mouseDZ(){ return (float)mMouseState.lZ;}
tools.cpp
//////////////////////////////////////////////////////////////////////////////////////// // File: Tools.cpp// Desc: implementation of common helper functins// Author: Chris Miiler// Date 6/12/o8////////////////////////////////////////////////////////////////////////////////////////#include "Global.h"void logError(std::string msg){ // open the file to write to it std::fstream errFile("debug.txt", std::ios::out | std::ios::app); // make sure the file is open if (errFile.is_open()) { errFile << msg; }}void logKey(std::string msg){ std::ofstream outFile("keys.txt", std::ios::out | std::ios::app); if (outFile.is_open()) { outFile << msg << std::endl; }}void logTurn(std::string msg){ std::ofstream outFile("turn.txt", std::ios::out | std::ios::app); if (outFile.is_open()) { outFile << msg << std::endl; }}void logTurn(std::string msg, int space){ std::ofstream outFile("turn.txt", std::ios::out | std::ios::app); if (outFile.is_open()) { outFile << msg << " " << space << std::endl; }}void logBoard(int mBoard[6][7]){ std::ofstream outFile("board.txt", std::ios::out | std::ios::app); if (outFile.is_open()) { for (int i = 5; i < -1; i--) { outFile << "{"; for (int j = 0; j < 7; j++) { outFile << mBoard[j] << " "; } outFile << "}\n"; } outFile << "\n\n"; }}
I really appreciate your helping this uber noob out, Hope someone can give me a suggestion as to how to do it. And if there are things that anybody sees that should be changed i'll take those suggestions as well.