Доработана угадайка, добавлена змейка

This commit is contained in:
2024-12-22 11:40:58 +04:00
parent d1ebd91521
commit f7342093af
10 changed files with 385 additions and 406 deletions

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace ProgLab1.GUI
{
public static class ExitDialog
public static class Dialogs
{
public static bool Exit()
{
@@ -18,5 +18,11 @@ namespace ProgLab1.GUI
}
return false;
}
public static bool GameOver(string message)
{
DialogResult result = MessageBox.Show(message, "Игра окончена", MessageBoxButtons.OK);
return result == DialogResult.OK;
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using laba3.Subprograms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -79,23 +80,22 @@ namespace ProgLab1.GUI
{
input.BackColor = SystemColors.Window;
double inputNum = double.Parse(input.Text);
Console.WriteLine(Math.Abs(answer - inputNum));
if (Math.Abs(answer - inputNum) < 0.1)
if (Math.Abs(answer - inputNum) < 0.01)
{
Dialogs.GameOver("Победа!\nВы угадали значение функции!");
this.Close();
}
else
{
tryes--;
}
if(tryes <= 0)
{
this.Close();
tryCount.Text = $"Количество попыток: {tryes}";
if (tryes <= 0)
{
Dialogs.GameOver($"Попытки кончились :(\nВерный ответ был {answer:F2}");
this.Close();
}
}
}
tryCount.Text = $"Количество попыток: {tryes}";
}
}
}

View File

@@ -131,21 +131,21 @@ namespace ProgLab1.GUI
game.setArgs(a, b);
bool funcValid = game.CheckArgs();
if (!funcValid)
{
error.Text = "Функция не определена при этих аргументах";
}
else
{
error.Text = "";
game.ComputeResult();
guessForm.SetAnswer(game.GetResult());
this.Hide();
guessForm.Show();
}
}
if (!(isAValid && isBValid))
else
{
// Если есть ошибка, подсвечиваем поля
if (!isAValid) textBoxA.BackColor = Color.Red;

View File

@@ -22,7 +22,7 @@ namespace ProgLab1.GUI
this.Width = 800;
this.Height = 600;
AddMenu(consoleMenu);
this.FormClosing += new FormClosingEventHandler((object sender, FormClosingEventArgs e) => { e.Cancel = !ExitDialog.Exit(); });
this.FormClosing += new FormClosingEventHandler((object sender, FormClosingEventArgs e) => { e.Cancel = !Dialogs.Exit(); });
}
public MenuForm(Menu consoleMenu, Action onAny)
@@ -32,7 +32,7 @@ namespace ProgLab1.GUI
this.Width = 800;
this.Height = 600;
AddMenu(consoleMenu, onAny);
this.FormClosing += new FormClosingEventHandler((object sender, FormClosingEventArgs e) => { e.Cancel = !ExitDialog.Exit(); });
this.FormClosing += new FormClosingEventHandler((object sender, FormClosingEventArgs e) => { e.Cancel = !Dialogs.Exit(); });
}
public void SwitchToForm(Form form)

39
GUI/SnakeForm.Designer.cs generated Normal file
View File

@@ -0,0 +1,39 @@
namespace ProgLab1.GUI
{
partial class SnakeForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "SnakeGUI";
}
#endregion
}
}

194
GUI/SnakeForm.cs Normal file
View File

@@ -0,0 +1,194 @@
using laba3.Subprograms;
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 static System.Formats.Asn1.AsnWriter;
namespace ProgLab1.GUI
{
public partial class SnakeForm : Form
{
private System.Windows.Forms.Timer gameTimer = new System.Windows.Forms.Timer();
private List<Point> snake = new List<Point>();
private Point food = Point.Empty;
private int tileSize = 20;
private string direction = "Right";
private string nextDirection = "Right";
private bool isGameOver = false;
private int score = 0;
private Level level;
private int sizex;
private int sizey;
private Random rand = new Random();
public SnakeForm(Level level, int sizex, int sizey, Form onCloseForm)
{
this.level = level;
this.sizex = sizex;
this.sizey = sizey;
InitializeComponent();
InitializeGame();
this.FormClosing += new FormClosingEventHandler((object sender, FormClosingEventArgs e) => {onCloseForm.Show();});
}
private void InitializeGame()
{
this.Text = "Snake Game";
this.ClientSize = new Size(sizex*tileSize, sizey*tileSize);
this.DoubleBuffered = true;
this.KeyDown += OnKeyDown;
this.Paint += OnPaint;
gameTimer.Interval = level switch
{
Level.Low => 250,
Level.Medium => 125,
Level.High => 50,
_ => 500,
}; ;
gameTimer.Tick += OnGameTick;
gameTimer.Start();
ResetGame();
}
private void ResetGame()
{
snake.Clear();
snake.Add(new Point(2, sizey/2)); // Initial snake head
snake.Add(new Point(1, sizey/2)); // Initial snake body
snake.Add(new Point(0, sizey/2)); // Initial snake tail
direction = "Right";
nextDirection = "Right";
isGameOver = false;
SpawnFood();
}
private void SpawnFood()
{
int maxX = sizex;
int maxY = sizey;
do
{
food = new Point(rand.Next(0, maxX), rand.Next(0, maxY));
} while (snake.Contains(food));
}
private void OnGameTick(object sender, EventArgs e)
{
if (isGameOver) return;
// Update direction
direction = nextDirection;
// Calculate new head position
Point newHead = snake[0];
switch (direction)
{
case "Up": newHead.Y--; break;
case "Down": newHead.Y++; break;
case "Left": newHead.X--; break;
case "Right": newHead.X++; break;
}
// Check collisions
if (newHead.X < 0 || newHead.Y < 0 ||
newHead.X >= sizex ||
newHead.Y >= sizey ||
snake.Contains(newHead))
{
isGameOver = true;
gameTimer.Stop();
Dialogs.GameOver($"Счёт: {score}");
this.Close();
return;
}
// Move snake
snake.Insert(0, newHead);
if (newHead == food)
{
SpawnFood();
addScore();
}
else
{
snake.RemoveAt(snake.Count - 1); // Remove tail
}
this.Invalidate(); // Redraw
}
private void OnPaint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
// Draw snake
foreach (Point p in snake)
{
DrawTile(g, p.X, p.Y, Brushes.Green);
}
// Draw food
DrawTile(g, food.X, food.Y, Brushes.Red);
// Draw grid (optional)
for (int x = 0; x < this.ClientSize.Width; x += tileSize)
{
for (int y = 0; y < this.ClientSize.Height; y += tileSize)
{
g.DrawRectangle(Pens.Gray, x, y, tileSize, tileSize);
}
}
}
private void DrawTile(Graphics g, int x, int y, Brush brush)
{
g.FillRectangle(brush, x * tileSize, y * tileSize, tileSize, tileSize);
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (isGameOver && e.KeyCode == Keys.R)
{
ResetGame();
gameTimer.Start();
return;
}
switch (e.KeyCode)
{
case Keys.Up: if (direction != "Down") nextDirection = "Up"; break;
case Keys.Down: if (direction != "Up") nextDirection = "Down"; break;
case Keys.Left: if (direction != "Right") nextDirection = "Left"; break;
case Keys.Right: if (direction != "Left") nextDirection = "Right"; break;
}
}
private void addScore()
{
score += level switch
{
Level.Low => 50,
Level.Medium => 100,
Level.High => 250,
_ => 1,
};
}
public enum Level
{
Low,
Medium,
High
}
}
}

120
GUI/SnakeForm.resx Normal file
View File

@@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>