#include <iostream>
#include <graphics.h>
#include <string>
#include <stdio.h>
#include <conio.h>
using namespace std;
int idx_current_anim = 0;
const int PLAYER_ANIM_NUM = 6;
IMAGE img_player_left[PLAYER_ANIM_NUM];
IMAGE img_player_right[PLAYER_ANIM_NUM];
int PLAYER_SPEED = 10;
POINT player_pos = {500,500};
#pragma comment(lib,"MSIMG32.LIB")
inline void putimage_alpha(int x,int y,IMAGE* img)
{
int w = img->getwidth();
int h = img->getheight();
AlphaBlend(GetImageHDC(NULL), x, y, w, h, GetImageHDC(img), 0, 0, w, h, { AC_SRC_OVER,0,255,AC_SRC_ALPHA });
}
void LoadAnimation()
{
for (size_t i = 0; i < PLAYER_ANIM_NUM; i++)
{
wstring path = L"img/player_left_" + to_wstring(i) + L".png";
loadimage(&img_player_left[i], path.c_str());
}
for (size_t i = 0; i < PLAYER_ANIM_NUM; i++)
{
wstring path = L"img/player_right_" + to_wstring(i) + L".png";
loadimage(&img_player_right[i], path.c_str());
}
}
int main()
{
initgraph(1280, 720);
IMAGE img_background;
bool running = true;
bool is_up = false;
bool is_down = false;
bool is_left = false;
bool is_right = false;
bool is_turn_right = false;
bool is_turn_left = true;
BeginBatchDraw();
while (running)
{
DWORD start_time = GetTickCount();
loadimage(&img_background, _T("img/background.png"));
LoadAnimation();
ExMessage msg;
while (peekmessage(&msg))
{
if (msg.message == WM_KEYDOWN)
{
switch (msg.vkcode)
{
case VK_UP:
is_up = true;
break;
case VK_DOWN:
is_down = true;
break;
case VK_LEFT:
is_left = true;
is_turn_left = true;
break;
case VK_RIGHT:
is_right = true;
is_turn_left = false;
break;
}
}
else if (msg.message == WM_KEYUP)
{
switch (msg.vkcode)
{
case VK_UP:
is_up = false;
break;
case VK_DOWN:
is_down = false;
break;
case VK_LEFT:
is_left = false;
break;
case VK_RIGHT:
is_right = false;
break;
}
}
}
if (is_up) player_pos.y -= PLAYER_SPEED;
if (is_down) player_pos.y += PLAYER_SPEED;
if (is_left) player_pos.x -= PLAYER_SPEED;
if (is_right) player_pos.x += PLAYER_SPEED;
DWORD end_time = GetTickCount();
DWORD delta_time = end_time - start_time;
if (delta_time < 1000 / 144)
{
Sleep(1000 / 144 - delta_time);
}
cleardevice();
static int counter = 0;
if (++counter % 5 == 0)
{
idx_current_anim++;
}
idx_current_anim = idx_current_anim % PLAYER_ANIM_NUM;
putimage_alpha(0, 0, &img_background);
if(is_turn_left) putimage_alpha(player_pos.x, player_pos.y, &img_player_left[idx_current_anim]);
else putimage_alpha(player_pos.x, player_pos.y, &img_player_right[idx_current_anim]);
FlushBatchDraw();
}
EndBatchDraw();
_getch();
closegraph();
}