C++实现俄罗斯方块(Windows控制台版)

2024-09-08 14:28

本文主要是介绍C++实现俄罗斯方块(Windows控制台版),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

C++实现俄罗斯方块(Windows控制台版)

在油管上看到一个使用C++控制台编写的俄罗斯方块小游戏,源代码200多行,B站上也有相关的讲解视频,非常不错,值得学习。
B站讲解视频地址为:【百万好评】国外技术大神C++游戏编程实战教程,油管580W收藏,新手10小时入门,并快速达到游戏开发能力(中英字幕) B站
CSDN博主千帐灯无此声还为此写了一篇博客:C++实现俄罗斯方块(源码+详解),讲解得已经非常详细了,为此我就不赘余了。
Github源代码地址为:https://github.com/OneLoneCoder/Javidx9/blob/master/SimplyCode/OneLoneCoder_Tetris.cpp

特此贴上对应的C++源代码,记录一下:

/*OneLoneCoder.com - Command Line Tetris"Put Your Money Where Your Mouth Is" - @Javidx9License~~~~~~~Copyright (C) 2018  Javidx9This program comes with ABSOLUTELY NO WARRANTY.This is free software, and you are welcome to redistribute itunder certain conditions; See license for details.Original works located at:https://www.github.com/onelonecoderhttps://www.onelonecoder.comhttps://www.youtube.com/javidx9GNU GPLv3https://github.com/OneLoneCoder/videos/blob/master/LICENSEFrom Javidx9 :)~~~~~~~~~~~~~~~Hello! Ultimately I don't care what you use this for. It's intended to beeducational, and perhaps to the oddly minded - a little bit of fun.Please hack this, change it and use it in any way you see fit. You acknowledgethat I am not responsible for anything bad that happens as a result ofyour actions. However this code is protected by GNU GPLv3, see the license in thegithub repo. This means you must attribute me if you use it. You can view thislicense here: https://github.com/OneLoneCoder/videos/blob/master/LICENSECheers!Background~~~~~~~~~~I made a video "8-Bits of advice for new programmers" (https://youtu.be/vVRCJ52g5m4)and suggested that building a tetris clone instead of Dark Sould IV might be a betterapproach to learning to code. Tetris is nice as it makes you think about algorithms.Controls are Arrow keys Left, Right & Down. Use Z to rotate the piece.You score 25pts per tetronimo, and 2^(number of lines)*100 when you get lines.Future Modifications~~~~~~~~~~~~~~~~~~~~1) Show next block and line counterAuthor~~~~~~Twitter: @javidx9Blog: www.onelonecoder.comVideo:~~~~~~https://youtu.be/8OK8_tHeCIALast Updated: 30/03/2017
*/#include <iostream>
#include <thread>
#include <vector>
using namespace std;#include <stdio.h>
#include <Windows.h>int nScreenWidth = 80;			// Console Screen Size X (columns)
int nScreenHeight = 30;			// Console Screen Size Y (rows)
wstring tetromino[7];
int nFieldWidth = 12;			// 表示场地的宽度,它的值为 12。这意味着在水平方向上,场地被分割成了 12 个单元格或列
int nFieldHeight = 18;			// nFieldHeight 表示场地的高度,它的值为 18。这意味着在垂直方向上,场地被分割成了 18 个单元格或行
// 一个指向无符号字符的指针,初始化为 nullptr。这个指针通常用于动态分配内存,并表示场地的状态或布局。
// 通过使用指针,可以在程序运行时为场地分配所需的内存空间
unsigned char* pField = nullptr;// 方块旋转
// 据给定的方块坐标(px, py)和旋转次数r,返回旋转后方块的索引位置
int Rotate(int px, int py, int r)
{int pi = 0;switch (r % 4){case 0: // 0 degrees			// 0  1  2  3pi = py * 4 + px;			// 4  5  6  7break;						// 8  9 10 11//12 13 14 15case 1: // 90 degrees			//12  8  4  0pi = 12 + py - (px * 4);	//13  9  5  1break;						//14 10  6  2//15 11  7  3case 2: // 180 degrees			//15 14 13 12pi = 15 - (py * 4) - px;	//11 10  9  8break;						// 7  6  5  4// 3  2  1  0case 3: // 270 degrees			// 3  7 11 15pi = 3 - py + (px * 4);		// 2  6 10 14break;						// 1  5  9 13}								// 0  4  8 12return pi;
}// 检查方块是否适合放置在指定位置
/******************************************
* 判断给定的方块是否适合放置在指定的位置(nPosX, nPosY)上。
* 通过遍历方块的每个格子,并将其与场地进行匹配,判断方块是否和场地中的其他方块冲突
* nTetromino:表示方块的类型(编号)
* nRotation:表示方块的旋转状态
* nPosX:表示要放置方块的水平位置(X 坐标)
* nPosY:表示要放置方块的垂直位置(Y 坐标)
*******************************************/
bool DoesPieceFit(int nTetromino, int nRotation, int nPosX, int nPosY)
{// All Field cells >0 are occupiedfor (int px = 0; px < 4; px++)	// 循环遍历方块的水平位置for (int py = 0; py < 4; py++)	// 循环遍历方块的垂直位置{// Get index into piece// 获取方块内部位置的索引int pi = Rotate(px, py, nRotation);// Get index into field// 获取方块在游戏区域中的索引int fi = (nPosY + py) * nFieldWidth + (nPosX + px);// Check that test is in bounds. Note out of bounds does// not necessarily mean a fail, as the long vertical piece// can have cells that lie outside the boundary, so we'll// just ignore themif (nPosX + px >= 0 && nPosX + px < nFieldWidth)	// 检查方块是否在横向范围内{if (nPosY + py >= 0 && nPosY + py < nFieldHeight)	// 检查方块是否在纵向范围内{// In Bounds so do collision checkif (tetromino[nTetromino][pi] != L'.' && pField[fi] != 0)	// 检查方块和游戏区域是否有重叠// 第一个碰撞就返回失败return false; // fail on first hit}}}// 方块适合放置在指定位置return true;
}/*****************************************************
游戏的主函数。包括创建方块、初始化场地和屏幕,
控制游戏逻辑的循环,处理用户输入,更新方块的位置和状态,
判断方块能否放置,渲染输出到屏幕,计分和游戏结束
*****************************************************/
int main()
{// Create Screen Buffer// 创建一个带有空格字符初始化的屏幕缓冲区,并将其设置为活动的屏幕缓冲区,以便后续可以将字符输出到控制台屏幕上wchar_t* screen = new wchar_t[nScreenWidth * nScreenHeight];for (int i = 0; i < nScreenWidth * nScreenHeight; i++) screen[i] = L' ';HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);SetConsoleActiveScreenBuffer(hConsole);// 用于记录写入到控制台屏幕缓冲区的字节数DWORD dwBytesWritten = 0;tetromino[0].append(L"..X...X...X...X."); // Tetronimos 4x4tetromino[1].append(L"..X..XX...X.....");tetromino[2].append(L".....XX..XX.....");tetromino[3].append(L"..X..XX..X......");tetromino[4].append(L".X...XX...X.....");tetromino[5].append(L".X...X...XX.....");tetromino[6].append(L"..X...X..XX.....");pField = new unsigned char[nFieldWidth * nFieldHeight]; // Create play field bufferfor (int x = 0; x < nFieldWidth; x++) // Board Boundaryfor (int y = 0; y < nFieldHeight; y++)pField[y * nFieldWidth + x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeight - 1) ? 9 : 0;// Game Logicbool bKey[4];int nCurrentPiece = 0;int nCurrentRotation = 0;int nCurrentX = nFieldWidth / 2;int nCurrentY = 0;int nSpeed = 20;			// 控制方块下落速度的变量,初始化为20int nSpeedCount = 0;		// 一个计数器,用于记录方块下落的帧数,初始化为0bool bForceDown = false;	// 用于标记是否强制方块向下移动,初始化为falsebool bRotateHold = true;	// 是否连续旋转,表明用户是否按住了旋转按钮int nPieceCount = 0;int nScore = 0;vector<int> vLines;bool bGameOver = false;// 绘制游戏界面并更新显示while (!bGameOver) // Main Loop{// Timing =======================// 将当前线程暂停执行,等待50毫秒,以控制游戏帧率this_thread::sleep_for(50ms); // Small Step = 1 Game TicknSpeedCount++;				  // 将计数器nSpeedCounter的值加1,表示经过了一个帧bForceDown = (nSpeedCount == nSpeed);	// 判断计数器是否等于设定数量,如果相等,则将bForceDown设置为true,表示需要强制方块向下移动// Input ========================for (int k = 0; k < 4; k++)								// R   L   D Z// 判断了指定键码对应的按键是否处于按下状态。如果按键被按下,则结果为真,否则为假。bKey[k] = (0x8000 & GetAsyncKeyState((unsigned char)("\x27\x25\x28Z"[k]))) != 0;// Game Logic ===================// 游戏逻辑// Handle player movement// 处理玩家的移动// 按下右键 rightnCurrentX += (bKey[0] && DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX + 1, nCurrentY)) ? 1 : 0;// 按下左键 leftnCurrentX -= (bKey[1] && DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX - 1, nCurrentY)) ? 1 : 0;// 按下下键 downnCurrentY += (bKey[2] && DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1)) ? 1 : 0;// Rotate, but latch to stop wild spinning// 按下Z键,旋转if (bKey[3])	// 按下Z键{nCurrentRotation += (bRotateHold && DoesPieceFit(nCurrentPiece, nCurrentRotation + 1, nCurrentX, nCurrentY)) ? 1 : 0;bRotateHold = false;}elsebRotateHold = true;	// 无法连续旋转// Force the piece down the playfield if it's time// 如果是时候,将棋子强行推向游戏场地if (bForceDown){// Update difficulty every 50 pieces// 每 50 件更新一次难度nSpeedCount = 0;nPieceCount++;if (nPieceCount % 50 == 0)if (nSpeed >= 10) nSpeed--;// Test if piece can be moved down// 测试是否可以向下移动if (DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY + 1))nCurrentY++; // It can, so do it!else{// It can't! Lock the piece in place// 它不能!将工件锁定到位for (int px = 0; px < 4; px++)for (int py = 0; py < 4; py++)if (tetromino[nCurrentPiece][Rotate(px, py, nCurrentRotation)] != L'.')pField[(nCurrentY + py) * nFieldWidth + (nCurrentX + px)] = nCurrentPiece + 1;// Check for linesfor (int py = 0; py < 4; py++)if (nCurrentY + py < nFieldHeight - 1){bool bLine = true;for (int px = 1; px < nFieldWidth - 1; px++)bLine &= (pField[(nCurrentY + py) * nFieldWidth + px]) != 0;if (bLine){// Remove Line, set to =for (int px = 1; px < nFieldWidth - 1; px++)pField[(nCurrentY + py) * nFieldWidth + px] = 8;vLines.push_back(nCurrentY + py);}}nScore += 25;if (!vLines.empty())	nScore += (1 << vLines.size()) * 100;// Pick New PiecenCurrentX = nFieldWidth / 2;nCurrentY = 0;nCurrentRotation = 0;nCurrentPiece = rand() % 7;// If piece does not fit straight away, game over!bGameOver = !DoesPieceFit(nCurrentPiece, nCurrentRotation, nCurrentX, nCurrentY);}}// Display ======================// Draw Field// nFieldWidth游戏界面宽度,nFieldHeight游戏界面高度;注意与屏幕宽度和高度区分// nScreenWidth屏幕宽度,nScreenHeight屏幕高度for (int x = 0; x < nFieldWidth; x++)for (int y = 0; y < nFieldHeight; y++)screen[(y + 2) * nScreenWidth + (x + 2)] = L" ABCDEFG=#"[pField[y * nFieldWidth + x]];// Draw Current Piece// 绘制当前方块for (int px = 0; px < 4; px++)	// 循环遍历方块的水平位置for (int py = 0; py < 4; py++)	// 循环遍历方块的垂直位置if (tetromino[nCurrentPiece][Rotate(px, py, nCurrentRotation)] != L'.')	// 检查方块是否存在于当前位置// 注意:65代表大写的Ascreen[(nCurrentY + py + 2) * nScreenWidth + (nCurrentX + px + 2)] = nCurrentPiece + 65;	// 将方块绘制到屏幕上(加上适当的偏移量)// Draw Scoreswprintf_s(&screen[2 * nScreenWidth + nFieldWidth + 6], 16, L"SCORE: %8d", nScore);// Animate Line Completionif (!vLines.empty()){// Display Frame (cheekily to draw lines)WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, { 0,0 }, &dwBytesWritten);this_thread::sleep_for(400ms); // Delay a bitfor (auto& v : vLines)for (int px = 1; px < nFieldWidth - 1; px++){for (int py = v; py > 0; py--)pField[py * nFieldWidth + px] = pField[(py - 1) * nFieldWidth + px];pField[px] = 0;}vLines.clear();}// Display Frame// 将字符写入控制台的输出缓冲区// 将 screen 数组中的字符数据写入到控制台的输出缓冲区中,并显示在控制台窗口上WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, { 0,0 }, &dwBytesWritten);}// Oh Dear// 游戏结束 查看分数CloseHandle(hConsole);cout << "Game Over!! Score:" << nScore << endl;system("pause");return 0;
}

VS2022中运行上述代码:

C++控制台版俄罗斯方块
其中有一点需要注意:窗口大小的问题,git clone源码100%相同,但输出不一样。

窗口大小的问题。
Windows11中Win+R键打开cmd命令行窗口,鼠标移动到窗口上方白色横条处,右键 - 设置 - 启动 - 启动大小👇改成下面这个,列改成80,行改成30,如下图所示:
在这里插入图片描述
对应代码中的:

int nScreenWidth = 80;			// Console Screen Size X (columns)
int nScreenHeight = 30;			// Console Screen Size Y (rows)

参考资料

  • 【百万好评】国外技术大神C++游戏编程实战教程,油管580W收藏,新手10小时入门,并快速达到游戏开发能力(中英字幕) B站
  • C++实现俄罗斯方块(源码+详解)
  • OneLoneCoder_Tetris.cpp
  • 如何做一个俄罗斯方块4:形状碰撞检测(上)

这篇关于C++实现俄罗斯方块(Windows控制台版)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1148358

相关文章

Spring Security+JWT如何实现前后端分离权限控制

《SpringSecurity+JWT如何实现前后端分离权限控制》本篇将手把手教你用SpringSecurity+JWT搭建一套完整的登录认证与权限控制体系,具有很好的参考价值,希望对大家... 目录Spring Security+JWT实现前后端分离权限控制实战一、为什么要用 JWT?二、JWT 基本结构

Java实现优雅日期处理的方案详解

《Java实现优雅日期处理的方案详解》在我们的日常工作中,需要经常处理各种格式,各种类似的的日期或者时间,下面我们就来看看如何使用java处理这样的日期问题吧,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言一、日期的坑1.1 日期格式化陷阱1.2 时区转换二、优雅方案的进阶之路2.1 线程安全重构2

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络

使用Python实现图像LBP特征提取的操作方法

《使用Python实现图像LBP特征提取的操作方法》LBP特征叫做局部二值模式,常用于纹理特征提取,并在纹理分类中具有较强的区分能力,本文给大家介绍了如何使用Python实现图像LBP特征提取的操作方... 目录一、LBP特征介绍二、LBP特征描述三、一些改进版本的LBP1.圆形LBP算子2.旋转不变的LB

Redis消息队列实现异步秒杀功能

《Redis消息队列实现异步秒杀功能》在高并发场景下,为了提高秒杀业务的性能,可将部分工作交给Redis处理,并通过异步方式执行,Redis提供了多种数据结构来实现消息队列,总结三种,本文详细介绍Re... 目录1 Redis消息队列1.1 List 结构1.2 Pub/Sub 模式1.3 Stream 结

C# Where 泛型约束的实现

《C#Where泛型约束的实现》本文主要介绍了C#Where泛型约束的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录使用的对象约束分类where T : structwhere T : classwhere T : ne

将Java程序打包成EXE文件的实现方式

《将Java程序打包成EXE文件的实现方式》:本文主要介绍将Java程序打包成EXE文件的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录如何将Java程序编程打包成EXE文件1.准备Java程序2.生成JAR包3.选择并安装打包工具4.配置Launch4

Windows Docker端口占用错误及解决方案总结

《WindowsDocker端口占用错误及解决方案总结》在Windows环境下使用Docker容器时,端口占用错误是开发和运维中常见且棘手的问题,本文将深入剖析该问题的成因,介绍如何通过查看端口分配... 目录引言Windows docker 端口占用错误及解决方案汇总端口冲突形成原因解析诊断当前端口情况解

MySQL索引的优化之LIKE模糊查询功能实现

《MySQL索引的优化之LIKE模糊查询功能实现》:本文主要介绍MySQL索引的优化之LIKE模糊查询功能实现,本文通过示例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前缀匹配优化二、后缀匹配优化三、中间匹配优化四、覆盖索引优化五、减少查询范围六、避免通配符开头七、使用外部搜索引擎八、分

Python实现特殊字符判断并去掉非字母和数字的特殊字符

《Python实现特殊字符判断并去掉非字母和数字的特殊字符》在Python中,可以通过多种方法来判断字符串中是否包含非字母、数字的特殊字符,并将这些特殊字符去掉,本文为大家整理了一些常用的,希望对大家... 目录1. 使用正则表达式判断字符串中是否包含特殊字符去掉字符串中的特殊字符2. 使用 str.isa