C++ Console WASD Block Game: Reach the Target and Win!
The following is a C++ code that implements a simple game where the player moves a block on the screen using the WASD keys. The objective is to reach a randomly generated target position. If the player reaches the target position, the target position changes and the player's score increases. If the player hits the boundary or reaches the maximum score, the game ends.
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <cstdlib>
#include <ctime>
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void color(int colorCode)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colorCode);
}
int main()
{
srand(time(0));
const int maxScore = 440;
const int targetSymbol = '*';
int currentScore = 0;
int blockX = 10;
int blockY = 10;
int targetX = 0;
int targetY = 0;
while (true)
{
// Clear screen
system("cls");
// Draw block
gotoxy(blockX, blockY);
color(14);
std::cout << "X";
// Draw target
gotoxy(targetX, targetY);
color(12);
std::cout << targetSymbol;
// Draw current score
gotoxy(26, 3);
color(20);
std::cout << "Score: " << currentScore;
// Check if game over
if (blockX == targetX && blockY == targetY)
{
currentScore++;
// Generate new target position
targetX = rand() % 20 + 1;
targetY = rand() % 20 + 1;
// Check if maximum score reached
if (currentScore > maxScore)
{
gotoxy(24, 5);
color(30);
std::cout << "You won!";
break;
}
}
// Check if block hit boundary
if (blockX == 0 || blockX == 21 || blockY == 0 || blockY == 21)
{
gotoxy(10, 10);
color(30);
std::cout << "Game over!";
break;
}
// Move block
if (_kbhit())
{
char key = _getch();
if (key == 'w' && blockY > 0)
blockY--;
else if (key == 's' && blockY < 21)
blockY++;
else if (key == 'a' && blockX > 0)
blockX--;
else if (key == 'd' && blockX < 21)
blockX++;
}
// Delay
Sleep(200);
}
// Wait for user input before exiting
_getch();
return 0;
}
Note: This code uses Windows-specific functions for console manipulation (getch(), gotoxy(), color(), Sleep()) and may not work on other platforms without modification.
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qFmY 著作权归作者所有。请勿转载和采集!