跳到正文

个人记录

在线五子棋程序

tiger2005约 42 分钟
原文

这是 2026年3月17日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2020年10月23日
收录
2026年3月17日
更新
2026年11月14日
篇幅
约 42 分钟

版本

  1. v2当前
  2. v1

请打开 -lwsock32 编译开关编译。打开方式同 C++11 和 O2。

User.cpp

C++
#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include <process.h>
#include <math.h>
#include <conio.h>

#define    BUFLEN        2000                  // 缓冲区大小
#define WSVERS        MAKEWORD(2, 0)        // 指明版本2.0 
#pragma comment(lib,"ws2_32.lib")         // 指明winsock 2.0 Llibrary

/*------------------------------------------------------------------------
 * main - TCP client for DAYTIME service
 *------------------------------------------------------------------------
 */
void colset(int a){
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);
}
SOCKET    sock, sockets[100] = { NULL };                          /* socket descriptor            */
//    int    cc;                                /* recv character count            */
char    *packet = NULL;               /* buffer for one line of text    */
char *pts, *input;
HANDLE hThread;
unsigned threadID;
int gameType;
unsigned int __stdcall Chat(PVOID PM)
{
	time_t    now;
	(void)time(&now);
	pts = ctime(&now);
	char buf[2000];

	while (1)
	{
		int cc = recv(sock, buf, BUFLEN, 0);   //cc为接收的字符数
		if (cc == SOCKET_ERROR || cc == 0)
		{
			colset(12);
			printf("[Error] Error Code: %d\n", GetLastError());
			printf("Cannot find the server.\n");
			colset(7);
			CloseHandle(hThread);
			(void)closesocket(sock);
			break;
		}
		else if (cc > 0)
		{
			if(buf[0]=='[' && buf[1]=='S')	gameType=1;
			else	gameType=0;
			if(!strcmp(buf,"/cls")){
				system("cls");continue;
			}
			if(buf[1]=='N'){
				colset(10);
				if(buf[6]=='['){
					if(buf[7]=='W')	colset(12);
					if(buf[7]=='R')	colset(13);
					if(buf[7]=='A')	printf("\n");
				}
			}
			printf("%s\n", buf);
			colset(7);
		}
	}
	return 0;
}
char    host[20];
char service[20];
char   namei[20];
int main(int argc, char *argv[])
{
	time_t    now;
	(void)time(&now);
	pts = ctime(&now);
	printf("Host IP: ");
	gets(host);
	printf("Service port: ");
	gets(service);
	printf("Your name: ");
	gets(namei);
	//const char *service = "50520";
	struct  sockaddr_in sin;            /* an Internet endpoint address    */
	WSADATA wsadata;
	WSAStartup(WSVERS, &wsadata);       /* 启动某版本Socket的DLL        */

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons((u_short)atoi(service));    //atoi:把ascii转化为int. htons:主机序(host)转化为网络序(network), s--short
	sin.sin_addr.s_addr = inet_addr(host);           //如果host为域名,需要先用函数gethostbyname把域名转化为IP地址

	sock = socket(PF_INET, SOCK_STREAM, 0);

	connect(sock, (struct sockaddr *)&sin, sizeof(sin));
	(void) send(sock,namei, sizeof(namei), 0);;
	hThread = (HANDLE)_beginthreadex(NULL, 0, Chat, NULL, 0, &threadID);

	while (1)
	{
		char buf1[2000];
		gets(buf1);
		if (!strcmp(buf1, "/exit"))
			goto end;
		if(!gameType && !strcmp(buf1,"/cls"))
			system("cls");
		else
			(void)send(sock, buf1, sizeof(buf1), 0);
		(void)time(&now);
		pts = ctime(&now);
	}

end:    CloseHandle(hThread);
	closesocket(sock);
	WSACleanup();

	printf("Press Enter to contine...");
	getchar();
	return 0;
}

Host.cpp

C++
#include <stdio.h>
#include <winsock2.h>
#include <time.h>
#include <conio.h>
#include <windows.h>
#include <process.h>
#include <math.h>
#include <set>
#define QLEN 5
#define WSVERS MAKEWORD(2, 0)
#define BUFLEN 2000
#pragma comment(lib,"ws2_32.lib")
using namespace std;
const char * systemAlert = "Use /setFirst and /setSecond to choose the players.\n\
Use w/a/s/d to move, and q to put chess.\n\
Press Enter after the movement statements.\n\
Use /cls to clear the screen if the game is not on.\n";
SOCKET msock, ssock;
SOCKET  sockets[100] = {NULL};
SOCKET  sockChess[2] = {NULL};
char gamerName[2][30];
char na[101][21];
int cc,nai;
time_t now;
char pts[64],tim[64],ptss[64];
char buf[2000],nam[2000];
char *input;
HANDLE hThread1,hThread[100] = {NULL};
clock_t sta,end;
unsigned int threadID,ThreadID[105],number,sen=0;
char *name[1005];
bool GetIn[2000];

struct  sockaddr_in fsin;
struct  sockaddr_in Sin;

struct Chess{
    int typ[16][16];
    const char MP[32][62]=
                    {"   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   "};
    char Mp[32][62]={
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   ",
                     "---+---+---+---+---+---+---+---+---+---+---+---+---+---+---",
                     "   |   |   |   |   |   |   |   |   |   |   |   |   |   |   "};
    int X[2],Y[2];
    char str[2000];
    int currS,Pt;
    bool check5(int a,int b,int c,int d,int e){
        return a==b && b==c && c==d && d==e && a!=0;
    }
    bool checkWin(){
        for(int i=1;i<=11;i++)
            for(int j=1;j<=15;j++)
                if(check5(typ[i][j],typ[i+1][j],
                    typ[i+2][j],typ[i+3][j],typ[i+4][j]))
                    return true;
        for(int i=1;i<=15;i++)
            for(int j=1;j<=11;j++)
                if(check5(typ[i][j],typ[i][j+1],
                    typ[i][j+2],typ[i][j+3],typ[i][j+4]))
                    return true;
        for(int i=1;i<=11;i++)
            for(int j=1;j<=11;j++)
                if(check5(typ[i][j],typ[i+1][j+1],
                    typ[i+2][j+2],typ[i+3][j+3],typ[i+4][j+4]))
                    return true;
        for(int i=1;i<=11;i++)
            for(int j=5;j<=15;j++)
                if(check5(typ[i][j],typ[i+1][j-1],
                    typ[i+2][j-2],typ[i+3][j-3],typ[i+4][j-4]))
                    return true;
        return false;
    }
    void newGame(){
        memset(typ,0,sizeof(typ));
        X[0]=1;X[1]=15;
        Y[0]=1;Y[1]=15;
        currS=Pt=0;
        for(int i=0;i<29;i++)
            for(int j=0;j<59;j++)
                Mp[i][j]=MP[i][j];
        memset(str,0,sizeof(str));
        for(int i=0;i<29;i++)
            sprintf(str,"%s%s\n",str,MP[i]);
        mdf(X[0]*2-2,Y[0]*4-3+(0==0?-1:1),(0==0?'>':'<'));
        mdf(X[1]*2-2,Y[1]*4-3+(1==0?-1:1),(1==0?'>':'<'));
    }
    void mdf(int x,int y,char ch){
        Mp[x][y]=ch;
        str[x*60+y]=ch;
    }
    void moveIndex(int delX,int delY){
        mdf(X[currS]*2-2,Y[currS]*4-3+(currS==0?-1:1),' ');
        X[currS]=max(1,min(15,X[currS]+delX));
        Y[currS]=max(1,min(15,Y[currS]+delY));
        mdf(X[currS]*2-2,Y[currS]*4-3+(currS==0?-1:1),(currS==0?'>':'<'));
    }
    int putChess(){
        if(typ[X[currS]][Y[currS]]) return -1;
        mdf(X[currS]*2-2,Y[currS]*4-3,(currS==0?'X':'O'));
        ++Pt;
        typ[X[currS]][Y[currS]]=currS+1;
        if(checkWin())  return currS+2;
        return !(currS=!currS);
    }
}gamer;
int gameType;
char Stt[2000],Inf[2000],Use[2000];
char Res[2000];
void sendMap(){
    sprintf(Res,"/cls");
    for(int i=0; i<=number; i++) {
        if(sockets[i] != NULL) {
            (void) send(sockets[i],Res, sizeof(Res), 0);
            printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
        }
    }
    sprintf(Res,"[STAT] %s\n[INFO] %s\n[USER] %s\n[PLAY] %s(X) vs %s(O)\n[CURR] %s\n%s"
        ,Stt,Inf,Use,gamerName[0],gamerName[1],gamerName[gamer.currS],gamer.str);
    for(int i=0; i<=number; i++) {
        if(sockets[i] != NULL) {
            (void) send(sockets[i],Res, sizeof(Res), 0);
            printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
        }
    }
}
unsigned int __stdcall Chat(PVOID PM) {

    (void) time(&now);
    strftime(pts,sizeof(pts),"%Y-%m-%d",localtime(&now));

    sprintf(pts,"%s.txt",pts);

    FILE *fp=fopen(pts,"a");;
    if((fp=fopen(pts,"a")) == NULL) {
        printf("ERROR:data file cannot be opened!\n");
        exit(1);
    }

    char buf1[2000];
    char buf2[2000];
    char buf3[2000];
    char buf4[2000];
    char buf15[2000];

    (void) time(&now);
    strftime(pts,sizeof(pts),"%Y,%b,%d %X %a",localtime(&now));

    fprintf(fp,"*-*-*-*-*[%s]*-*-*-*-*\n\n",pts);

    (void) time(&now);
    strftime(pts,sizeof(pts),"%X",localtime(&now));

    sockets[number] = ssock;
    SOCKET  sock = ssock;
    ThreadID[number] = threadID;
    GetIn[number]=true;
    unsigned int threadid = threadID;
    char namei[20];

    (void) recv(sock,namei, BUFLEN, 0);
    name[number]=namei;
    sprintf(buf2,"[NOTE] %s\n%s entered the char room!",pts,namei);
    printf("%s",buf2);
    fprintf(fp,"%s",buf2);
    if(!gameType){
        for(int i=0; i<=number; i++) {
            if(sockets[i] != NULL && sockets[i] != sock) {
                (void) send(sockets[i],buf2, sizeof(buf2), 0);
                printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
            }
        }
    }
    else    sprintf(Inf,"%s",buf2);
    sprintf(buf2,"[NOTE] Chat name: %s\nUser(s): ",nam);
    bool hasnC=false;
    for(int i=0;i<=number;i++){
        if(!GetIn[i])   continue;
        if(hasnC)   sprintf(buf2,"%s, ",buf2);
        sprintf(buf2,"%s%s",buf2,name[i]);
        hasnC=true;
    }
    hasnC=false;
    memset(Use,'\0',sizeof(Use));
    for(int i=0;i<=number;i++){
        if(!GetIn[i])   continue;
        if(hasnC)   sprintf(Use,"%s, ",Use);
        sprintf(Use,"%s%s",Use,name[i]);
        hasnC=true;
    }
    sprintf(buf2,"%s\n%s",buf2,systemAlert);
    fprintf(fp,"%s",buf2);
    if(!gameType)
        (void) send(sock,buf2, sizeof(buf2), 0);
    puts("");
    fprintf(fp,"\n");
    if(gameType){
        sprintf(Inf,"%s entered the char room!",namei);
        sendMap();  
    }
flag1:
    cc = recv(sock, buf3, BUFLEN, 0);
    if(cc == SOCKET_ERROR || cc == 0) {

        (void) time(&now);
        strftime(pts,sizeof(pts),"%X",localtime(&now));

        sprintf( buf3,"[NOTE] %s\n%s left the chat room!",pts,namei);

        for(int i=0; i<=number; i++) {
            if(sockets[i] != NULL && sockets[i] == sock) {
                sockets[i] = NULL;
                name[i] = NULL;
                GetIn[i]=false;
                CloseHandle(hThread[i]);
                break;
            }
        }
        sock = NULL;
        printf("%s", buf3);
        fprintf(fp,"%s", buf3);
        bool hasnC=false;
        memset(Use,'\0',sizeof(Use));
        for(int i=0;i<=number;i++){
            if(!GetIn[i])   continue;
            if(hasnC)   sprintf(Use,"%s, ",Use);
            sprintf(Use,"%s%s",Use,name[i]);
            hasnC=true;
        }
        if(!gameType){
            for(int i=0; i<=number; i++) {
                if(sockets[i] != NULL && sockets[i] != sock) {
                    (void) send(sockets[i], buf3, sizeof(buf3), 0);
                    printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
                }
            }
        }
        else    sprintf(Inf,"%s",buf3);
        puts("");
        fprintf(fp,"\n");
        if(gameType){
            sprintf(Inf,"%s left the chat room!",namei);
            sendMap();  
        }
    }

    else if(cc > 0) {

        (void) time(&now);
        strftime(pts,sizeof(pts),"%X",localtime(&now));
        sprintf(buf4,"[INFO] %s - %s\n%s",namei,pts,buf3);
        ++sen;
        printf("%s",buf4);
        fprintf(fp,"%s",buf4);
        if(gameType && sock==sockChess[gamer.currS]
             && (!strcmp(buf3,"w") || !strcmp(buf3,"W")
              || !strcmp(buf3,"s") || !strcmp(buf3,"S")
              || !strcmp(buf3,"a") || !strcmp(buf3,"A")
              || !strcmp(buf3,"d") || !strcmp(buf3,"D")
              || !strcmp(buf3,"q") || !strcmp(buf3,"Q"))){
            if(!strcmp(buf3,"w") || !strcmp(buf3,"W"))
                gamer.moveIndex(-1,0);
            if(!strcmp(buf3,"s") || !strcmp(buf3,"S"))
                gamer.moveIndex(1,0);
            if(!strcmp(buf3,"a") || !strcmp(buf3,"A"))
                gamer.moveIndex(0,-1);
            if(!strcmp(buf3,"d") || !strcmp(buf3,"D"))
                gamer.moveIndex(0,1);
            if(!strcmp(buf3,"q") || !strcmp(buf3,"Q")){
                int res=gamer.putChess();
                if(res>=2){
                    sprintf(Stt,"Game End: %s win the game!",gamerName[res-2]);
                    sendMap();
                    _sleep(3000);
                    sprintf(buf4,"/cls");
                    gameType=0;
                    sockChess[0]=sockChess[1]=NULL;
                    for(int i=0; i<=number; i++) {
                        if(sockets[i] != NULL) {
                            (void) send(sockets[i],buf4, sizeof(buf4), 0);
                            printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
                        }
                    }
                    sprintf(buf4,"[NOTE] %s",systemAlert);
                    for(int i=0; i<=number; i++) {
                        if(sockets[i] != NULL) {
                            (void) send(sockets[i],buf4, sizeof(buf4), 0);
                            printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
                        }
                    }
                }
                else if(res==-1){
                    sprintf(Stt,"Chess Error: Cannot put the chess!");
                }
                else if(gamer.Pt==225){
                	sprintf(Stt,"Game End: Draw!");
                    sendMap();
                    _sleep(3000);
                    sprintf(buf4,"/cls");
                    gameType=0;
                    sockChess[0]=sockChess[1]=NULL;
                    for(int i=0; i<=number; i++) {
                        if(sockets[i] != NULL) {
                            (void) send(sockets[i],buf4, sizeof(buf4), 0);
                            printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
                        }
                    }
                    sprintf(buf4,"[NOTE] %s",systemAlert);
                    for(int i=0; i<=number; i++) {
                        if(sockets[i] != NULL) {
                            (void) send(sockets[i],buf4, sizeof(buf4), 0);
                            printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
                        }
                    }
				}
                else{
                    sprintf(Stt,"Chess Put: %s put the chess!",gamerName[res]);
                }
            }
            if(gameType)    sendMap();
        }
        else if(!gameType){
            if((!strcmp(buf3,"/setFirst") || !strcmp(buf3,"/setSecond"))
            && !gameType){
                if(!strcmp(buf3,"/setFirst") && sockChess[0]==NULL)
                    sockChess[0]=sock,sprintf(gamerName[0],"%s",namei),
                    sprintf(buf4,"[NOTE] %s is Player 0",namei);
                if(!strcmp(buf3,"/setSecond") && sockChess[1]==NULL)
                    sockChess[1]=sock,sprintf(gamerName[1],"%s",namei),
                    sprintf(buf4,"[NOTE] %s is Player 1",namei);
            }
            if(sockChess[0]!=NULL && sockChess[1]!=NULL){
                sprintf(Inf,"");
                sprintf(Stt,"Game Start!");
                gameType=1;
                gamer.newGame();
                sendMap();
            }
            else for(int i=0; i<=number; i++) {
                if(sockets[i] != NULL) {
                    (void) send(sockets[i],buf4, sizeof(buf4), 0);
                    printf("(成功将消息发送至<%d>)\n",ThreadID[i]);
                }
            }
        }
        else{
            sprintf(Inf,"%s: %s",namei,buf3);
            sendMap();
        }
        puts("");
        fprintf(fp,"\n");
        goto flag1;
    }
    (void) closesocket(sock);

    return 0;
}

int main(int argc, char *argv[]) {
    int alen;
    WSADATA wsadata;

    char  service[10];

    printf("请输入服务器端口:");
    gets(service);

    //注意:客户端连接服务端,IP为服务端的计算机的IP,端口为上面的service
    printf("请输入对话名字:");
    gets(nam);
    WSAStartup(WSVERS, &wsadata);
    msock = socket(PF_INET, SOCK_STREAM, 0);
    memset(&Sin, 0, sizeof(Sin));

    Sin.sin_family = AF_INET;
    Sin.sin_addr.s_addr = INADDR_ANY;
    Sin.sin_port = htons((u_short)atoi(service));
    bind(msock, (struct sockaddr *)&Sin, sizeof(Sin));
    listen(msock, 5);

    system("cls");

    printf("机房聊天工具【服务端】\n");
    printf("服务器端口:[%s]\n",service);
    printf("对话名字:%s\n",nam);
    (void) time(&now);
    strftime(pts,sizeof(pts),"%Y/%m/%d %X",localtime(&now));
    printf("时间:%s\n-----------------------\n",pts);

    number = -1;
    strftime(tim,sizeof(tim),"%X",localtime(&now));
    while(1) {

        alen = sizeof(struct sockaddr);
        ssock = accept(msock, (struct sockaddr *)&fsin, &alen);
        number ++;
        hThread[number] = (HANDLE)_beginthreadex(NULL, 0,Chat,NULL, 0, &threadID);

    }

    (void) closesocket(msock);
    WSACleanup();

    return 0;
}