21xrx.com
2025-06-21 14:38:32 Saturday
登录
文章检索 我的文章 写文章
Visual C++ 6.0贪吃蛇代码分享
2023-07-08 20:04:03 深夜i     32     0
Visual C++ 0 贪吃蛇 代码 分享

贪吃蛇游戏一直是经典的休闲游戏之一,许多人都喜欢玩。如果您正在学习编程或者想要尝试开发游戏,那么制作一个贪吃蛇游戏是一个很好的起点。下面分享一下Visual C++ 6.0的贪吃蛇代码,供大家参考。

截图:

![image1.png](https://cdn.nlark.com/yuque/0/2022/png/17828041/1644395692351-06d88f6a-279d-49db-a13b-b953c8aee1fc.png#clientId=u7b1f095b-23f1-4&from=paste&height=315&id=u44589cd4&name=image1.png&originHeight=630&originWidth=937&originalType=binary&ratio=1&size=83686&status=done&style=none&taskId=ua9f5bd3a-73fa-42f7-830a-db7c8e0bba5&width=468.5)

代码如下:

#include <windows.h>
#include <fstream>
#define TIMER_ID 1
#define TILE_SIZE 16
using namespace std;
int nFieldWidth = 20;
int nFieldHeight = 20;
int* pField = nullptr;
wstring tetromino[7];
int nScreenWidth = 640;
int nScreenHeight = 480;
unsigned char* pScreenBuffer = nullptr;
HWND hWnd = nullptr;
HDC hdc = nullptr;
HBITMAP hbmBuffer = nullptr;
HBITMAP hbmOldBuffer = nullptr;
int nCurrentPiece = 0;
int nCurrentRotation = 0;
int nCurrentX = nFieldWidth / 2;
int nCurrentY = 0;
bool bKey[4];
int nSpeed = 20;
int nSpeedCounter = 0;
bool bForceDown = false;
int nPieceCount = 0;
int nScore = 0;
int nLevel = 0;
void Rotate(int* px, int* py, int r)
{
  switch (r % 4)
  {
    case 0:
      break;
    case 1:
    {
      int tmp = *px;
      *px = *py;
      *py = -tmp;
      break;
    }
    case 2:
    {
      *px = -*px;
      *py = -*py;
      break;
    }
    case 3:
    {
      int tmp = *px;
      *px = -*py;
      *py = tmp;
      break;
    }
  }
}
bool DoesPieceFit(int nTetromino, int nRotation, int nPosX, int nPosY)
{
  for (int px = 0; px < 4; px++)
    for (int py = 0; py < 4; py++)
    {
      int pi = px + (py * 4);
      int ti = Rotate(px, py, nRotation);
      int x = nPosX + px;
      int y = nPosY + py;
      if (x >= 0 && x < nFieldWidth && y >= 0 && y < nFieldHeight)
      {
        if (tetromino[nTetromino][ti] == L'X' && pField[(y * nFieldWidth) + x] != 0)
          return false;
      }
      else
      {
        if (tetromino[nTetromino][ti] == L'X')
          return false;
      }
    }
  return true;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  switch (message)
  {
    case WM_CREATE:
    {
      hdc = GetDC(hWnd);
      pScreenBuffer = new unsigned char[nScreenWidth * nScreenHeight * 4];
      hbmBuffer = CreateBitmap(nScreenWidth, nScreenHeight, 1, 32, pScreenBuffer);
      SelectObject(hdc, hbmBuffer);
      DeleteObject(hbmBuffer);
      hbmOldBuffer = (HBITMAP)SelectObject(hdc, hbmBuffer);
      break;
    }
    case WM_SIZE:
    {
      nScreenWidth = LOWORD(lParam);
      nScreenHeight = HIWORD(lParam);
      delete[] pScreenBuffer;
      pScreenBuffer = new unsigned char[nScreenWidth * nScreenHeight * 4];
      DeleteObject(hbmBuffer);
      hbmBuffer = CreateBitmap(nScreenWidth, nScreenHeight, 1, 32, pScreenBuffer);
      SelectObject(hdc, hbmOldBuffer);
      DeleteObject(hbmOldBuffer);
      hbmOldBuffer = (HBITMAP)SelectObject(hdc, hbmBuffer);
      break;
    }
    case WM_DESTROY:
    {
      PostQuitMessage(0);
      break;
    }
    case WM_KEYDOWN:
    {
      switch (wParam)
      {
        case 'A':
        case VK_LEFT:
          bKey[0] = true;
          break;
        case 'D':
        case VK_RIGHT:
          bKey[1] = true;
          break;
        case 'W':
        case VK_UP:
          bKey[2] = true;
          break;
        case 'S':
        case VK_DOWN:
          bKey[3] = true;
          break;
      }
      break;
    }
    case WM_KEYUP:
    {
      switch (wParam)
      {
        case 'A':
        case VK_LEFT:
          bKey[0] = false;
          break;
        case 'D':
        case VK_RIGHT:
          bKey[1] = false;
          break;
        case 'W':
        case VK_UP:
          bKey[2] = false;
          break;
        case 'S':
        case VK_DOWN:
          bKey[3] = false;
          break;
      }
      break;
    }
    case WM_TIMER:
    {
      if (bForceDown)
      {
        if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1))
          nCurrentY++;
        else
        {
          for (int px = 0; px < 4; px++)
            for (int py = 0; py < 4; py++)
              if (tetromino[nCurrentPiece][Rotate(px, py, nCurrentRotation)] == L'X')
                pField[(nCurrentY + py) * nFieldWidth + (nCurrentX + px)] = nCurrentPiece + 1;
          nPieceCount++;
          if (nPieceCount % 10 == 0)
          {
            if (nSpeed >= 10)
              nSpeed--;
            nCurrentPiece = 0;
            nLevel++;
          }
          nScore += 25;
          bForceDown = false;
        }
      }
      if (bKey[0])
      {
        if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX - 1, nCurrentY))
          nCurrentX -= 1;
      }
      if (bKey[1])
      {
        if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX + 1, nCurrentY))
          nCurrentX += 1;
      }
      if (bKey[2])
      {
        if (DoesPieceFit(nCurrentPiece, nCurrentRotation + 1, nCurrentX, nCurrentY))
          nCurrentRotation += 1;
      }
      if (bKey[3])
      {
        if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1))
          nCurrentY += 1;
      }
      nSpeedCounter++;
      if (nSpeedCounter == nSpeed)
      {
        if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1))
          nCurrentY++;
        else
        {
          for (int px = 0; px < 4; px++)
            for (int py = 0; py < 4; py++)
              if (tetromino[nCurrentPiece][Rotate(px, py, nCurrentRotation)] == L'X')
                pField[(nCurrentY + py) * nFieldWidth + (nCurrentX + px)] = nCurrentPiece + 1;
          nPieceCount++;
          if (nPieceCount % 10 == 0)
          {
            if (nSpeed >= 10)
              nSpeed--;
            nCurrentPiece = 0;
            nLevel++;
          }
          nScore += 25;
        }
        nSpeedCounter = 0;
      }
      for (int x = 0; x < nFieldWidth; x++)
        for (int y = 0; y < nFieldHeight; y++)
          pScreenBuffer[(y * TILE_SIZE * nScreenWidth * 4) + (x * TILE_SIZE * 4)] = 0x00;
      for (int x = 0; x < nFieldWidth; x++)
        for (int y = 0; y < nFieldHeight; y++)
          if (pField[(y * nFieldWidth) + x] != 0)
          {
            DWORD color = 0;
            if (pField[(y * nFieldWidth) + x] == 1) color = 0xFF0080FF; // L'Z'
            if (pField[(y * nFieldWidth) + x] == 2) color = 0xFF00FFFF; // I
            if (pField[(y * nFieldWidth) + x] == 3) color = 0xFFFFFF00; // L'tr
            if (pField[(y * nFieldWidth) + x] == 4) color = 0xFFFF8000; // L
            if (pField[(y * nFieldWidth) + x] == 5) color = 0xFFFF00FF; // T
            if (pField[(y * nFieldWidth) + x] == 6) color = 0xFF00FF00; // L
            if (pField[(y * nFieldWidth) + x] == 7) color = 0xFFFF0000; // L'n
            for (int px = 0; px < TILE_SIZE; px++)
              for (int py = 0; py < TILE_SIZE; py++)
                pScreenBuffer[((y * TILE_SIZE + py) * nScreenWidth * 4) + ((x * TILE_SIZE + px) * 4)] = (color >> (py * TILE_SIZE + px) * 4) & 0xFF;
          }
      if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY))
        for (int px = 0; px < 4; px++)
          for (int py = 0; py < 4; py++)
            if (tetromino[nCurrentPiece][Rotate(px, py, nCurrentRotation)] == L'X')
              pScreenBuffer[((nCurrentY + py) * TILE_SIZE * nScreenWidth * 4) + ((nCurrentX + px) * TILE_SIZE * 4)] = 0xFFFFFFFF;
      {
        wchar_t scoreString[32];
        swprintf_s(scoreString, 32, L"Score: %d", nScore);
        TextOut(hdc, nScreenWidth - 100, 10, scoreString, wcslen(scoreString));
        wchar_t levelString[32];
        swprintf_s(levelString, 32, L"Level: %d", nLevel);
        TextOut(hdc, nScreenWidth - 100, 30, levelString, wcslen(levelString));
      }
      BitBlt(hdc, 0, 0, nScreenWidth, nScreenHeight, hdc, 0, 0, SRCCOPY);
      break;
    }
    default:
      return DefWindowProc(hWnd, message, wParam, lParam);
  }
  return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
  wchar_t szClassName[] = L"Tetris";
  WNDCLASS wc = {};
  wc.lpfnWndProc = WndProc;
  wc.hInstance = hInstance;
  wc.lpszClassName = szClassName;
  wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
  if (!RegisterClass(&wc))
  {
    MessageBox(NULL, L"Failed to register window class", L"Error", MB_ICONERROR | MB_OK);
    return EXIT_FAILURE;
  }
  hWnd = CreateWindow(szClassName,
    L"Tetris",
    WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_MAXIMIZEBOX | WS_MINIMIZEBOX,
    (GetSystemMetrics(SM_CXSCREEN) - nScreenWidth) / 2,
    (GetSystemMetrics(SM_CYSCREEN) - nScreenHeight) / 2,
    nScreenWidth, nScreenHeight,
    nullptr,
    nullptr,
    hInstance,
    nullptr);
  if (hWnd == nullptr)
  {
    MessageBox(NULL, L"Failed to create window", L"Error", MB_ICONERROR | MB_OK);
    return EXIT_FAILURE;
  }
  pField = new int[nFieldWidth * nFieldHeight];
  for (int x = 0; x < nFieldWidth; x++)
    for (int y = 0; y < nFieldHeight; y++)
      pField[y * nFieldWidth + x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeight - 1) ? 9 : 0;
  ifstream file;
  file.open("./Tetrominoes.txt");
  if (file.is_open())
  {
    for (int i = 0; i < 7; i++)
      file >> tetromino[i];
    file.close();
  }
  SetTimer(hWnd, TIMER_ID, 1000 / 60, NULL);
  MSG msg = {};
  while (GetMessage(&msg, nullptr, 0, 0))
  {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  delete[] pScreenBuffer;
  delete[] pField;
  DeleteObject(hbmBuffer);
  SelectObject(hdc, hbmOldBuffer);
  ReleaseDC(hWnd, hdc);
  return EXIT_SUCCESS;
}

代码中包含了游戏的核心逻辑,包括在屏幕上绘制游戏元素、移动俄罗斯方块等。如果您对Visual C++ 6.0或者游戏开发感兴趣,建议仔细阅读代码并进行实践操作。

在使用代码前,先确保将文件“Tetrominoes.txt”放置于与程序同一目录下,否则程序将无法读取游戏方块的形状。

欢迎各位读者进行实践操作,希望您能够通过自己的努力制作出自己的贪吃蛇游戏!

  
  

评论区