/*
石头剪刀布
玩家, 结构体,来定义
玩家的名字
target 石头剪刀布 (宏定义)
history (三局两胜)
winer 弹框提示
**/
//game.c
#include "game.h"
#include "defines3.h"
#include "windows.h"
#include <stdio.h>
#include <string.h>
Role red; //这里需要全局变量,赋值调用。
Role blue;
Role *role_red =&red;
Role *role_blue =&blue;
char *core(int r,int m){
int count = r-m;
const char *msg = count==0?"平":(count==-2||count==1)?"赢":"输";
return msg;
}
//把手势的协议转换成字符串
const char *toString(int r){
const char *msg="";
switch(r){
case 1:
msg="剪刀";
break;
case 2:
msg = "石头";
break;
case 3:
msg = "布";
break;
default:
printf("error.....\n");
}
return msg;
}
//出手势的函数
void action(Role *role){
int a;
error:
printf("请%s出手势\n",role->name);
scanf("%d",&a);
//判断如果输入的不是123,则重新输入
if(CHECK(a)==0){
printf("手势错误!!!");
goto error; //校验手势
}
role->current = a;
printf("哇擦类%s出了%s\n",role->name,toString(role->current));
}
//初始化数据
void init(){
role_red->name ="文大帅哥";
role_blue->name ="大坏蛋";
red.fire = &action;
blue.fire = &action;
}
//开始游戏的函数
void run(){
gaming:
init();
role_red->fire(role_red);
role_blue->fire(role_blue);
const char *result =core(role_blue->current,role_red->current);
printf("%s获得%s\n",role_red->name,core(role_red->current,role_blue->current));
if(strcmp(result,"赢")){
role_blue->score+=1;
printf("%s取得%d分\n",role_blue->name,role_blue->score);
}
if(strcmp(result,"输")){
role_red->score+=1;
printf("%s取得%d分\n",role_red->name,role_red->score);
}
if(role_blue->score!=3&&role_red->score!=3){
goto gaming;
}else{
const char *title = "";
title= role_blue->score==3?title="蓝方胜":"红方胜";
MessageBox(NULL,title,"",MB_OK);
role_blue->score = 0;
role_red->score = 0;
}
}
void startGame(){
run();
}
//defines3.h
#pragma once
#define SHI_TOU 1
#define JIAN_DAO 2
#define BU 3
//校验手势的正确性 ,宏定义
#define CHECK(a)(a==SHI_TOU||a==JIAN_DAO||a==BU)
//函数指针类型 -----自定义指针
typedef void (*Function) ();
typedef struct _Role{
const char *name; //角色名字
int current; // 当前手势
int score; //赢得次数
Function fire; //出手势的行为
}Role;
//game.h
#pragma once
void startGame();
//main.c
#include <stdio.h>
#include <stdlib.h>
#include "defines3.h"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
startGame();
return 0;
}
结束,简单的C语言实现小游戏,运用了许多C的性质,指针。。。等很有学习意义。