Hangman游戏设计
写在前面
最近,接了一个小单子,就是写一个hangman游戏,是用c语言写的,现在把它分享出来。
介绍hangman游戏
Hangman直译为“上吊的人”,是一个猜单词的双人游戏。由一个玩家想出一个单词或短语,另一个玩家猜该单词或短语中的每一个字母 。第一个人抽走单词或短语,只留下相应数量的空白与下划线。
出题玩家一般会画一个绞刑架,当猜词的玩家猜出了短语中存在的一个字母时,出题的玩家就将这个字母存在的所有位置都填上。如果玩家猜的字母不在单词或短语中,那么出题的玩家就给绞刑架上小人添上一笔,直到7笔过后,游戏结束。
设计分析
为了设计这个hangman游戏,首先我们要分析它的组成,这个游戏怎么去做。基于题目的要求,第一,我们需要取创建一个账户,用来选择用户名和密码,还需要记录log,所以这里需要创建一个用户结构体,用来保存用户的基本信息。
第二,题目要求hangman游戏中要给玩家提供Start a new game,Review their game history,Clear their game history,Logout这些选项,这里我们可以用if来确定用户的选择。第三,我们要确定单词的来源这个问题,
单词可以从.txt文件中来,也可以由另外一个玩家自己生成,所以我们需要定义一个读取文件的函数,同样也提供if来确定用户的选择;第四,我们需要设计hangman主程序,让用户提供猜测单词,如果猜测错误就画一个下划线,如果猜测正确,就用单词补充上下划线的地方。
最后,如果失败了,我们还需要画出绞刑台,提示用户它已经失败了,所以需要个void printGallows (int)
函数,其中int表示失败次数,超过七次,就画出完整小人,提示用户失败。
设计
- 用户结构体的设计
基于上述的分析,我们先要确定定义用户的结构体,确立了四个变量,username
,password
,Time
,logRecord
,分别用来存储用户名、密码、玩的次数、log记录,其结构体定义如下图所示
代码如下:
struct users
{
char username[NameLen];
char password[PassLen];
int Time; // Number of games played
char *logRecord;
}users[MaxUer];
- hangman游戏中提示语的设计
其次,我们在游戏中我们需要提示用户操作Start a new game,Review their game history,Clear their game history,Logout的选项,我们用一个函数来展示。其实,不知这一个提示,在游戏中有很多需要提示的地方,
最终,我们确定需要提供用户选择的函数:chooseUserMenu()
,showOperation()
,WordComefrom()
。
其各个函数结构图如下:
其chooseUserMenu()
具体函数如下:
void chooseUserMenu()
{
printf("=========================================================================\n");
printf("Hangman Game Assistant:\n This is the user login module, do you want to create a user, or select an existing user or Exit\n");
printf("1. I want to create a new user\n");
printf("2. I want to choose an existing user\n");
printf("3. Exit the hangman game\n");
}
其showOperation()
具体函数如下:
// Prompt game action
int showOperation()
{
int choose;
printf("Hangman Game Assistant: Please Choose your operation:\n");
printf("1.Start a new game\n");
printf("2.Review their game history\n");
printf("3.Clear their game history\n");
printf("4.Logout\n");
scanf("%d", &choose);
return choose;
}
其WordComefrom()
具体函数如下:
int WordComefrom()
{
int choose;
printf("Hangman Game Assistant:\n please Choose your words source:\n");
printf("1. from an existing '.txt' file;\n");
printf("2. from the keyboard from the other player.\n");
scanf("%d", &choose);
return choose;
}
-
从文本中获取单词的函数设计
对于这个函数,采用FILE
函数进行读取,其程序结构图如下所示:
-
hangman主程序的设置
进入hangman主程序,首先选定一个秘密数字,提示玩家猜测一个字母,如果这个字母在单词中,并且直到玩家猜出所有字母,那么取得胜利;否则,字母不在单词中,在绞刑台画上一笔,直到猜的次数超过七次,就游戏失败,最后跳到chooseUserMenu
界面,提示用户选择账户,如果登录成功可以再一次玩
其框架图如下:
-
程序
程序由两部分组成,一个是hangman.h
头文件,另一个是hangman_problem.c
文件
头文件代码如下:
//Import the required libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Define general traversal
#define MaxUer 500
#define NameLen 100
#define PassLen 100
#define WordSLen 100
#define NumWordS 10
// Used to determine the number of registered users
int userNum = 0;
// User structure type
struct users
{
char username[NameLen];
char password[PassLen];
int Time; // Number of games played
char *logRecord;
}users[MaxUer];
// Declare these functions
void Welcome_Interface(); // Action used to select a user
void chooseUserMenu(); // Action used to select a user
int showOperation(); // Select operation
void HangmanModel(struct users user);
int WordComefrom(); //Choose the source of the word
char charToLower(char c); // Convert the word to lowercase
void printGallows (int); // Draw the gallows
void getWord(char words[][WordSLen]); //Get the word from the file
int checkUsername(char* strs); // Verify that the user name is correct
int checkPassword(char* strs, int loc); // Check that the password is correct
// Welcome screen: Welcome to the Hangman game
void Welcome_Interface () {
printf("---------->Welcome to Hangman Game<----------\n");
printf("*****************************************\n");
printf("| | __ ___ __ \n");
printf("|__| | | |\\ | | |\\ /| | | |\\ |\n");
printf("| | |__| | \\ | | -- | \\ / | |__| | \\ |\n");
printf("| | | | | \\| |___| | \\/ | | | | \\|\n");
printf("*****************************************\n");
printf("Let's us play the game! Are you ready?\n");
printf("\n");
printf("Guess the word in less than 7 mistakes to win.\n");
printf("\n");
}
// Action used to select a user
void chooseUserMenu()
{
printf("=========================================================================\n");
printf("Hangman Game Assistant:\n This is the user login module, do you want to create a user, or select an existing user or Exit\n");
printf("1. I want to create a new user\n");
printf("2. I want to choose an existing user\n");
printf("3. Exit the hangman game\n");
}
// Choose the source of the word
int WordComefrom()
{
int choose;
printf("Hangman Game Assistant:\n please Choose your words source:\n");
printf("1. from an existing '.txt' file;\n");
printf("2. from the keyboard from the other player.\n");
scanf("%d", &choose);
return choose;
}
// Verify that the user name is correct
int checkUsername(char* strs)
{
char* username = strs;
for (int i = 0; i < userNum; i++) {
if (!strcmp(username, users[i].username)) {
return i;
}
}
return -1;
}
// Check that the password is correct
int checkPassword(char* strs, int loc)
{
char* password = strs;
if (!strcmp(password, users[loc].password)) {
return 1;
}
return 0;
}
// hangman code
void HangmanModel(struct users user) {
// The number increased
user.Time ++;
// The user account and password are displayed
printf("===Hangman Game Assistant:You have entered the Hangman game==\n");
printf("Hangman Game Assistant:You Username is %s\n",users->username);
printf("Hangman Game Assistant:You passward is %s\n", users->password);
//Recording Log Information
char *logs;
// Choose your actions
int choose = showOperation();
char HangmanWord[WordSLen]; // The length of the letter
// Select operation
if (choose == 1) {
// Determine the origin of the word
int from = WordComefrom();
// enumerate:Used to traverse
int enumerate = 0;
// If choose 1
if (from == 1) {
char wordList[NumWordS][WordSLen];
// Read a word from a document
getWord(wordList);
// Generate a statement at random
srand(time(NULL));
int Num = (int) (rand() % NumWordS);
for(int i = 0; i < strlen(wordList[Num]); i ++)
{
HangmanWord[i] = wordList[Num][i];
}
} else if (from == 2) { //If choose 2
int end = 1;
while (end) {
printf("Hangman Game Assistant:You need to type a word from the keyboard and let your partner guess, What is word?\n");
char inputWords[WordSLen];
scanf("%s", inputWords);
for (int i = 0; i < strlen(inputWords); i++) {
if (inputWords[i] >= 'A' && inputWords[i] <= 'Z' || inputWords[i] >= 'a' && inputWords[i] <= 'z')
HangmanWord[i] = inputWords[i];
else {
printf("Hangman Game Assistant:Invalid input. Try again !!!\n\n");
break;
}
}
// When the input passes, the while loop is exited
end = 0;
}
}
// the count of errors
int errors = 0;
// The word character that has been resolved
int correctList[(int) strlen(HangmanWord)];
// correctList:All initialized to zero
for (enumerate = 0; enumerate < strlen(HangmanWord); enumerate++) {
correctList[enumerate] = 0;
}
// checkArray: to check
int checkArray[(int) strlen(HangmanWord)];
// checkArray:All initialized to zero
for (enumerate = 0; enumerate < strlen(HangmanWord); enumerate++) {
checkArray[enumerate] = 0;
}
printf("Hangman Game Assistant:Let's Start!\n");
// initialized to zero
int solvedStatus = 0;
while ((solvedStatus == 0) && errors < 7) {
printf("=========================================\n");
printf("Hangman Game Assistant:The words contains %d letters.\n", (int) strlen(HangmanWord));
printf("Hangman Game Assistant:Enter a letter: ");
// used to enter the test
char letter[WordSLen];
scanf(" %s", &letter[0]);
printf("Hangman Game Assistant:You entered: %c\n", letter[0]);
int unsolvedLetters = 0;
for (enumerate = 0; enumerate < strlen(HangmanWord); enumerate++) {
if (charToLower(HangmanWord[enumerate]) == charToLower(letter[0])) {
checkArray[enumerate] = 1;
} else {
checkArray[enumerate] = 0;
unsolvedLetters++;
}
}
//If the validation is incorrect, the error increases
if (unsolvedLetters == strlen(HangmanWord)) {
errors++;
}
//Output the number of errors
printf("Hangman Game Assistant:Number of errors: %d\n", errors);
printGallows(errors);
// The initial call error is 0
enumerate = 0;
while (enumerate < strlen(HangmanWord)) {
if ((checkArray[enumerate] == 0) && (correctList[enumerate] == 0)) {
correctList[enumerate] = 0;
} else {
correctList[enumerate] = 1;
}
enumerate++;
}
for (enumerate = 0; enumerate < strlen(HangmanWord); enumerate++) {
checkArray[enumerate] = 0;
}
//The initial address has been resolved to 0
int solvedLetters = 0;
for (enumerate = 0; enumerate < strlen(HangmanWord); enumerate++) {
if (correctList[enumerate] == 1) {
solvedLetters++;
}
}
//If they are the same, that means the character is correct
if (solvedLetters == strlen(HangmanWord)) {
solvedStatus = 1;
}
for (enumerate = 0; enumerate < strlen(HangmanWord); enumerate++) {
if (correctList[enumerate] == 0) {
printf("_");
} else if (correctList[enumerate] == 1) {
printf("%c", HangmanWord[enumerate]);
}
}
printf("\n\n\n");
}
// If the number of times exceeds 7, a failure message is displayed
if (errors == 7) {
printf("Hangman Game Assistant:\nCorrect word was: %s\n", HangmanWord);
printf("Hangman Game Assistant:\nthe %d game result: YOU LOSE!\n\n",user.Time);
printf("*************************************************");
logs = "Hangman Game Assistant:\n Logs:YOU LOSE\n\n";
user.logRecord = logs;
} else {
printf("Hangman Game Assistant:the %d game result: YOU WIN!\n\n",user.Time);
logs = "Hangman Game Assistant:\n Logs:YOU WIN!\n\n";
user.logRecord = logs;
printf("*************************************************");
}
}
else if(choose == 2) {
printf("Hangman Game Assistant:\n YOU game log is showing here%s\n", user.logRecord);
}
else if (choose == 3) {
user.logRecord = "";
}
else if(choose == 4) {
printf("Hangman Game Assistant:\n this is your %d times that play the game, wish you come back soon!",user.Time);
printf("Hangman Game Assistant:\nYou are out of the game!!\n");
}
}
// get the word from file
void getWord(char words[][WordSLen]) {
FILE *file;
char Word[WordSLen];
char filename[] = "wordfromfile.txt";
file = fopen(filename, "r");
if (file == NULL) {
printf("Something Went Wrong!!!\n");
} else {
printf("read the file sucessful\n");
for (int i = 0; i <= NumWordS; i++) {
fgets(Word, 30, file);
strcpy(words[i], Word);
}
}
fclose(file);
}
// Lower case
char charToLower(char c)
{
if (c >= 'A' && c <= 'Z')
return c + 32;
}
// Prompt game action
int showOperation()
{
int choose;
printf("Hangman Game Assistant: Please Choose your operation:\n");
printf("1.Start a new game\n");
printf("2.Review their game history\n");
printf("3.Clear their game history\n");
printf("4.Logout\n");
scanf("%d", &choose);
return choose;
}
void printGallows (int error) {
switch (error) {
case 1:
{
printf("-----------------------------\n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf("-----------------------------\n");
break;
}
case 2:
{
printf("-----------------------------\n");
printf(" | | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf("-----------------------------\n");
break;
}
case 3:
{
printf("-----------------------------\n");
printf(" | | \n");
printf(" | O \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf("-----------------------------\n");
break;
}
case 4:
{
printf("-----------------------------\n");
printf(" | | \n");
printf(" | O \n");
printf(" | | \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf("-----------------------------\n");
break;
}
case 5:
{
printf("-----------------------------\n");
printf(" | | \n");
printf(" | O \n");
printf(" | -|- \n");
printf(" | \n");
printf(" | \n");
printf(" | \n");
printf("-----------------------------\n");
break;
}
case 6:
{
printf("-----------------------------\n");
printf(" | | \n");
printf(" | O \n");
printf(" | -|- \n");
printf(" | / \n");
printf(" | \n");
printf(" | \n");
printf("-----------------------------\n");
break;
}
case 7:
{
printf("-----------------------------\n");
printf(" | | \n");
printf(" | O \n");
printf(" | -|- \n");
printf(" | / \\ \n");
printf(" | \n");
printf(" | \n");
printf("-----------------------------\n");
break;
}
default:
break;
}
}
hangman_problem.c
主文件
#include "hangman.h"
int main()
{
// Welcome to the Hangman game
Welcome_Interface();
// Used to exit the program
int exit = 0;
while(!exit) {
chooseUserMenu();
// to choose the operation
int chs;
scanf("%d", &chs);
if(chs == 1)
{
printf("Hangman Game Assistant: \nplease input new username:\n");
scanf("%s", users[userNum].username);
printf("Hangman Game Assistant:\n please intput the password:\n");
scanf("%s", users[userNum].password);
userNum ++;
}
else if(chs == 2)
{
printf("Hangman Game Assistant: \nplease input username:\n");
char username[1000], password[1000];
scanf("%s", username);
int loc;
int end1 = 1;
int end2 = 1;
loc = checkUsername(username);
while(end1)
{
if(loc != -1)
{
end1 = 0;
printf("Hangman Game Assistant:\n please intput your password:\n");
scanf("%s", password);
while(end2)
{
if (checkPassword(password,loc)) {
end2 = 0;
break;
}
printf("Hangman Game Assistant: \npassword error, please intput your password again:\n");
scanf("%s", password);
}
printf("Hangman Game Assistant: login sucessfully!!!\n");
HangmanModel(users[loc]);
}
else
{
printf("Hangman Game Assistant: can't find your username, retype your username");
scanf("%s", username);
loc = checkUsername(username);
}
}
}
else if (chs == 3)
{
exit = 1;
}
}
}