Скачиваний:
4
Добавлен:
03.02.2019
Размер:
14.19 Кб
Скачать
#pragma comment (lib,"ws2_32.lib")
#pragma warning(disable: 4098)
#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS // откл устаревшие предупреждения 

#include <WinSock2.h>
#include <WS2tcpip.h>
#include <tchar.h> //в этом файле содержатся определения некоторых полезных макросов
#include <iostream>
#include <windows.h>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <deque>
#include <string>
using namespace std;

#define ID_BTNCONNECT 2
#define ID_BTNGETCARD 3
#define ID_BTNIMG 4
#define WM_DRAW (WM_USER + 3)
SOCKET clientSocket;
USHORT PORT;
char IP[80];
HWND hWnd, btnPlay, staticIp, staticPort, editIp, editPort, btnConnect, rcvArea , staticName, editName , sendArea, btn;
HDC hdc;
PAINTSTRUCT ps;
HINSTANCE hInst ;
void recvMessage(HWND);
void connectServer(HWND);

int nSelectList = 0;
char color[128];
char name[128];
//////////////////////
static HBITMAP hBitmap1;
HANDLE handle1, hOldBitmap;
BITMAP bm1;
HDC cardBMP;
int xDraw;
int yDraw = 350;
double step = 25;
double wCard = 57.14;
double hCard = 85.75;
struct CardObj {
	int x;
	int y;
	int width;
	int height;
	char color[128];
	char name[128];
};
deque<CardObj> imgCards;
CardObj currentCard;
bool isValidCard = FALSE;
bool isMyTurn = true;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int getPosX(int);
void drawCards();
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	WNDCLASS wc;
	MSG msg;

	// Регистрируем класс окна
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 0);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = "MainFrame";

	if (!RegisterClass(&wc)) return 0;

	hWnd = CreateWindow("MainFrame", "Uno Client", WS_OVERLAPPEDWINDOW,
		400, 200, 700,550, hWnd, NULL, hInstance, NULL);

	editIp = CreateWindow(_T("EDIT"), _T("127.0.0.1"), WS_VISIBLE | WS_CHILD,
		10, 10, 110, 20, hWnd, NULL, hInst, NULL);

	editPort = CreateWindow(_T("EDIT"), _T("8080"), WS_VISIBLE | WS_CHILD,
		10, 35, 110, 20, hWnd, NULL, hInst, NULL);

	editName = CreateWindow("EDIT", "Name", WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 
		10, 60, 110, 20,	hWnd, NULL, hInstance, NULL);

	btnConnect = CreateWindow(_T("BUTTON"), _T("Connect"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
		10, 100, 110, 30, hWnd, (HMENU)ID_BTNCONNECT, hInst, NULL);

	btnPlay = CreateWindow(_T("BUTTON"), _T("Get card"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
		10, 140, 110, 30, hWnd, (HMENU)ID_BTNGETCARD, hInst, NULL);

	//lstBox = CreateWindow(_T("LISTBOX"), NULL, WS_VISIBLE | WS_CHILD | LBS_WANTKEYBOARDINPUT |  LBS_NOTIFY | WS_BORDER | WS_VSCROLL,
	//	 0, 180, 130, 300, hWnd, (HMENU)ID_LIST, hInst, NULL);

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return 0;
}
//#define ID_BTNRED 10
//#define ID_BTNGREEN 11
//#define ID_BTNYELLOW 12
//#define ID_BTNBLUE 13
//HWND btnRed, btnGreen, btnBlue, btnYellow;
//HWND newHwnd;

void loadImage(HWND hWnd) {
	hBitmap1 = (HBITMAP)LoadImage(NULL, _T("deck.bmp"), IMAGE_BITMAP,
								0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	if (hBitmap1 == NULL )
	{
		MessageBox(hWnd, _T("Файл не найден"), _T("Загрузка изображения"),
						MB_OK | MB_ICONHAND);
		DestroyWindow(hWnd);
		return;
	}
	GetObject(hBitmap1, sizeof(bm1), &bm1);
	hdc = GetDC(hWnd);
	cardBMP = CreateCompatibleDC(hdc);
	SelectObject(cardBMP, hBitmap1);
	ReleaseDC(hWnd, hdc);
}
void getCard() {
	if (true)
	{
		char client[128];
		wsprintf(client," ; | | | | :%d",1);// 1 - когдя клиент хочет взять карту
		send(clientSocket,client,sizeof(client),0);
	} else
	{
		MessageBox(NULL, "Ждите очередь", "Ошибка", MB_ICONERROR);
	}
}

void colorChoice() {
	//btnRed = CreateWindow(_T("BUTTON"), _T("Red"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
	//	200, 140, 50, 30, hWnd, (HMENU)ID_BTNRED, hInst, NULL);
	//btnGreen = CreateWindow(_T("BUTTON"), _T("Green"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
	//	260, 140, 50, 30, hWnd, (HMENU)ID_BTNGREEN, hInst, NULL);
	//btnBlue = CreateWindow(_T("BUTTON"), _T("Blue"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
	//	200, 200, 50, 30, hWnd, (HMENU)ID_BTNBLUE, hInst, NULL);
	//btnYellow = CreateWindow(_T("BUTTON"), _T("Yellow"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
	//	260, 200, 50, 30, hWnd, (HMENU)ID_BTNYELLOW, hInst, NULL);
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg) {
		case WM_CREATE: {
			loadImage(hWnd);
			break;
		}
		case WM_SIZE: {
			drawCards();
			break;
		}
		case WM_PAINT:
		{
			break;
		}
		case WM_LBUTTONDOWN:
		{
			if (isMyTurn)
			{
				int mouseY = HIWORD(lParam);
				int mouseX = LOWORD(lParam);
				int x = getPosX(mouseX);
				if (mouseY > yDraw && mouseY < yDraw + hCard &&
					 mouseX > 100 && mouseX < xDraw + (wCard - step))
				{

					int selectCard = (int)x/step - ( (100 + step)/step );
					if ( strcmp(currentCard.color,imgCards[selectCard].color) == 0 || strcmp(currentCard.name,imgCards[selectCard].name) == 0
						 || strcmp(imgCards[selectCard].name,"wild") == 0 )
					{
						currentCard = imgCards[selectCard];
						char currCard[128];
						wsprintf(currCard,"%s;%s|%d|%d|%d|%d:%d",
									currentCard.name,
									currentCard.color,
									currentCard.x,
									currentCard.y,
									currentCard.width,
									currentCard.height,
									2
						);// отпрв карту на сервер
						//MessageBox(hWnd,currCard,"CurrCard",MB_OK);
					
						send(clientSocket,currCard,sizeof(currCard),0);
						imgCards.erase(imgCards.begin() + selectCard);
						drawCards();
						// победитель
						if (imgCards.size() < 1)
						{
							char win[128];
							char nameClient[128], buff[128];
							GetWindowText(editName, buff, 255);
							wsprintf(nameClient, "%s",buff);
							wsprintf(win,"%s; | | | | :%d", nameClient, 3); //3 - говорим серверу посчитай очки победителя
							send(clientSocket, win, sizeof(win), 0);
							return 0;
						}
					} else{ MessageBox(NULL, "Карта не подходит", "Ошибка", MB_ICONERROR); }
				} 
			}else { MessageBox(NULL, "Ждите очередь", "Ошибка", MB_ICONERROR); }
			break;
		}
		case WM_COMMAND: {
			switch (LOWORD(wParam)) {
				case ID_BTNGETCARD:  {
					if (isMyTurn)
					{
						getCard();
					}else
					{
						MessageBox(NULL, "Ждите очередь", "Ошибка", MB_ICONERROR);
					}
					break;
				}
				case ID_BTNCONNECT: {
					char port[10];
					GetWindowText(editPort, port, 255);
					GetWindowText(editIp, IP, 255);
					PORT = atoi(port);
					connectServer(hWnd);
					break;
				}
			}
			break;
		}
		case WM_DESTROY: {
			PostQuitMessage(0);
			break;
		}
		default: { return DefWindowProc(hWnd, msg, wParam, lParam); }
	}
	return 0;
}

void connectServer(HWND hWnd) {
	// Шаг 1 - инициализация библиотеки Winsock
	WSADATA wsData;
	WORD version = MAKEWORD(2, 2);
	if (WSAStartup(version, &wsData))
	{
		// Ошибка!
		MessageBox(NULL, "WSAStartup  Error", "Error", MB_OK | MB_ICONHAND);
		return;
	}
	// Шаг 2 - создание сокета
	if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		MessageBox(NULL, "Socket error", "Error", MB_OK);
		return;
	}
	// Шаг 3 - установка соединения
	HOSTENT *hst;
	// заполнение структуры sockaddr_in
	// указание адреса и порта сервера
	sockaddr_in dest_addr;
	dest_addr.sin_family = AF_INET;
	dest_addr.sin_port = htons(PORT);
	if (inet_addr(IP) != INADDR_NONE)
		dest_addr.sin_addr.s_addr = inet_addr(IP); // преобразование IP адреса из символьного в сетевой формат
	else
		// попытка получить IP адрес по доменному
		// имени сервера
		if (hst = gethostbyname(IP))
			// hst->h_addr_list содержит не массив адресов,
			// а массив указателей на адреса
			((unsigned long *)&dest_addr.sin_addr)[0] =
			((unsigned long **)hst->h_addr_list)[0][0];
		else
		{
			MessageBox(NULL, "Invalid address", "Error", MB_OK);
			closesocket(clientSocket);
			WSACleanup();
			return;
		}
	// адрес сервера получен – пытаемся установить соединение 
	if (connect(clientSocket, (sockaddr *)&dest_addr, sizeof(dest_addr)) < 0)
	{
		closesocket(clientSocket);
		MessageBox(NULL, "Socket Error", "Error", MB_OK);

		return;
	}
	
	//MessageBox(hWnd, "Connected is OK", "Error", MB_OK);
	CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)recvMessage, hWnd, NULL, NULL);
}

void drawCards() {
	xDraw  = 100;
	InvalidateRect(hWnd, NULL, TRUE);
	hdc = BeginPaint(hWnd, &ps);
	for (int i = 0; i < imgCards.size(); i++)
	{
		StretchBlt(hdc, xDraw, yDraw, (int)wCard, (int)hCard, cardBMP,
			 imgCards.at(i).x, imgCards.at(i).y, imgCards.at(i).width, imgCards.at(i).height, SRCCOPY);
		xDraw += (int)step;
	}
	StretchBlt(hdc, 300, 140, (int)wCard,(int) hCard, cardBMP,
				  currentCard.x, currentCard.y, currentCard.width, currentCard.height, SRCCOPY);

	EndPaint(hWnd, &ps);
}

int getPosX(int mousePos) { //mousePos = X, Y
	int pos = 0;
	double count = 100 + step;
	for (int p = 0; p < imgCards.size(); p++) {
		if (p == imgCards.size() - 1)
		{
			count += (wCard - step);
		}
		if (mousePos < count) {
			if (p == imgCards.size() - 1)
			{
				count -= (wCard - step);
			}
			pos = (int)count;

			break;
		}
		count += step;
	}
	return pos;
}

void restart() {
	imgCards.clear();
}
void recvMessage(HWND hWnd) {
	char res[128];
	char *token;
	int flag = 0;
	int x = 0;
	int y = 0;
	int width = 0;
	int height = 0;
	char charFlag[128];

	while (1)
	{
		int result = recv(clientSocket, res, sizeof(res), 0);
		if (result > 0)
		{
			token = strtok(res, ";");
			wsprintf(name,"%s", token);
			token = strtok(NULL, ";");
			wsprintf(color,"%s", token);

			token = strtok(color, "|");
			token = strtok(NULL, "|");
			wsprintf(charFlag,"%s",token);
			x = atoi(charFlag);

			token = strtok(NULL, "|");
			wsprintf(charFlag,"%s",token);
			y = atoi(charFlag);

			token = strtok(NULL, "|");
			wsprintf(charFlag,"%s",token);
			width = atoi(charFlag);

			token = strtok(NULL, "|");
			wsprintf(charFlag,"%s",token);
			height = atoi(charFlag);

			token = strtok(charFlag,":");
			token = strtok(NULL,":");
			wsprintf(charFlag,"%s",token);
			flag = atoi(charFlag);

			char card[128];
			wsprintf(card,"%s %s", name, color);
			//wsprintf(imgCard,"%d %d \n%d %d", x, y, width, height);
			if (flag == 1) // 1 - проверка очереди
			{
				if(x == 0){
					isMyTurn = false;
				} 
				if(x == 1)
				{
					isMyTurn = true;
					//если до меня походили этой картой то...
					if (*currentCard.name == *"takeTwo")
					{
						getCard();
						getCard();
					}else if(strcmp(currentCard.name,"skip") == 0)
					{
						char skip[128];
						wsprintf(skip," ; | | | | :%d",5);
						send(clientSocket, skip, sizeof(skip), 0);
					}else if (strcmp(currentCard.name,"moveBack") == 0)
					{
						char moveBack[128];
						wsprintf(moveBack," ; | | | | :%d",6);
						send(clientSocket, moveBack, sizeof(moveBack), 0);
					}else if (strcmp(currentCard.name,"wild") == 0)
					{
					}else if (strcmp(currentCard.name,"wildFour") == 0)
					{
						getCard();
						getCard();
						getCard();
						getCard();
					}
				}

			} else if(flag == 2)
			{
				MessageBox(NULL,card,"НЕ ПОДХОДИТ",MB_ICONINFORMATION);
			} else if (flag == 3) //  получаем перевернутою карту
			{
				currentCard.x = x;
				currentCard.y = y;
				currentCard.width = width;
				currentCard.height = height;
				strcpy(currentCard.color,color);
				strcpy(currentCard.name,name);
				drawCards();
				

			} else if (flag == 4)
			{
				MessageBox(NULL,name,"Error",MB_ICONINFORMATION);
			} else if (flag == 5) // отправка очков со всех своих карт победителю
			{
				int score = 0;
				for (int i = 0; i < imgCards.size(); i++)
				{
					char decimal[128];
					char colorTest[128];
					wsprintf(colorTest,"%s",imgCards[i].color);
					wsprintf(decimal,"%s",imgCards[i].name);
					if (atoi(decimal) != 0 || strcmp(imgCards[i].name,"0") == 0 ) // все карты с цифрами
					{
						score += atoi(decimal);
					} else if(strcmp(colorTest,"black") != 0) // все карте с действием кроме черных
					{
						score += 20;
					} else // черные с действием
					{
						score += 50;
					}
				}
				char decimal[128];
				wsprintf(decimal," ; |%d| | | :%d",score, 7); // 
				send(clientSocket, decimal, sizeof(decimal), 0);
			} else if (flag == 6) // сообщение всем кроме победителя
			{
				char msgWin[128];
				wsprintf(msgWin,"Игрок %s выиграл!\nОн набрал %d очков",name, x); // 
				MessageBox(hWnd,msgWin,"End Game",MB_OK);
				restart();
				drawCards();
				char restartGame[128];
				wsprintf(restartGame," ; | | | | :%d", 8); // restart game
				send(clientSocket, restartGame, sizeof(restartGame), 0);
			} else if (flag == 7) // сообщение победтелю
			{
				char msgWin[128];
				wsprintf(msgWin,"Вы выиграли!\nВаши очки: %d", x); // nameClient
				MessageBox(hWnd,msgWin,"End Game",MB_OK);
				restart();
				drawCards();
				char restartGame[128];
				wsprintf(restartGame," ; | | | | :%d", 8); // restart game
				send(clientSocket, restartGame, sizeof(restartGame), 0);
			}else
			{
				//MessageBox(hWnd,card,"imgCard",MB_ICONINFORMATION);
				CardObj cardObj;
				cardObj.x = x;
				cardObj.y = y;
				cardObj.width = width;
				cardObj.height = height;
				strcpy(cardObj.color,color);
				strcpy(cardObj.name,name);

				imgCards.push_back(cardObj);
				drawCards();
			}

		}else if (result == SOCKET_ERROR) {
			MessageBox(hWnd, "Вас исключили", "Client", MB_OK);
			closesocket(clientSocket);
			SendMessage(hWnd, WM_CLOSE, 0, 0L);
			break;
		}
	}
	closesocket(clientSocket);
	WSACleanup();
}
Соседние файлы в папке Client Class