赞
踩
C++ graphics.h 贪吃蛇
- #include <graphics.h>
- #include <conio.h>
- #include <ctime>
-
- #define SIZE 20
-
- struct SnakeNode
- {
- int x;
- int y;
- struct SnakeNode* next;
- };
-
- SnakeNode* head;
- SnakeNode* food;
- int direction;
- int score;
-
- void InitGame()
- {
- initgraph(640, 480); // 初始化图形界面
- setbkcolor(WHITE);
- cleardevice();
-
- score = 0;
- direction = VK_RIGHT;
-
- SnakeNode* node = new SnakeNode;
- node->x = 0;
- node->y = 0;
- node->next = nullptr;
- head = node;
-
- food = new SnakeNode;
- srand(static_cast<unsigned>(time(nullptr)));
- food->x = rand() % (640 / SIZE) * SIZE;
- food->y = rand() % (480 / SIZE) * SIZE;
- food->next = nullptr;
- }
-
- void DrawSnake()
- {
- SnakeNode* node = head;
- while (node != nullptr)
- {
- setfillcolor(BLACK);
- solidrectangle(node->x, node->y, node->x + SIZE, node->y + SIZE);
- node = node->next;
- }
- }
-
- void DrawFood()
- {
- setfillcolor(RED);
- solidrectangle(food->x, food->y, food->x + SIZE, food->y + SIZE);
- }
-
- void UpdateSnake()
- {
- SnakeNode* node = new SnakeNode;
- node->x = head->x;
- node->y = head->y;
- node->next = head->next;
- head->next = node;
-
- if (direction == VK_RIGHT && head->x < 640 - SIZE)
- head->x += SIZE;
- else if (direction == VK_LEFT && head->x > 0)
- head->x -= SIZE;
- else if (direction == VK_DOWN && head->y < 480 - SIZE)
- head->y += SIZE;
- else if (direction == VK_UP && head->y > 0)
- head->y -= SIZE;
-
- if (head->x >= 640)
- head->x = 0;
- else if (head->x < 0)
- head->x = 640 - SIZE;
- if (head->y >= 480)
- head->y = 0;
- else if (head->y < 0)
- head->y = 480 - SIZE;
-
- if (head->x == food->x && head->y == food->y)
- {
- score++;
- delete food;
-
- food = new SnakeNode;
- food->x = rand() % (640 / SIZE) * SIZE;
- food->y = rand() % (480 / SIZE) * SIZE;
- food->next = nullptr;
- }
- else
- {
- SnakeNode* tail = head;
- while (tail->next->next != nullptr)
- tail = tail->next;
- delete tail->next;
- tail->next = nullptr;
- }
- }
-
- bool IsGameOver()
- {
- SnakeNode* node = head->next;
- while (node != nullptr)
- {
- if (head->x == node->x && head->y == node->y)
- return true;
- node = node->next;
- }
- return false;
- }
-
- int main()
- {
- InitGame();
-
- while (true)
- {
- if (_kbhit())
- {
- int key = _getch();
- if (key == 'D' || key == 'd' || key == VK_RIGHT)
- direction = VK_RIGHT;
- else if (key == 'A' || key == 'a' || key == VK_LEFT)
- direction = VK_LEFT;
- else if (key == 'S' || key == 's' || key == VK_DOWN)
- direction = VK_DOWN;
- else if (key == 'W' || key == 'w' || key == VK_UP)
- direction = VK_UP;
- }
-
- cleardevice();
- DrawSnake();
- DrawFood();
- UpdateSnake();
-
- if (IsGameOver())
- {
- MessageBox(nullptr, "Game Over!", "提示", MB_OK);
- break;
- }
-
- Sleep(200); // 控制游戏速度
- }
-
- closegraph();
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。