圖標貪喫蛇

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章