#include<stdio.h>
#include<stdlib.h>
#include<graph.h>
#include"graph_sup.h"

#define TABLE_SIZE 289 /*17²*/

int* table;

void saveGame() {
	FILE* flux = fopen("save.txt", "w");

	for (int i = 0; i < 16; i ++) {
		for (int i2 = 0; i2 < 16; i2++) {
			fprintf(flux, "%d ", table[i*17+i2]);
		}
		fprintf(flux, "\n");
	}

	fclose(flux);
}

void loadGame() {
	FILE* flux = fopen("save.txt", "r");

	if (flux) {
		for (int i = 0; i < 16; i++) {
			for (int i2 = 0; i2 < 16; i2++) {
				int owo;
				fscanf(flux, "%d ", &owo);
				table[i*17+i2] = owo;
			}
			fscanf(flux, "\n");
		}

		fclose(flux);
	}

	for (int i = 0; i < 16; i++) {
		for (int i2 = 0; i2 < 16; i2++) {
			if (table[i2*17+i] == 1) {
				SetColor(255, 255, 255);
				RemplirRectangle(35 + 40*i, 35 + 40*i2, 30, 30);
				SetColor(0, 0, 0);
				DessinerRectangle(35 + 40*i, 35 + 40*i2, 30, 30);
			} else if (table[i2*17+i] == 2) {
				RemplirRectangle(35 + 40*i, 35 + 40*i2, 30, 30);
			}
		}
	}
}

void showGame() {
	for (int i = 0; i < 16; i ++) {
		for (int i2 = 0; i2 < 16; i2++) {
			printf("%d ", table[i*17+i2]);
		}
		printf("\n");
	}
}

int main(int argc, char * argv[]) {
	table = calloc(TABLE_SIZE , sizeof(int));
	InitialiserGraphique();
	CreerFenetre(100, 100, 700, 800);
	ChoisirCouleurDessin(CouleurParNom("black"));
	for (int i = 0; i < 17; i++) {
		for (int i2 = 0; i2 < 17; i2++) {
			DessinerRectangle(10 + 40*i, 10 + 40*i2, 40, 40);
			if (i != 16 && i2 != 16) AddButton(30 + 40*i, 30 + 40*i2, 40, 40, i2*17+i);
		}
	}

	AddButton(50, 720, 200, 50, -2); //Load
	AddButton(450, 720, 200, 50, -3); //Save

	DessinerRectangle(50, 720, 200, 50);
	DessinerRectangle(450, 720, 200, 50);

	EcrireTexte(120, 755, "Load", 2);
	EcrireTexte(520, 755, "Save", 2);

	int turn = 0;

	do {
		if (DrawNextFrame()) {
			if (SourisCliquee()) {
				int BT = GetButton(_X, _Y);
				if (BT != -1) {
					if (BT >= 0) {
						if (turn == 0) {
							turn = 1;
							table[BT] = 1;
						} else {
							turn = 0;
							table[BT] = 2;
						}

						for (int i = 0; i < 16; i++) {
							for (int i2 = 0; i2 < 16; i2++) {
								if (table[i2*17+i] == 1) {
									SetColor(255, 255, 255);
									RemplirRectangle(35 + 40*i, 35 + 40*i2, 30, 30);
									SetColor(0, 0, 0);
									DessinerRectangle(35 + 40*i, 35 + 40*i2, 30, 30);
								} else if (table[i2*17+i] == 2) {
									RemplirRectangle(35 + 40*i, 35 + 40*i2, 30, 30);
								}
							}
						}
					} else {
						if (BT == -2) loadGame();
						else if (BT == -3) saveGame();
					}
				}
			}
		}
	} while (1);
	FermerGraphique();
	return EXIT_SUCCESS;
}
