首先是代码:

MyDirectX.h:

 #pragma once
//header file
#define WIN32_EXTRA_LEAN
#define DIRECTINPUT_VERSION 0x0800
#include<Windows.h>
#include<d3d9.h>
#include<d3dx9.h>
#include<dinput.h>
#include<xinput.h>
#include<time.h>
#include<iostream>
#include<iomanip>
#include<sstream>
using namespace std;
//libraries
#pragma comment(lib,"winmm.lib")
#pragma comment(lib,"user32.lib")
#pragma comment(lib,"gdi32.lib")
#pragma comment(lib,"dxguid.lib")
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")
#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"xinput.lib")
//program values
extern const string APPTITLE;
extern const int SCREENW;
extern const int SCREENH;
extern bool gameover;
//Direct3D objects
extern LPDIRECT3D9 d3d;
extern LPDIRECT3DDEVICE9 d3ddev;
extern LPDIRECT3DSURFACE9 backbuffer;
//Direct3D functions
bool Direct3D_Init(HWND hwnd, int width, int height, bool fullscreen);
void Direct3D_Shutdown();
LPDIRECT3DSURFACE9 LoadSurface(string filename);
void DrawSurface(LPDIRECT3DSURFACE9 dest, float x, float y, LPDIRECT3DSURFACE9 source);
//DirectInput objects,devices,and states
extern LPDIRECTINPUT8 dinput;
extern LPDIRECTINPUTDEVICE8 dimouse;
extern LPDIRECTINPUTDEVICE8 dikeyboard;
extern DIMOUSESTATE mouse_state;
extern XINPUT_GAMEPAD controllers[];
//DirectInput functions
bool DirectInput_Init(HWND);
void DirectInput_Update();
void DirectInput_Shutdown();
int Key_Down(int);
int Mouse_Button(int);
int Mouse_X();
int Mouse_Y();
void XInput_Vibrate(int contNum = , int amount = );
bool XInput_Controller_Found();
//game functions
bool Game_Init(HWND window);
void Game_Run(HWND window);
void Game_End();

MyDirectX.cpp:

 #include "MyDirectX.h"
#include<iostream>
using namespace std;
//Direct3D variables
LPDIRECT3D9 d3d = NULL;
LPDIRECT3DDEVICE9 d3ddev = NULL;
LPDIRECT3DSURFACE9 backbuffer = NULL;
//DirectInput variables
LPDIRECTINPUT8 dinput = NULL;
LPDIRECTINPUTDEVICE8 dimouse = NULL;
LPDIRECTINPUTDEVICE8 dikeyboard = NULL;
DIMOUSESTATE mouse_state;
char keys[];
XINPUT_GAMEPAD controllers[];
//Direct3D initiallization
bool Direct3D_Init(HWND window, int width, int height, bool fullscreen)
{
//initialize Direct3D
d3d = Direct3DCreate9(D3D_SDK_VERSION);
if (!d3d) return false;
//set Direct3D presentation parameters
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = (!fullscreen);
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = ;
d3dpp.BackBufferWidth = width;
d3dpp.BackBufferHeight = height;
d3dpp.hDeviceWindow = window;
//create Direct3D device
d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,window, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);
if (!d3ddev) return false;
//get a pointer to the back buffer surface
d3ddev->GetBackBuffer(, , D3DBACKBUFFER_TYPE_MONO, &backbuffer);
return true;
}
//Direct3D shutdown
void Direct3D_Shutdown()
{
if (d3ddev) d3ddev->Release();
if (d3d) d3d->Release();
}
//Draw a surface to the screen using StretchRect
void DrawSurface(LPDIRECT3DSURFACE9 dest, float x, float y, LPDIRECT3DSURFACE9 source)
{
//get width/height from source surface
D3DSURFACE_DESC desc;
source->GetDesc(&desc);
//create rects for drawing
RECT source_rect = { ,,(long)desc.Width,(long)desc.Height };
RECT dest_rect = { (long)x,(long)y,(long)x + desc.Width,(long)y + desc.Height };
//draw the source surface onto the dest
d3ddev->StretchRect(source, &source_rect, dest, &dest_rect, D3DTEXF_NONE);
}
//Loads a bitmap file into a surface
LPDIRECT3DSURFACE9 LoadSurface(string filename)
{
LPDIRECT3DSURFACE9 image = NULL;
//get width and height from bitmap file
D3DXIMAGE_INFO info;
HRESULT result = D3DXGetImageInfoFromFile(filename.c_str(), &info);
if (result != D3D_OK) return NULL;
//create surface
result = d3ddev->CreateOffscreenPlainSurface(
info.Width, //width of the surface
info.Height, //height of the surface
D3DFMT_X8R8G8B8, //surface format
D3DPOOL_DEFAULT, //memorypool to use
& image, //pointer to the surface
NULL); //reserved(always NULL)
if (result != D3D_OK) return NULL;
//Load surface from file into newly created surface
result = D3DXLoadSurfaceFromFile(
image, //destination surface
NULL, //destination palette
NULL, //destination rectangle
filename.c_str(), //source filename
NULL, //source rectangle
D3DX_DEFAULT, //controls how image is filtered
D3DCOLOR_XRGB(, , ), //for transparency(0 for none)
NULL); //source image info(usually NULL)
//make sure file was loaded okay
if (result != D3D_OK) return NULL;
return image;
}
//DIrectInput initlization
bool DirectInput_Init(HWND hwnd)
{
//initialize DirectInput object
HRESULT result = DirectInput8Create(
GetModuleHandle(NULL),
DIRECTINPUT_VERSION,
IID_IDirectInput8,
(void**)&dinput,
NULL);
//initialize the keyboard
dinput->CreateDevice(GUID_SysKeyboard, &dikeyboard, NULL);
dikeyboard->SetDataFormat(&c_dfDIKeyboard);
dikeyboard->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
dikeyboard->Acquire();
//initialize the mouse
dinput->CreateDevice(GUID_SysMouse, &dimouse, NULL);
dimouse->SetDataFormat(&c_dfDIMouse);
dimouse->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
dimouse->Acquire();
d3ddev->ShowCursor(false);
return true;
}
//DirectInput update
void DirectInput_Update()
{
//update mouse
dimouse->GetDeviceState(sizeof(mouse_state), (LPVOID)&mouse_state);
//update keyboard
dikeyboard->GetDeviceState(sizeof(keys), (LPVOID)&keys);
//update controllers
for (int i = ; i < ; i++)
{
ZeroMemory(&controllers[i], sizeof(XINPUT_STATE));
//get the state of the controller
XINPUT_STATE state;
DWORD result = XInputGetState(i, &state);
//store state in global controllers array
if (result == ) controllers[i] = state.Gamepad;
}
}
//Return mouse x movement
int Mouse_X()
{
return mouse_state.lX;
}
//Return mouse y movement
int Mouse_Y()
{
return mouse_state.lY;
}
//Return mouse button state
int Mouse_Button(int button)
{
return mouse_state.rgbButtons[button] & 0x80;
}
//Return key press state
int Key_Down(int key)
{
return (keys[key] & 0x80);
}
//DirectInput shutdown
void DirectInput_Shutdown()
{
if (dikeyboard)
{
dikeyboard->Unacquire();
dikeyboard->Release();
dikeyboard = NULL;
}
if (dimouse)
{
dimouse->Unacquire();
dimouse->Release();
dimouse = NULL;
}
}
//Return true if controller is plugged in
bool XInput_Controller_Found()
{
XINPUT_CAPABILITIES caps;
ZeroMemory(&caps, sizeof(XINPUT_CAPABILITIES));
XInputGetCapabilities(, XINPUT_FLAG_GAMEPAD, &caps);
if (caps.Type != ) return FALSE; return TRUE;
}
//Vibrates the controller
void XInput_Vibrate(int contNum, int amount)
{
XINPUT_VIBRATION vibration;
ZeroMemory(&vibration, sizeof(XINPUT_VIBRATION));
vibration.wLeftMotorSpeed = amount;
vibration.wRightMotorSpeed = amount;
XInputSetState(contNum, &vibration);
}

MyGame.cpp:

 #include "MyDirectX.h"
const string APPTITLE = "Bomb Catcher Game";
const int SCREENW = ;
const int SCREENH = ;
LPDIRECT3DSURFACE9 bomb_surf = NULL;
LPDIRECT3DSURFACE9 bucket_surf = NULL;
struct BOMB
{
float x, y;
void reset()
{
x = (float)(rand() % (SCREENW - ));
y = ;
}
};
BOMB bomb; struct BUCKET
{
float x, y;
};
BUCKET bucket;
int score = ;
int vibrating = ;
bool Game_Init(HWND window)
{
Direct3D_Init(window, SCREENW, SCREENH, false);
DirectInput_Init(window);
bomb_surf = LoadSurface("images/bomb.bmp");
if (!bomb_surf) {
MessageBox(window, "Error loadng bomb", "Error", );
return false;
}
bucket_surf = LoadSurface("images/bucket.bmp");
if (!bucket_surf) {
MessageBox(window, "Error loadng bucket", "Error", );
return false;
}
//get the back buffer surface
d3ddev->GetBackBuffer(, , D3DBACKBUFFER_TYPE_MONO, &backbuffer);
//position the bomb
srand((unsigned int)time(NULL));
bomb.reset();
//psition the bucket
bucket.x = ;
bucket.y = ;
return true;
}
void Game_Run(HWND window)
{
//make sure the Direct3D device is valid
if (!d3ddev)return;
//update input device
DirectInput_Update();
//move the bomb down the screen
bomb.y += 2.0f;
//see if bomb hit the floor
if (bomb.y > SCREENH)
{
MessageBox(, "Oh,no, the bomb exploded!!", "YOU STINK", );
gameover = true;
}
//move the bucket with the mouse
int mx = Mouse_X();
if (mx < )
bucket.x -= 6.0f;
else if (mx > )
bucket.x += 6.0f;
//move the bucket with the keyboard
if (Key_Down(DIK_LEFT)) bucket.x -= 6.0f;
else if (Key_Down(DIK_RIGHT)) bucket.x += 6.0f;
//move the bucket with the controller
if (XInput_Controller_Found())
{
//left analog thumb stick
if (controllers[].sThumbLX < -)
bucket.x -= 6.0f;
else if (controllers[].sThumbLX > )
bucket.x += 6.0f;
//left and right triggers
if (controllers[].bLeftTrigger > )
bucket.x -= 6.0f;
else if (controllers[].bRightTrigger > )
bucket.x += 6.0f;
//left and right D-PAD
if (controllers[].wButtons&XINPUT_GAMEPAD_LEFT_SHOULDER)
bucket.x -= 6.0f;
else if (controllers[].wButtons&XINPUT_GAMEPAD_RIGHT_SHOULDER)
bucket.x += 6.0f;
//left and right shoulders
if(controllers[].wButtons&XINPUT_GAMEPAD_DPAD_LEFT)
bucket.x -= 6.0f;
if (controllers[].wButtons&XINPUT_GAMEPAD_DPAD_RIGHT)
bucket.x += 6.0f;
}
//update vibration
if (vibrating > )
{
vibrating++;
if (vibrating > )
{
XInput_Vibrate(, );
vibrating = ;
}
}
//keep bucket inside the screen
if (bucket.x < ) bucket.x = ;
if (bucket.x > SCREENW - ) bucket.x = SCREENW - ;
//see if bucket caugth the bomb
int cx = bomb.x + ;
int cy = bomb.y + ;
if (cx > bucket.x&&cx<bucket.x + && cy>bucket.y&&cy < bucket.y + )
{
//update and display score
score++;
std::ostringstream os;
os << APPTITLE << " [SCORE " << score << "]";
string scoreStr = os.str();
SetWindowText(window, scoreStr.c_str());
//vibrate the controller
XInput_Vibrate(, );
vibrating = ;
//restart bomb
bomb.reset();
}
//clear the backbuffer
d3ddev->ColorFill(backbuffer, NULL, D3DCOLOR_XRGB(, , ));
//start rendering
if (d3ddev->BeginScene())
{
//draw the bomb
DrawSurface(backbuffer, bomb.x, bomb.y, bomb_surf);
//draw the bucket
DrawSurface(backbuffer, bucket.x, bucket.y, bucket_surf);
//stop rendering
d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);
}
//escape key exits
if (Key_Down(DIK_SPACE) || Key_Down(DIK_ESCAPE))
gameover = true;
//controller Back button also exits
if (controllers[].wButtons&XINPUT_GAMEPAD_BACK)
gameover = true;
}
void Game_End()
{
if (bomb_surf) bomb_surf->Release();
if (bucket_surf) bucket_surf->Release();
DirectInput_Shutdown();
Direct3D_Shutdown();
}

MyWindows.cpp:

 #include "MyDirectX.h"
using namespace std;
bool gameover = false;
//Windows event handler
LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
gameover = true;
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
//Windows entry point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wc;
MSG msg;
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = (WNDPROC)WinProc;
wc.style = ;
wc.cbClsExtra = ;
wc.cbWndExtra = ;
wc.hIcon = NULL;
wc.hIconSm = NULL;
wc.hInstance = hInstance;
wc.lpszMenuName = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszClassName = "MainWindowClass";
if (!RegisterClassEx(&wc))
return FALSE;
HWND window = CreateWindow("MainWindowClass", APPTITLE.c_str(), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, SCREENW, SCREENH, (HWND)NULL, (HMENU)NULL,
hInstance, (LPVOID)NULL);
if (window == )
return ;
ShowWindow(window, nCmdShow);
UpdateWindow(window);
if (!Game_Init(window))
return ;
while (!gameover)
{
if (PeekMessage(&msg, NULL, , , PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Game_Run(window);
}
Game_End();
return msg.wParam;
}

结果:

游戏编程入门之Bomb Catcher游戏的更多相关文章

  1. Python游戏编程入门 中文pdf扫描版|网盘下载内附地址提取码|

    Python是一种解释型.面向对象.动态数据类型的程序设计语言,在游戏开发领域,Python也得到越来越广泛的应用,并由此受到重视. 本书教授用Python开发精彩游戏所需的[]为重要的该你那.本书不 ...

  2. PC游戏编程(入门篇)(前言写的很不错)

    PC游戏编程(入门篇) 第一章 基石 1. 1 BOSS登场--GAF简介 第二章 2D图形程式初体验 2.l 饮水思源--第一个"游戏"程式 2.2 知其所以然一一2D图形学基础 ...

  3. Python游戏编程入门3

    用户输入:Bomb Catcher游戏本章介绍使用键盘和鼠标获得用户输入.包括如下主题:学习pygame事件学习实时循环学习键盘和鼠标事件学习轮询键盘和鼠标的状态编写Bomb Catcher游戏 1本 ...

  4. Python游戏编程入门

    <Python游戏编程入门>这些文章负责整理在这本书中的知识点.注意事项和课后习题的尝试实现.并且对每一个章节给出的最终实例进行分析和注释. 初识pygame:pie游戏pygame游戏库 ...

  5. Python游戏编程入门2

    I/O.数据和字体:Trivia游戏 本章包括如下内容:Python数据类型获取用户输入处理异常Mad Lib游戏操作文本文件操作二进制文件Trivia游戏 其他的不说,我先去自己学习文件类型和字符串 ...

  6. DirectX游戏编程入门

    刚开始学习D3D,安装完DirectX9后,在VS2008中新建Win32项目· ----------------------------------------------------------- ...

  7. 【Visual C++】游戏编程学习笔记之三:游戏循环的使用

     本系列文章由@二货梦想家张程 所写,转载请注明出处. 本文章链接:http://blog.csdn.net/terence1212/article/details/44208419 作者:Zee ...

  8. python编程学习--Pygame - Python游戏编程入门(0)---转载

    原文地址:https://www.cnblogs.com/wuzhanpeng/p/4261015.html 引言 博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因 ...

  9. Pygame - Python游戏编程入门(0) 转

    博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因为我感觉Python是一门很有意思的语言,很早以前就想学了(碍于懒),它的功能很强大,你可以用它来做科学运算,或者数 ...

随机推荐

  1. Ext JS 6学习文档-第5章-表格组件(grid)

    Ext JS 6学习文档-第5章-表格组件(grid) 使用 Grid 本章将探索 Ext JS 的高级组件 grid .还将使用它帮助读者建立一个功能齐全的公司目录.本章介绍下列几点主题: 基本的 ...

  2. mysql 相同表结构拷贝数据

    第一种方法: 在导出表结构的时候可以勾选导出数据: 第二种方法: 表已经存在了,只需要数据即可.这个时候可以编写sql语句(暂不支持不同服务器之间的表数据复制) insert into tab_a(i ...

  3. ServletContext域对象

    场景:假设某个web服务,有两个servlet分别是servlet1和servlet2,servlet1要传参数name=zhangsan传送给servlet2,传统方法如下: servlet1端:用 ...

  4. 3dContactPointAnnotationTool开发日志(八)

      今天上午去实验室打算把项目从github上pull下来发现貌似不行,然后强行pull下来后项目变得乱七八糟了,有的组件都不知道去哪里了.去github上看了看发现上面day6和day7都没有,特别 ...

  5. Qt Creator子目录项目-类似VS解决方案

    版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:Qt Creator子目录项目-类似VS解决方案     本文地址:http://techie ...

  6. phpmyadmin打开空白

    本地phpstudy环境,打开 phpmyadmin,登陆之后,显示空白页面. 解决办法:切换为 低版本的php版本,正常登陆.

  7. java中多种方式读文件

    转自:http://www.jb51.net/article/16396.htm java中多种方式读文件 一.多种方式读文件内容. 1.按字节读取文件内容 2.按字符读取文件内容 3.按行读取文件内 ...

  8. 【bzoj1616】[Usaco2008 Mar]Cow Travelling游荡的奶牛 bfs

    题目描述 奶牛们在被划分成N行M列(2 <= N <= 100; 2 <= M <= 100)的草地上游走,试图找到整块草地中最美味的牧草.Farmer John在某个时刻看见 ...

  9. Qt——设计颜色编辑选取对话框

    Qt中已经有一些封装好的对话框,比如QMessageBox.QColorDialog等,使用起来快捷方便,但缺点是我们无法为它们自定义样式,所以可能难以“融入”我们的项目.既然如此,那就自己做一个把. ...

  10. Apple - Hdu5160

    Problem Description We are going to distribute apples to n children. Every child has his/her desired ...