程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C/C++仿華容道小游戲

C/C++仿華容道小游戲

編輯:關於C++

C/C++仿華容道小游戲。本站提示廣大學習愛好者:(C/C++仿華容道小游戲)文章只能為提供參考,不一定能成為您想要的結果。以下是C/C++仿華容道小游戲正文


本文實例引見了C++模擬華容道小游戲完成代碼,分享給年夜家供年夜家參考,詳細內容以下

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
 
#define maxnum 16
#define colnum 4
 
bool numexists(int *numbers, int length, int num);
int getnumber(int **numbers, int randIndex, int *length);
int* initnumbers(void);
void swap(int **a, int **b);
 
int main(int argc, char *argv[])
{
  int *tempnumbers = initnumbers();
  int *randnumbers = initnumbers();
  int **numbers;
  numbers = malloc(maxnum * sizeof(int*));
  //bool a = numexists(numbers, 16, 3);
  //printf("a=%d\n", a);
 
  int length = maxnum;
  srand((unsigned)time(NULL));
  for (int i = 0; i < maxnum; i++)
  {
    int temp = getnumber(&tempnumbers, rand() % length, &length);
    randnumbers[i] = temp;
    numbers[temp] = &randnumbers[i];
    //printf("%d%c", temp, (i + 1) % colnum == 0?'\n':'\t');
  }
  if (tempnumbers != NULL)
    free(tempnumbers);
  while (true)
  {
    system("clear");
    for (int i = 0; i < maxnum; i++)
      printf("%d%c", randnumbers[i], (i + 1) % colnum == 0?'\n':'\t');
 
    printf("move number/ invalid num==exit: ");
    int i;
    if (!scanf("%d", &i))
    {
      printf("game over\n");
      break;
    }
    if (i >= maxnum || i <0)
    {
      printf("sorry, i can't find %d\n", i);
      break;
    }
    unsigned char sign = abs(numbers[i] - numbers[0]);
    switch (sign)
    {
      case 1:
      case 4: swap(&numbers[0], &numbers[i]); break; 
    }
 
  }
  if (numbers != NULL)
    free(numbers);
  if (randnumbers != NULL)
    free(randnumbers);
}
 
void swap(int **a, int **b)
{
  int *templocation = *a;
  int tempvalue = **a;
  **a = **b;
  **b = tempvalue;
  *a = *b;
  *b = templocation;
}
 
int* initnumbers(void)
{
  int *numbers = malloc(maxnum * sizeof(int));
  for (int i = 0; i < maxnum; i++)
    numbers[i] = i;
  return numbers;
}
 
int getnumber(int **numbers, int randIndex, int *length)
{
  int result = (*numbers)[randIndex];
  (*numbers)[randIndex] = (*numbers)[--(*length)];
  int *temp = realloc(*numbers, (*length) * sizeof(int));
  *numbers = temp;
  return result;
}
 
bool _numexists(int *numbers, int start, int end, int num)
{
  printf("start: %d, end: %d, num: %d\n", start, end, num);
  if (start == end)
    return numbers[start] == num;
  else
  {
    int middle = (start+end) / 2;
    if (numbers[middle] == num)
      return true;
    else if (numbers[middle] > num)
      return _numexists(numbers, start, middle-1, num);
    else
      return _numexists(numbers, middle+1, end, num);
  }
}
bool numexists(int *numbers, int length, int num)
{
  return _numexists(numbers, 0, length-1, num);  
}

願望本文對年夜家進修C++法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved