#define _CRT_SECURE_NO_WARNINGS //消除一个安全检测,没有会报c4996错误
#include<stdio.h> //标准输入、出
#include<string.h> // strcpy
#include<stdlib.h> //标准库函数 malloc
#include"GameCompany1.h" //
/*1、 甲方实现---》 == 留接口--》函数指针*/
//初始化游戏 参数1:人物指针 参数2:人物姓名
// *INIT_GAME 函数指针类型
typedef void(*INIT_GAME)(void **player, char *name);
//核心战斗 如果胜利:返回1 失败则返回:0 参数1:玩家 参数2:副本难度
typedef int(*FIGHT_GAME)(void *player, int gameDiff);
// 查看玩家信息
typedef void(*PRINT_GAME)(void *player);
//离开游戏
typedef void(*EXIT_GAME)(void *player);
//甲方的功能实现, 通过INIT_GAME 函数指针类型--》创建 init 指针
void playGame(INIT_GAME init, FIGHT_GAME fight, PRINT_GAME printGame, EXIT_GAME exitGame){
//初始化游戏
void * player = NULL;
printf("请输入玩家的姓名: \n");
char buf[1024];
scanf("%s", buf);
init(&player, buf); // init 是函数指针--》调用此函数--》构建了人物
// 战斗
printf("请选择游戏难度: \n");
printf("1: 简单\n");
printf("2: 中等\n");
printf("3: 困难\n");
int diff = -1; //初始值
scanf("%d", &diff);
int ret = fight(player, diff);
if (ret == 0){
printf("游戏结束 \n");
}
else{
printf("恭喜胜利 \n");
printf("玩家当前状态: \n");
printGame(player);
}
//退出游戏
exitGame(player);
}
int main(){
playGame(INIT_GAME_GameCompany1, FIGHT_GAME_GameCompany1, PRINT_GAME_GameCompany1, EXIT_GAME_GameCompany1);
system("pause");
return EXIT_SUCCESS; // 宏=0
}
GameCompany1.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS //消除一个安全检测,没有会报c4996错误
#include<stdio.h> //标准输入、出
#include<string.h> // strcpy
#include<stdlib.h> //标准库函数 malloc
struct Player{
char name[64];
int level;
int exp;
};
// *INIT_GAME 函数指针类型
void INIT_GAME_GameCompany1(void **player, char *name);
//核心战斗 如果胜利:返回1 失败则返回:0 参数1:玩家 参数2:副本难度
int FIGHT_GAME_GameCompany1(void *player, int gameDiff);
// 查看玩家信息
void PRINT_GAME_GameCompany1(void *player);
//离开游戏
void EXIT_GAME_GameCompany1(void *player);
GameCompany1.c
#include"GameCompany1.h"
void INIT_GAME_GameCompany1(void **pl, char *name){
struct Player *player = malloc(sizeof(struct Player)); //内存分配完成
if (player == NULL)
{
return;
}
*pl = player;
strcpy(player->name, name); // 字符串赋值
player->exp = 0;
player->level = 0;
}
//核心战斗 如果胜利:返回1 失败则返回:0 参数1:玩家 参数2:副本难度
int FIGHT_GAME_GameCompany1(void *p, int gameDiff){
struct Player *player = p;
int addExp = 0; // 玩家经验
switch (gameDiff) //根据难度不同--》产生3种情况
{
case 1:
addExp = isWin(90, 1); // (90 胜率, 1 难度)---》返回是否胜利
break;
case 2:
addExp = isWin(50, 2);
break;
case 3:
addExp = isWin(30, 1);
break;
default:
break;
}
player->exp += addExp;
player->level = player->exp / 10;
if (addExp == 0){
return 0;
}
else{
return 1;
}
}
// 是否赢了 游戏胜率winRate
int isWin(int winRate, int diff){
int random = rand() % 100 + 1;
if (random <= winRate)
{
return diff * 10;
}
else{
return 0;
}
}
// 查看玩家信息
void PRINT_GAME_GameCompany1(void *p){
struct Player *player = p;
printf("玩家<%s>----当前等级<%d>", player->name, player->level, player->exp);
}
//离开游戏
void EXIT_GAME_GameCompany1(void *player){
if (player == NULL){
return;
}
free(player);
player = NULL;
}