编写一个贪吃蛇的C语言程序,要求使用定时器SetTimer和线程函数的控制台版本
时间: 2024-02-15 13:05:59 浏览: 97
用c语言编写的贪吃蛇程序
好的,以下是使用定时器和线程函数实现的贪吃蛇控制台游戏的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#define width 20
#define height 20
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum Direction {STOP = 0, LEFT, RIGHT, UP, DOWN};
Direction dir;
bool gameOver;
void Setup() {
srand(time(NULL));
gameOver = false;
dir = STOP;
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw() {
system("cls");
for (int i = 0; i < width+2; i++)
printf("#");
printf("\n");
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (j == 0)
printf("#");
if (i == y && j == x)
printf("O");
else if (i == fruitY && j == fruitX)
printf("F");
else {
bool print = false;
for (int k = 0; k < nTail; k++) {
if (tailX[k] == j && tailY[k] == i) {
printf("o");
print = true;
}
}
if (!print)
printf(" ");
}
if (j == width - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < width+2; i++)
printf("#");
printf("\n");
printf("Score:%d\n", score);
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}
void Logic() {
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++) {
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x > width || x < 0 || y > height || y < 0)
gameOver = true;
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % width;
fruitY = rand() % height;
nTail++;
}
}
void TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) {
Draw();
Input();
Logic();
}
DWORD WINAPI ThreadProc(LPVOID lpParam) {
SetTimer(NULL, 0, 50, TimerProc);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
int main() {
Setup();
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
if (hThread) {
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
return 0;
}
```
上述代码使用了`SetTimer()`函数来创建定时器,并在定时器回调函数中进行游戏逻辑的更新和画面的绘制。同时,还使用了线程函数`CreateThread()`和`WaitForSingleObject()`函数来启动游戏线程和等待线程结束。
阅读全文