Вот функция:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
if (SpielField[ypos + 1][xpos] != '#')
{
SpielField[ypos].Replace('@', ' ');
ypos++;
string temp = new string(SpielField[ypos].ToCharArray(), 0, xpos);
temp += '@';
temp += SpielField[ypos].Substring(xpos + 1);
SpielField[ypos] = temp;
}
}
}
и вот как я добавил ее в события в конструкторе:
this.KeyDown += Form1_KeyDown;
Я реализую функции winforms для ConsoleApp, но это делает нет разницы я верю.
Вот полный код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing;
namespace MazeProject
{
class Form1 : Form
{
string[] SpielField;
int column;
int line;
int xpos;
int ypos;
public Form1(int c,int l,string[] input)
{
this.Width = 800;
this.Height = 800;
this.column = c;
this.line = l;
this.KeyPreview = true;
SpielField = new string[column];
SpielField = input;
for (int i = 0; i < column; i++) {
for(int j = 0; j < line; j++)
{
if(SpielField[i][j] == '@')
{
xpos = j;
ypos = i;
break;
}
}
}
this.Paint += Form1_Paint;
this.KeyDown += Form1_KeyDown;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Console.WriteLine(column);
for (int i = 0; i < column; i++)
{
Font f = new Font(FontFamily.GenericMonospace, 20, FontStyle.Regular);
Brush b = new SolidBrush(Color.Black);
e.Graphics.DrawString(SpielField[i], f, b , 10, 650-(i+2)*40);
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
if (SpielField[ypos + 1][xpos] != '#')
{
SpielField[ypos].Replace('@', ' ');
ypos++;
string temp = new string(SpielField[ypos].ToCharArray(), 0, xpos);
temp += '@';
temp += SpielField[ypos].Substring(xpos + 1);
SpielField[ypos] = temp;
}
}
}
}
class Program
{
[STAThread]
static void Main(string[] args)
{
string filePath = System.IO.Directory.GetCurrentDirectory() + "\\maze.txt";
string[] input = File.ReadAllLines(filePath);
int l = Convert.ToInt32(input[0]);
int c = Convert.ToInt32(input[1]);
string[] data = new string[c];
for(int i = 0; i < c; i++)
{
data[i] = input[i + 2];
}
Form1 game = new Form1(c, l, data);
Console.WriteLine(c);
Console.WriteLine(l);
Application.EnableVisualStyles();
Application.Run(game);
Console.ReadLine();
}
}
}