#include "stdafx.h"
#include<stdio.h>
#include<windows.h>
#include<commctrl.h>
#include<math.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>
#include<time.h>
char ch;//动作
int head_x, head_y, food_x, food_y, length, max_length;
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); //判断
int _tmain(int argc, char* argv[])
{
//初始化
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");
return 0;
}
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;
}