猜数字(Bulls and Cows)C语言实现

C/C++ 2014年08月19日 ,

猜数字(又称Bulls and cows)是一种大概于20世纪中期兴起于英国的益智类小游戏。一般由两个人玩,也可以由一个人和电脑玩,在纸上、在网上都可以玩。这种游戏规则简单,但可以考验人的严谨和耐心。详细要求请GOOGLE。

猜数字游戏

计算机随机生成没有重复的n个数,用户从键盘输入猜测的数。每猜一次,电脑给出提示信息。如果用户输入的数跟计算机生成的数,数值和位置都完全相等,则胜出。

基本功能要求

  1. 1. 随机生成没有重复的4个数。(每个数字在0-9范围内)。
  2. 2. 用户从键盘输入4个不重复的数,程序能对用户输入的数与随机生成的数进行匹配,并给出提示信息:有多少数字答对,有多少数字位置正确。
  3. 3. 控制用户的尝试次数为10次。
  4. 4. 计算、输出并保存用户的得分,计分规则:总分是100分,每失败一次扣10分。
  5. 5. 有操作菜单,能根据不同选择运行不同功能:1:开始游戏!2:查看上次成绩!9:输 出帮助信息!0:退出程序!

扩展功能要求

  1.  1. 对用户输入的数字进行检查,如果用户输入重复的数,给出提示,要求重新输入。
  2. 2. 能对游戏进行设置:在操作菜单中增加相应的选项:“3:系统设置”。
    1.  (1) 修改要猜的数字的个数n,根据修改后的n值,计算机可随机生成n个数,用户 进行n个数的猜测游戏。
    2.  (2) 修改可以尝试的次数。
  3.  3. 若游戏胜出且成绩在前五名,可输入并记录对应的用户姓名,并添加到积分榜中。操作 菜单中相应选项改为“2:积分榜!”,用于把积分榜中保存的前五名成绩及用户姓名显示出来。
  4.  4. 能对积分榜的成绩进行排序和输出。

猜数字游戏C语言实现

问题分析

首先根据需求分析,完成流程图及数据结构规划。

guessnum流程图

具体编码

由于程序比较简单,程序分为如下几个文件:

  1. 1.<main.c>主程序及总体逻辑的实现。
  2. 2.<guess.h>数据结构定义及模块定义。
  3. 3.<guess.c>模块具体实现。
  4. 4.<Makefile>(可选)。

<main.c>

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "guess.h"

/* main.c - guess number
 * Copyright (C) 2013-2014 FURZOOM.COM
 *
 * @file      main.c
 * @brief     Guess number
 * @details   Guess number
 * @author    Yan Ma
 * @version   1.0
 * @date      2014-08
 * @history
 * @website  http://furzoom.com/
 */

#define GAMECOUNT	5			// max game playing count
#define MAXGUESSCOUNT	10	// max guess count
#define NUMCOUNT	10			// number count

int main()
{
	int curScore;	// current score
//	int scoreRecord[GAMECOUNT];	// score history
	int guessCount;			// current guess count
	int selectItem;				// menu selected index
	int guessNum[NUMCOUNT];	// generated number
	int inputNum[NUMCOUNT];		// user input number
	int repeatCount;			// count number is right
	int samePos;				// number and position if right
	int i;
	int guessNumCount;		// guess number count
	int maxGuessCount;		// max guess count
	int isWin;					// win or not
	gamemeta scoreRecord[GAMECOUNT];	// score list

	// initialize scoreRecord to -1
	for(i = 0; i<GAMECOUNT; ++i ) 	{ 		scoreRecord[i].score = -1; 		scoreRecord[i].name[0] = '\0'; 	} 	// initialize guessNumCount 	guessNumCount = 4; 	// initialize maxGuessCount 	maxGuessCount = 10; 	// main loop 	while(0 != (selectItem = menu())) 	{ 		switch(selectItem) 		{ 		case 1:			// start game 			curScore = 0; 			selectItem = 0; 			guessCount = 0; 			isWin = 0; 			generateNum( guessNum, guessNumCount); 			getsNum(inputNum, guessNumCount); 			while( !(isWin = constrastNum(guessNum,inputNum, guessNumCount, &repeatCount, &samePos))) 			{ 				guessCount ++; 				if(guessCount >= maxGuessCount)
				{
					break;
				}
				printf("%d in, %d right pos\n", repeatCount, samePos);
				getsNum(inputNum, guessNumCount);
			}
			curScore = calculateScore(guessCount, isWin);
			if(!isWin)
			{
				puts("YOU FAILED!\n");
			}
			else
			{
				printf("CONGRADULATIONS, YOU WIN!\nSCORE:%d\n",curScore);
			}
			storeScore(scoreRecord, GAMECOUNT, curScore);
			break;
		case 2:			// socre list
			printScoreRecord(scoreRecord, GAMECOUNT);
			break;
		case 3:			// game setting
			while(0 != (selectItem = gameSettingMenu()))
			{
				switch(selectItem)
				{
				case 1:
					gsGuessNumCount(&guessNumCount);
					break;
				case 2:
					gsGuessingCount(&maxGuessCount);
					break;
				default:
					break;
				}
			}
			break;
		case 9:			// game help
			gameHelp();
			break;
		default:
			break;
		}
	}
	return 0;
}

<guess.h>

#ifndef _GUESS_H_
#define _GUESS_H_

/* guess.h - guess number header file
 * Copyright (C) 2013-2014 FURZOOM.COM
 *
 * @file      guess.h
 * @brief     Guess number
 * @details   Guess number
 * @author    Yan Ma
 * @version   1.0
 * @date      2014-08
 * @history
 * @website  http://furzoom.com/
 */

typedef struct GAMEMETA{
	int score;
	char name[20];
}gamemeta, *pGamemeta;

// print menu and return selection item index
int menu(void);

// generate n different numbers(0~9)
int generateNum(int *arrNum, int n);

// get n numbers from input
int getsNum(int *arrNum, int n);

// contrast numbers
int constrastNum(int *arrSrc, int *arrDest, int n, int *equalCount, int *samePosCount);

// calculate score
int calculateScore(int guessCount, int bWin );

// store score
void storeScore(gamemeta *arrScore, int n, int score);

// print score record
void printScoreRecord(gamemeta *arrScore, int n);

// game help
void gameHelp();

// game setting menu
int gameSettingMenu();

// game setting : guess number count
void gsGuessNumCount(int *guessNumCount);

// game setting : guessing count
void gsGuessingCount(int *guessCount);

#endif	// end _GUESS_H_

<guess.c>

#include "guess.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

/* guess.c - guess number
 * Copyright (C) 2013-2014 FURZOOM.COM
 *
 * @file      guess.c
 * @brief     Guess number
 * @details   Guess number
 * @author    Yan Ma
 * @version   1.0
 * @date      2014-08
 * @history
 * @website  http://furzoom.com/
 */

// print menu and return selection item index
int menu(void)
{
	int index;
	while(1)
	{
		puts("Welcome to GUESS NUMBER GAME!");
		puts("+++++++++++++++++++++++++++");
		puts("+ 1   Start game.         +");
		puts("+ 2   Score list.         +");
		puts("+ 3   Settings.           +");
		puts("+ 9   Help.               +");
		puts("+ 0   Quit.               +");
		puts("+++++++++++++++++++++++++++");
		puts("Input your selection: (1, 2, 3, 9 or 0)");
		scanf("%d", &index);
		if(index == 0 || index == 1 || index == 2 || index == 3 || index == 9)
		{
			return index;
		}
		else
		{
			puts("You have selection is wrong, please select again!");
		}
	}
}

// generate 4 different numbers (0~9)
int generateNum(int *arrNum, int n)
{
	int i, j, num;
	srand(time(0));
	if(n >= 10 || n<=0)
	{
		return 0;
	}

	i = 0;
	while( i != n)
	{
		num = rand() % 10;
		for(j = 0; j < i; ++j)
		{
			if(arrNum[j] == num)
			{
				break;
			}
		}
		if( j == i)
		{
			arrNum[i++] = num;
		}
	}
	return 1;
}

// get n numbers from input
int getsNum(int *arrNum, int n)
{
	int i, j;
	int num;

	for(i = 0;i < n;++i )
	{
		arrNum[i] = -1;
	}

	printf("Input %d numbers:", n);
	i = 0;
	while(i < n) 	{ 		scanf("%d", &num); 		if(num >=0 && num <= 9 ) 		{ 			for(j = i; j > 0; --j)
			{
				if(num == arrNum[j])
				{
					puts("You have input repeated numbers, please input again:");
					break;
				}
			}
			if(j == 0)
			{
				arrNum[i++] = num;
			}
		}
		else
		{
			puts("Input numbers range 0 to 9, please input again:");
			i = 0;
		}
	}
	return 1;
}

// constrast numbers
int constrastNum(int *arrSrc, int *arrDest, int n, int *equalCount, int *samePosCount)
{
	int i,j;
	*equalCount = 0;
	*samePosCount = 0;
	for(i=0;i<n;++i)
	{
		if(arrSrc[i] == arrDest[i])
		{
			(*samePosCount)++;
		}
		for(j = 0;j<n;++j) 		{ 			if(arrSrc[i] == arrDest[j]) 			{ 				(*equalCount)++; 			} 		} 	} 	if(*samePosCount == n) 	{ 		return 1; 	} 	else 	{ 		return 0; 	} } // calculate score int calculateScore(int guessCount,  int bWin) { 	if(bWin) 	{ 		return (100 - guessCount * 10) > 0 ? 100 - guessCount * 10 : 0;
	}
	else
	{
		return 0;
	}
}

// store score
void storeScore(gamemeta *arrScore, int n, int score)
{
	int i, j;
	char name[255];
	for(i = 0;i<n;++i)
	{
		if(arrScore[i].score < score) 		{ 			for(j = n - 1; j > i; --j)
			{
				arrScore[j].score= arrScore[j-1].score;
				strcpy(arrScore[j].name, arrScore[j-1].name);
			}
			arrScore[i].score = score;
			printf("Input your name:");
			scanf("%s", arrScore[i].name);
			break;
		}
	}
}

// pirnt score record
void printScoreRecord(gamemeta *arrScore, int n)
{
	int i;
	puts("+++++++++++++++++++++++++++");
	puts("+         SCORE           +");
	puts("+++++++++++++++++++++++++++");
	for(i = 0;i<n;++i) 	{ 		if(arrScore[i].score >=0)
		{
			printf("+ %d. %5d%16s+\n", i+1, arrScore[i].score, arrScore[i].name);
		}
		else
		{
			break;
		}
	}
	if(i == 0)
	{
		puts("+        NO SCORE         +");
	}
	puts("+++++++++++++++++++++++++++");
}

// game help
void gameHelp()
{
	puts("+++++++++++++++++++++++++++");
	puts("+        GAME HELP        +");
	puts("+++++++++++++++++++++++++++");
	puts("+Secret number: 4271      +");
	puts("+Opponent's try: 1234     +");
	puts("+Answer: 1 in, 2 right pos+");
	puts("+++++++++++++++++++++++++++");
}

// game settings
void gsGuessNumCount(int *guessNumCount)
{
	int count;
	printf("The current guess number count is %d.\n", *guessNumCount);
	printf("Please input the guess number count(1~9):");
	scanf("%d", &count);
	if(count >= 1 && count <= 9) 	{ 		*guessNumCount = count; 	} } // game setting menu int gameSettingMenu() { 	int num; 	while(1) 	{ 		puts("+++++++++++++++++++++++++++"); 		puts("+      GAME SETTINGS      +"); 		puts("+++++++++++++++++++++++++++"); 		puts("+ 1   Guess numbers count.+"); 		puts("+ 2   Count of guessing.  +"); 		puts("+ 0   Return to main menu.+"); 		puts("+++++++++++++++++++++++++++"); 		printf("Input you selection(1, 2 or 0):"); 		scanf("%d", &num); 		if(num == 1 || num == 2 || num == 0) 		{ 			return num; 		} 		else 		{ 			puts("You have selection is wrong, please select again!"); 		} 	} } // game setting : guessing count void gsGuessingCount(int *guessCount) { 	int count; 	printf("The current guessing count is %d.\n", *guessCount); 	printf("Please input the guess number count(1~20):"); 	scanf("%d", &count); 	if(count >= 1 && count <= 20)
	{
		*guessCount = count;
	}
}

<Makefile>

# ---------------------------------------------
# This file is for project guess number
# By Yan Ma@2014-08
# ---------------------------------------------
# macros
# Obj is for objects
Obj = main.o guess.o
c = gcc
# c = cc
# ---------------------------------------------
# make rule
guessnum.exe : ${Obj}
	${c} -o guessnum.exe ${Obj}
main.o : guess.h
	${c} -c -o main.o main.c
guess.o : guess.h
	${c} -c -o guess.o guess.c
.PHONY : clean
clean :
	del guessnum.exe ${Obj}
#	rm guessnum ${Obj}

运行过程

猜数字主界面

猜数字主界面

猜数字游戏过程

猜数字游戏过程

猜数字积分榜

猜数字积分榜

至此,要求的内容已全部实现。http://furzoom.com/bulls-and-cows/

这个游戏太费脑子了,自己做完都不爱玩。

有Bug请留言,谢谢!

如无特别说明,本站文章皆为原创,若要转载,务必请注明以下原文信息:
日志标题:《猜数字(Bulls and Cows)C语言实现》
日志链接:http://furzoom.com/bulls-and-cows/
博客名称:枫竹梦

【上一篇】
【下一篇】

发表评论

插入图片

NOTICE1:请申请gravatar头像,没有头像的评论可能不会被回复!

回到顶部