Я написал свою програмку(Cапер), но у меня не выводит данные из файла в DataGridView. Данные записываю в класс, а объекты класса записываю в List. Потом провожу сериализацию(в основной форме) и десериализацию в форме, где вывожу таблицу рекордов. Программа работает, игра - играется, компиляор - не ругается. Единственное, что не так: то-ли вывод данных в таблицу не работает, то ли класс данные не собирает и не записывает. Помогите, пожалуйста.
Во код основной формы:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO.Compression;
using System.IO;
namespace Minesweeper
{
public partial class Form1 : Form
{
int height = 7;
int width = 7;
int distanseBetweenButtons = 22;
ButtonExtended[,] allButtons;
int amount_buttons;
int EmptyCell;
Data_achievements result = new Data_achievements("", "", "");
Stopwatch stopWatch = new Stopwatch();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GenerateField();
}
void GenerateField ()
{
groupBox1.Text = width.ToString() + " x " + height.ToString();
stopWatch.Start();
result.sizeOf_Field = width.ToString() + "x" + height.ToString();//** size of field remembering
amount_buttons = height * width;
int numerator_mineOrNot = 0;
allButtons = new ButtonExtended[width, height];
Random rng = new Random();
for (int x = 10; (x - 10) < width * distanseBetweenButtons; x += distanseBetweenButtons)
{
for (int y = 20; (y - 20) < height * distanseBetweenButtons; y += distanseBetweenButtons)
{
ButtonExtended button = new ButtonExtended();
button.Location = new Point(x, y);
button.Size = new Size(21, 21);
if (rng.Next(0, 101) < 20)
{
button.isBomb = true;
numerator_mineOrNot++;
}
allButtons[(x - 10) / distanseBetweenButtons, (y - 20) / distanseBetweenButtons] = button; //We put our created buttons in array
groupBox1.Controls.Add(button);
//creating field and checking on mine
EmptyCell = amount_buttons - numerator_mineOrNot;
button.Click += new EventHandler(FieldClick);
}
}
}
void FieldClick(object sender, EventArgs e)
{
EmptyCell--;
//function which will call with each click on button
ButtonExtended button = (ButtonExtended)sender;
if(EmptyCell == 0)// win condition
{
EmptyFieldClick(button);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if (allButtons[x, y].isBomb)
{
allButtons[x, y].Text = "*";
}
}
}
stopWatch.Stop();
TimeSpan result_time = stopWatch.Elapsed;
result.time = String.Format("{0:00}:{1:00}:{2:00}", result_time.Hours, result_time.Minutes, result_time.Seconds);
request Request_form = new request();
Request_form.Show();
Achievements_recording(result);
Disactiveted();
}
if(button.isBomb == true)
{
stopWatch.Stop();
Explode(button);
}
else
{
EmptyFieldClick(button);
button.Enabled = false;
}
}
void Explode(ButtonExtended button)
{
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
if (allButtons[x,y].isBomb)
{
allButtons[x, y].Text = "*";
}
}
}
Disactiveted();
MessageBox.Show("You lose!");
}
void EmptyFieldClick(ButtonExtended button)
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
if(allButtons[x,y] == button)
{
button.Text = "" + CountBombsAround(x, y);
}
}
}
}
int CountBombsAround (int xB, int yB)
{
int bombsCount = 0;
for (int x = xB - 1; x <= xB + 1 ; x++)
{
for (int y = yB - 1; y <= yB + 1; y++)
{
if(x >= 0 && x < width && y >= 0 && y < height)
{
if(allButtons[x, y].isBomb)
{
bombsCount++;
}
}
}
}
return bombsCount;
}
private void x10ToolStripMenuItem_Click(object sender, EventArgs e)
{
Activeted();
groupBox1.Controls.Clear();
//size for form (255; 300)
width = 7;
height = 7;
GenerateField();
}
private void x5ToolStripMenuItem_Click(object sender, EventArgs e)
{
Activeted();
groupBox1.Controls.Clear();
//size for form (190; 228)
width = 10;
height = 10;
GenerateField();
}
private void x15ToolStripMenuItem_Click(object sender, EventArgs e)
{
Activeted();
groupBox1.Controls.Clear();
//size for form (365; 405)
width = 15;
height = 15;
GenerateField();
}
void Disactiveted ()
{
groupBox1.Enabled = false;
}
void Activeted ()
{
groupBox1.Enabled = true;
}
private void рекордиToolStripMenuItem_Click(object sender, EventArgs e)//**
{
Form2 _achievements = new Form2();
_achievements.Show();
_achievements.Size = new Size(250, 250);
}
void Achievements_recording(Data_achievements results)//**
{
List<Data_achievements> recording = new List<Data_achievements>();
using (request userNAME = new request())
{
result.user_name = userNAME.userName;
}
recording.Add(results);
var formatter = new BinaryFormatter();
// Запись
using (var fileStream = new FileStream("Minesweep_result.bin", FileMode.Create))
using (var zipStream = new GZipStream(fileStream, CompressionMode.Compress))
{
formatter.Serialize(zipStream, recording);
}
}
}
}
Вот код класса, который собирает данные:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Minesweeper
{
[Serializable]
class Data_achievements
{
private string User_name { get; set; }
private string Time { get; set; }
private string SizeOf_Field { get; set; }
public string user_name { get; set; }
public string time { get; set; }
public string sizeOf_Field { get; set; }
public Data_achievements (string user_name, string time, string sizeOf_Field)
{
this.user_name = user_name;
this.time = time;
this.sizeOf_Field = sizeOf_Field;
}
}
}
Здесь код формы которая выплывает при победе и запрашивает имя игрока:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Minesweeper
{
public partial class request : Form
{
public string userName
{
get { return textBox1.Text; }
}
public request()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Hide();
}
}
}
А здесь код формы, которая десериализирует файл и выводит данные в DataGridView:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO.Compression;
using System.IO;
namespace Minesweeper
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
void data_output()
{
var formatter = new BinaryFormatter();
List<Data_achievements> gift = new List <Data_achievements>();
// Чтение
using (var fileStream = new FileStream("data.bin",
FileMode.Open))
using (var zipStream = new GZipStream(fileStream, CompressionMode.Decompress))
{
gift = (List<Data_achievements>)formatter.Deserialize(zipStream);
}
//create table with name: "Results"
DataTable table = new DataTable("Результати");
//create objects DataColumn
var user_name = new DataColumn("Ім'я");
var time = new DataColumn("Час");
var field = new DataColumn("Поле");
//add objects DataColumn in DataTable
table.Columns.Add(user_name);
table.Columns.Add(time);
table.Columns.Add(field);
//for each elements add row in table
foreach (Data_achievements results in gift)
{
DataRow row = table.NewRow();
row["Ім'я"] = results.user_name;
row["Час"] = results.time;
row["Поле"] = results.sizeOf_Field;
}
dataGridView1.DataSource = table;
}
}
}
UPD: прошу прощения за дезинформацию, знаний LINQ недостаточно что бы сделать коректный запрос через реалмЯ это немного поздно понял
Хочу сделать универсальный метод выгружающий таблицу в pdf