Змінюй хід війни! Допомагай ЗСУ!

[С#] Нужна помощь по сапёру (игра)

🔴 21:26 Повітряна тривога в Харків.обл.
  • 🔴 21:26 Повітряна тривога в Харків.обл.
  • #21
  • 🔴 21:26 Повітряна тривога в Харків.обл.
  • #22
в общем у меня не получается сделать так чтобы в клетке писалось кол-во мин, которые рядом, не знаю что с этим сделать, у меня цифры выводяться после того как на мину напоришься - вобщем лажа... Напиши пожалуйста, мне завтра сдавать...
 
  • 🔴 21:26 Повітряна тривога в Харків.обл.
  • #23
private int status; // статус игры 0 - начало
// 1 - игра
// 2 - конец

enum'ом религия не позволяет пользоваться?
 
  • 🔴 21:26 Повітряна тривога в Харків.обл.
  • #24
скомпилил.
поиграл
не впечатлило. оно без циферок :D

в общем у меня не получается сделать так чтобы в клетке писалось кол-во мин, которые рядом, не знаю что с этим сделать, у меня цифры выводяться после того как на мину напоришься - вобщем лажа... Напиши пожалуйста, мне завтра сдавать...

ну хорошо, вот вариант с цифрами :)
Код:
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace SAPER2
{
    public class FormMain : Form
    {
        private const int CellWidth = 40;
        private const int CellHeight = 40;
        private readonly Font CellFont = new Font(FontFamily.GenericMonospace, 20F, FontStyle.Bold);
        
        private Random _rand = new Random();
        private CellState[,] _grid = null;
        
        
        
        
        public FormMain()
        {
            Paint += Form_Paint;
            MouseClick += Form_MouseClick;

            SetStyle(ControlStyles.Opaque, true);
            DoubleBuffered = true;
            FormBorderStyle = FormBorderStyle.FixedSingle;
            init(8, 8, 4);
        }

        private void init(int width, int height, int count)
        {
            _grid = new CellState[width, height];
            for(int i=0; i < width; i++)
                for(int j=0; j < height; j++)
                    _grid[i,j] = CellState.NotTestedFree;
            
            if (width * height < count) 
                count = width * height;

            for (int i = 0; i < count; i++)
            {
                int x,y;
                do
                {
                    x = _rand.Next(width);
                    y = _rand.Next(height);
                } while (_grid[x, y] != CellState.NotTestedFree);
                _grid[x, y] = CellState.NotTestedMine;
            }
            ClientSize = new Size(CellWidth * _grid.GetLength(0), CellHeight * _grid.GetLength(1));
            Invalidate();
        }

        private void drawGrid(Graphics g)
        {
            for (int x = 0; x < _grid.GetLength(0); x++)
                for (int y = 0; y < _grid.GetLength(1); y++)
                    drawCell(g, x, y);
        }

        private void drawCell(Graphics g, int x, int y)
        {
            CellState value = _grid[x, y];
            Rectangle rect = new Rectangle(x * CellWidth, y * CellHeight, CellWidth, CellHeight);
            
            Rectangle subRect = new Rectangle(rect.X + 1, rect.Y + 1, rect.Width - 2, rect.Height - 2);
            g.FillRectangle(Brushes.Silver, rect);
            switch(value)
            {
                case CellState.NotTestedFree:
                case CellState.NotTestedMine:
                    g.FillRectangle(Brushes.Gray, subRect);
                    break;
                case CellState.TestedFree:
                    g.FillRectangle(Brushes.Green, subRect);
                    drawMineCount(g, subRect, x, y, CellFont);
                    break;
                case CellState.TestedMine:
                    g.FillEllipse(Brushes.Black, subRect);
                    break;
                case CellState.TestedMineExplode:
                    g.FillRectangle(Brushes.Red, subRect);
                    g.FillEllipse(Brushes.Black, subRect);
                    break;
            }
        }

        private void drawMineCount(Graphics g, Rectangle rect, int x, int y, Font font)
        {
            int mineCount = getMineCount(x, y);
            if (mineCount < 1)
                return;
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            g.DrawString(mineCount.ToString(), font, Brushes.Red, rect, sf);
        }

        private int getMineCount(int x, int y)
        {
            int count = 0;
            if (y > 0)
            {
                if (x > 0 && testIsMine(x - 1, y - 1)) count++;
                if (testIsMine(x, y - 1)) count++;
                if (x < _grid.GetLength(0)-1 && testIsMine(x + 1, y - 1)) count++;
            }

            if (x > 0 && testIsMine(x - 1, y)) count++;
            if (x < _grid.GetLength(0)-1 && testIsMine(x + 1, y)) count++;

            if (y < _grid.GetLength(1)-1)
            {
                if (x > 0 && testIsMine(x - 1, y + 1)) count++;
                if (testIsMine(x, y + 1)) count++;
                if (x < _grid.GetLength(0)-1 && testIsMine(x + 1, y + 1)) count++;
            }
            return count;
        }

        private bool testIsMine(int x, int y)
        {
            CellState value = _grid[x, y];
            return value == CellState.NotTestedMine || value == CellState.TestedMine || value == CellState.TestedMineExplode;
        }

        private StepResult check(int x, int y)
        {
            StepResult result = StepResult.Win;
            switch (_grid[x, y])
            {
                case CellState.NotTestedFree:
                    _grid[x, y] = CellState.TestedFree;
                    break;
                case CellState.NotTestedMine:
                    for (int i = 0; i < _grid.GetLength(0); i++)
                        for (int j = 0; j < _grid.GetLength(1); j++)
                        {
                            if (_grid[i, j] == CellState.NotTestedMine)
                                _grid[i, j] = CellState.TestedMine;
                        }
                    _grid[x, y] = CellState.TestedMineExplode;
                    result = StepResult.Lose;
                    break;
            }
            if (result != StepResult.Lose)
                for (int i = 0; i < _grid.GetLength(0); i++)
                    for (int j = 0; j < _grid.GetLength(1); j++)
                        if (_grid[i, j] == CellState.NotTestedFree)
                        {
                            result = StepResult.None;
                            break;
                        }
            Invalidate();
            return result;
        }

        protected void Form_Paint(object sender, PaintEventArgs e)
        {
            drawGrid(e.Graphics);
        }

        protected void Form_MouseClick(object sender, MouseEventArgs e)
        {
            int x = e.X / CellWidth;
            int y = e.Y / CellHeight;
            if (x >= 0 && y >= 0 && x < _grid.GetLength(0) && y < _grid.GetLength(1))
            {    
                StepResult result = check(x, y);
                if (result == StepResult.Lose || result == StepResult.Win)
                {
                    MessageBox.Show("You are " + result.ToString());
                    init(8, 8, 4);
                }
            }
        }
    }

    public enum CellState
    {
        NotTestedFree,
        TestedFree,
        NotTestedMine,
        TestedMine,
        TestedMineExplode,
    }
    public enum StepResult
    {
        None,
        Lose,
        Win,
    }

    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }
    }
}
 
  • 🔴 21:26 Повітряна тривога в Харків.обл.
  • #25
Спасибо большое!!! Вот кстати моя попытка это реализовать (делал до того как увидел этот код). Вобщем алгоритм открытия пустых клеток я возьму из своего, а циферки с твоего (Klez).

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication2Saper
{

public partial class Saper1 : Form
{
private const int CellWidth = 40;
private const int CellHeight = 40;

private Random _rand = new Random();
private CellState[,] _grid = null;

int X, Y;


public Saper1()
{
InitializeComponent();

Paint += Form_Paint;
MouseClick += Form_MouseClick;

SetStyle(ControlStyles.Opaque, true);
DoubleBuffered = true;
FormBorderStyle = FormBorderStyle.FixedSingle;
init(10, 10, 15);
}

private void DrawText(Rectangle rect, String s, Graphics g)
{
g.DrawString(s, new Font("Times New Roman", 23),Brushes.Black,(RectangleF)rect);
}

private int Check (int t, int t1)
{
int k = 0;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
{
if (j != 0 || i != 0)
{
if (_grid[t + i, t1 + j] == CellState.NotTestedMine) k++;
}

}
return k;
}

private void init(int width, int height, int count)
{
_grid = new CellState[width, height];
for (int i = 0; i < width; i++)
for (int j = 0; j < height; j++)
_grid[i, j] = CellState.NotTestedFree;

if (width * height < count)
count = width * height;

for (int i = 0; i < count; i++)
{
int x, y;
do
{
x = _rand.Next(width-2)+1;
y = _rand.Next(height-2)+1;
} while (_grid[x, y] != CellState.NotTestedFree);
_grid[x, y] = CellState.NotTestedMine;
}
ClientSize = new Size(CellWidth * (_grid.GetLength(0)-2), CellHeight * (_grid.GetLength(1)-2));
Invalidate();
}

private void drawGrid(Graphics g)
{
for (int x = 1; x < _grid.GetLength(0)-1; x++)
for (int y = 1; y < _grid.GetLength(1)-1; y++)
drawCell(g, new Rectangle((x-1) * CellWidth, (y-1) * CellHeight, CellWidth, CellHeight), _grid[x, y], x, y);
}

private void drawCell(Graphics g, Rectangle rect, CellState value, int x, int y)
{
int k = 0;
Rectangle subRect = new Rectangle(rect.X + 1, rect.Y + 1, rect.Width - 2, rect.Height - 2);
g.FillRectangle(Brushes.Silver, rect);
switch (value)
{
case CellState.NotTestedFree:
case CellState.NotTestedMine:
g.FillRectangle(Brushes.Gray, subRect);
break;
case CellState.TestedFree:
g.FillRectangle(Brushes.Green, subRect);

k = Check(x, y);
DrawText(subRect, k.ToString(), g);

if (k == 0)
{
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
{
if (j != 0 || i != 0)
{
if (_grid[x + i, y + j] == CellState.NotTestedFree) _grid[x + i, y + j] = CellState.TestedFree;
}

}
Invalidate();
}




break;
case CellState.TestedMine:
g.FillEllipse(Brushes.Black, subRect);
break;
case CellState.TestedMineExplode:
g.FillRectangle(Brushes.Red, subRect);
g.FillEllipse(Brushes.Black, subRect);
break;
}
}

private StepResult check(int x, int y)
{
StepResult result = StepResult.Win;
switch (_grid[x, y])
{
case CellState.NotTestedFree:
_grid[x, y] = CellState.TestedFree;
break;
case CellState.NotTestedMine:
for (int i = 1; i < _grid.GetLength(0)-1; i++)
for (int j = 1; j < _grid.GetLength(1)-1; j++)
{
if (_grid[i, j] == CellState.NotTestedMine)
_grid[i, j] = CellState.TestedMine;
}
_grid[x, y] = CellState.TestedMineExplode;
result = StepResult.Lose;
break;
}
if (result != StepResult.Lose)
for (int i = 1; i < _grid.GetLength(0)-1; i++)
for (int j = 1; j < _grid.GetLength(1)-1; j++)
if (_grid[i, j] == CellState.NotTestedFree)
{
result = StepResult.None;
break;
}
Invalidate();
return result;
}

protected void Form_Paint(object sender, PaintEventArgs e)
{
drawGrid(e.Graphics);

}

protected void Form_MouseClick(object sender, MouseEventArgs e)
{
int x = e.X / CellWidth +1;
int y = e.Y / CellHeight +1;
X = x;
Y = y;
if (x >= 0 && y >= 0 && x < _grid.GetLength(0) && y < _grid.GetLength(1))
{
StepResult result = check(x, y);
if (result == StepResult.Lose || result == StepResult.Win)
{


MessageBox.Show("You " + result.ToString() + " !!! Ещё раз?", "Результат игры");
init(10, 10, 10);
}
}
}
}

public enum CellState
{
NotTestedFree,
TestedFree,
NotTestedMine,
TestedMine,
TestedMineExplode,
}
public enum StepResult
{
None,
Lose,
Win,
}
}
 
  • 🔴 21:26 Повітряна тривога в Харків.обл.
  • #26
Назад
Зверху Знизу