闲暇之余,写了一个小游戏,因为以前用不同语言写过好几个版本的贪吃蛇,所以这次轻车熟路,只用了100行代码
实现语言:c
实现原理:链表
代码:
#include<stdio.h>
#include<windows.h>
#include<commctrl.h>
#include<math.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>
#include<time.h>
int head_x, head_y,food_x,food_y,length,max_length;
char ch;//动作
HWND H = (HWND)0x00010146;
HWND hwnd = FindWindowEx(H, NULL, "SysListView32", "FolderView");
typedef struct node {
int i;//图标序号
int x;//图标横坐标
int y;//图标纵坐标
struct node *pNext;
}Node,*pNode;
pNode CreateList();//创建链表
void Insert_Node(pNode ,int,int,int);//插入节点
void Move(pNode,int,int);//移动蛇身
void MakeFood(); //产生食物
bool Judge(pNode);//判断
void main() {
//初始化
max_length = ListView_GetItemCount(hwnd);
printf("%d", max_length);
for (int i = 0; i < max_length; i++)
{
SendMessage(hwnd, LVM_SETITEMPOSITION, i, MAKELPARAM(100000, 100000));
}
pNode pHead = CreateList();
Insert_Node(pHead, 0, 800, 800);
length = 1;
SendMessage(hwnd, LVM_SETITEMPOSITION, pHead->pNext->i, MAKELPARAM(pHead->pNext->x, pHead->pNext->y));
MakeFood();
//进入游戏
while (1) {
if (_kbhit()) {
ch = _getch();
}
head_x = pHead->pNext->x;
head_y = pHead->pNext->y;
if (ch == 'w') {
head_y -= 50;
}
if (ch == 'a') {
head_x -= 50;
}
if (ch == 'd') {
head_x += 50;
}
if (ch == 's') {
head_y += 50;
}
bool bo = Judge(pHead);
Move(pHead, head_x, head_y);
SendMessage(hwnd, LVM_SETITEMPOSITION, pHead->pNext->i, MAKELPARAM(pHead->pNext->x,pHead->pNext->y));
if (bo) {
MakeFood();
SendMessage(hwnd, LVM_SETITEMPOSITION, pHead->pNext->i, MAKELPARAM(pHead->pNext->x, pHead->pNext->y));
}
Sleep(200);
}
system("pause");
}
pNode CreateList() {
pNode pHead = (pNode)malloc(sizeof(Node));
pHead->pNext = NULL;
return pHead;
}
//头插法
void Insert_Node(pNode pHead, int i, int x, int y) {
pNode pNew = (pNode)malloc(sizeof(Node));
pNew->i = i;
pNew->x = x;
pNew->y = y;
pNode p = pHead;
pNew->pNext = p->pNext;
p->pNext = pNew;
}
void Move(pNode pHead, int x, int y) {
pNode p = pHead;
while (p->pNext != NULL) {
p = p->pNext;
}
Insert_Node(pHead,p->i,x,y);
p = pHead;
while (p->pNext->pNext!=NULL) {
p = p->pNext;
}
p->pNext = NULL;
}
void MakeFood() {
srand((unsigned)time(0));
food_x = (rand() % 18 + 1) * 100;
food_y = (rand() % 9 + 1) * 100;
SendMessage(hwnd, LVM_SETITEMPOSITION, length, MAKELPARAM(food_x,food_y));
}
bool Judge(pNode p) {
if (head_x == food_x && head_y == food_y ) {
Insert_Node(p,length, food_x, food_y);
length += 1;
return true;
}
return false;
}
蛇的身体是由链表组成,食物是随机产生,身体成长用的是链表的头插法。
这两句代码是获取桌面图标的句柄
HWND H = (HWND)0x00010146;
HWND hwnd = FindWindowEx(H, NULL, "SysListView32", "FolderView");
因为 win10的桌面窗口句柄没有窗口标题,只靠类名无法确定,所以用了vs自带的工具spy++强制定位转型
还有一点需要注意的是 要取消桌面的网格布局和自动排序,他会影响图标的控制和移动
然后设置自动排序就能恢复原状
感兴趣的小伙可以联系我交流一下