游戏编程入门之Bomb Catcher游戏
首先是代码:
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游戏的更多相关文章
- Python游戏编程入门 中文pdf扫描版|网盘下载内附地址提取码|
Python是一种解释型.面向对象.动态数据类型的程序设计语言,在游戏开发领域,Python也得到越来越广泛的应用,并由此受到重视. 本书教授用Python开发精彩游戏所需的[]为重要的该你那.本书不 ...
- PC游戏编程(入门篇)(前言写的很不错)
PC游戏编程(入门篇) 第一章 基石 1. 1 BOSS登场--GAF简介 第二章 2D图形程式初体验 2.l 饮水思源--第一个"游戏"程式 2.2 知其所以然一一2D图形学基础 ...
- Python游戏编程入门3
用户输入:Bomb Catcher游戏本章介绍使用键盘和鼠标获得用户输入.包括如下主题:学习pygame事件学习实时循环学习键盘和鼠标事件学习轮询键盘和鼠标的状态编写Bomb Catcher游戏 1本 ...
- Python游戏编程入门
<Python游戏编程入门>这些文章负责整理在这本书中的知识点.注意事项和课后习题的尝试实现.并且对每一个章节给出的最终实例进行分析和注释. 初识pygame:pie游戏pygame游戏库 ...
- Python游戏编程入门2
I/O.数据和字体:Trivia游戏 本章包括如下内容:Python数据类型获取用户输入处理异常Mad Lib游戏操作文本文件操作二进制文件Trivia游戏 其他的不说,我先去自己学习文件类型和字符串 ...
- DirectX游戏编程入门
刚开始学习D3D,安装完DirectX9后,在VS2008中新建Win32项目· ----------------------------------------------------------- ...
- 【Visual C++】游戏编程学习笔记之三:游戏循环的使用
本系列文章由@二货梦想家张程 所写,转载请注明出处. 本文章链接:http://blog.csdn.net/terence1212/article/details/44208419 作者:Zee ...
- python编程学习--Pygame - Python游戏编程入门(0)---转载
原文地址:https://www.cnblogs.com/wuzhanpeng/p/4261015.html 引言 博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因 ...
- Pygame - Python游戏编程入门(0) 转
博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因为我感觉Python是一门很有意思的语言,很早以前就想学了(碍于懒),它的功能很强大,你可以用它来做科学运算,或者数 ...
随机推荐
- Python面向对象-类成员
类的成员可以分为三大类:字段.方法和属性: 注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存中就有多少个普通字段.而其他的成员,则都是保存在类中,即:无论对象的多少,在 ...
- 自测之Lesson12:信号量
题目:创建一个包含5个信号量的信号集. 完成代码: #include <stdio.h> #include <sys/ipc.h> #include <sys/sem.h ...
- 【IdentityServer4文档】- 贡献
贡献 我们非常乐于接受社区贡献,但您应遵循一些指导原则,以便我们可以很方便的解决这个问题. 如何贡献? 最简单的方法是打开一个问题并开始讨论.然后,我们可以决定如何实现一个特性或一个变更.如果您即将提 ...
- java — 值传递和引用传递
在 Java 应用程序中永远不会传递对象,而只传递对象引用.因此是按引用传递对象.Java 应用程序按引用传递对象这一事实并不意味着 Java 应用程序按引用传递参数.参数可以是对象引用,而 Java ...
- JS高级 1
关于string,number是大写,那么就是构造函数,变量不可能为null值,除非手动设置,要解除对象的引用的时候手动去除. in关键字操作数组的时候操作的是索引值,不是里面的内容,.在操作对象的时 ...
- maven仓库中添加自定义的包jar包
mvn install:install-file -DgroupId=impl -DartifactId=center -Dversion=1.0 -Dpackaging=jar -Dfile=D:\ ...
- SQL SERVER 存储过程中SELECT 返回值如何赋值给变量
今天在处理一个问题时,使用到一个存储过程,是用于更新并获取最新ID的.在使用过程中,需要获取到这个ID并赋值给变量,结果用EXEC @ID = 存储过程的方式获取失败了.具体情况如下: 为了还原整个情 ...
- SpringBoot2.0(一) mybatis
使用mybatis springboot使用mybatis主要依赖 mybatis-spring-boot-starter 来实现.其提供了2中解决方案,一种是使用注解:另一种是简化后的传统的xml方 ...
- 移除 ios 上 input 的默认样式
input{ -webkit-appearance:none; }
- hdu3625-Rooms
题目 有\(n\)个房间,\(n\)个钥匙,每个钥匙随机出现在一个房间里,一个房间里有且仅有一个钥匙.我们现在手上没有钥匙,但我们要搜索所有的房间,所以我们有\(k\)次机会把一个房间炸开.一号房间里 ...