Форум программистов
 
О проблемах, например, с регистрацией пишите сюда - alarforum@yandex.ru, проверяйте папку спам! Обязательно пройдите активизацию e-mail, а тут можно восстановить пароль.

Вернуться   Форум программистов > .NET > Windows Forms
Регистрация

Восстановить пароль
Повторная активизация e-mail

Здесь нужно купить рекламу за 20 тыс руб в месяц! ) пишите сюда - alarforum@yandex.ru
Без учёта ботов - 20000 человек в день, 350000 в месяц.

Ответ
 
Опции темы
Старый 19.05.2020, 17:27   #1
Brean
Новичок
Джуниор
 
Регистрация: 19.05.2020
Сообщений: 3
По умолчанию Генерация препятствий в игре

Написал змейку, но с одним справиться не могу. Проблемы с drawwall, они исчезают после поедания еды, добавил еще drawwall в hit food, но оно просто рисует новые стены. Но мне нужно чтобы они перегенерировались при переходе на новый уровень(или вообще не перегенерировались). Также не знаю, как сделать так, чтобы при врезании в любую из стен игра заканчивалась.Пожалуйста, помогите
Код:
namespace Snake
{public partial class Snake : Form
{Timer myTimer = new Timer();
Timer myTimer2 = new Timer();
PictureBox[] snakeParts;
int snakesize = 3;
Point location = new Point(120, 120);
string direction = "Right";
bool changingDirection = false;
PictureBox food = new PictureBox();
Point foodlocation = new Point(0, 0);
PictureBox[] wallparts;
double a = 15;
int level = 1;
public Snake()
{InitializeComponent();}
void myTimer_Tick(object sender, EventArgs e)
{int currentScores = Int32.Parse(Score_count.Text);
int newScore = currentScores + 1;
Score_count.Text = newScore + "";
int currenttime = Int32.Parse(timelabel.Text);
int newtime = currenttime - 1;
timelabel.Text = newtime + "";}
void myTimer2_Tick(object sender, EventArgs e)
{GamePanel.Controls.Remove(food);drawfood();}
private void button2_Click(object sender, EventArgs e)
{stopgame();}
private void Start_Click(object sender, EventArgs e)
{//play again
GamePanel.Controls.Clear();
snakeParts = null;
Score_count.Text = "0";
level_count.Text = "1";
fruit_count.Text = "0";
snakesize = 3;
direction = "Right";
location = new Point(120, 120);
//start game
drawsnake();
drawfood();
drawwall();
level_count.Text = "1";
timer1.Start();
//control
trackBar1.Enabled = false;
Start.Enabled = false;
namebox.Enabled = false;
//enable pause
Pause.Enabled = true;
// timer +1 on
myTimer.Interval = 1000;myTimer.Enabled = true;
myTimer.Tick += myTimer_Tick;myTimer.Start();       
//snake long label
longlabel.Text = snakesize + "";}
private void drawsnake()
{snakeParts = new PictureBox[snakesize];
//one part after another
for (int i = 0; i < snakesize; i++)
{snakeParts[i] = new PictureBox();
snakeParts[i].Size = new Size(15, 15);
snakeParts[i].BackColor = Color.LawnGreen;
snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
snakeParts[i].Location = new Point(location.X - (15 * i), location.Y);
GamePanel.Controls.Add(snakeParts[i]);}}
private void drawfood()
{Random rnd = new Random();
int Xrand = rnd.Next(38) * 15;
int Yrand = rnd.Next(30) * 15;
bool isOnSnake = true;
// chek food on snake
while (isOnSnake){for (int i = 0; i < snakesize; i++)
{if (snakeParts[i].Location == new Point(Xrand, Yrand))
{Xrand = rnd.Next(38) * 15;
Yrand = rnd.Next(30) * 15;}
else{isOnSnake = false;}}}
//draw food
if (isOnSnake == false)
{int col = rnd.Next(1, 6);
foodlocation = new Point(Xrand, Yrand);
food.Size = new Size(15, 15);
if (col == 1)
{food.BackColor = Color.OrangeRed;}
 //.... other colors
else
{food.BackColor = Color.Red;}
food.BorderStyle = BorderStyle.FixedSingle;
food.Location = foodlocation;
GamePanel.Controls.Add(food);
myTimer2.Interval = 30000;myTimer2.Enabled = true;
myTimer2.Tick += myTimer2_Tick;myTimer2.Start();timelabel.Text = "30";}}
private void drawwall()
{Random rnd = new Random();
int numwall = rnd.Next(3, 10);
for (int a = 1; a < numwall; a++)
{int ranX = rnd.Next(50) * 15;
int ranY = rnd.Next(42) * 15;
int wallrnd = rnd.Next(2, 7);
wallparts = new PictureBox[wallrnd];
int xy = rnd.Next(1, 3);
if (xy == 1)
{for (int i = 0; i < wallrnd; i++)
{wallparts[i] = new PictureBox();
wallparts[i].Size = new Size(15, 15);
wallparts[i].BackColor = Color.Brown;
wallparts[i].BorderStyle = BorderStyle.FixedSingle;
wallparts[i].Location = new Point(ranX - (15 * i), ranY);
GamePanel.Controls.Add(wallparts[i]);} }
else {for (int i = 0; i < wallrnd; i++)
{wallparts[i] = new PictureBox();
wallparts[i].Size = new Size(15, 15);
wallparts[i].BackColor = Color.Brown;
wallparts[i].BorderStyle = BorderStyle.FixedSingle;
wallparts[i].Location = new Point(ranX, ranY - (15 * i));
GamePanel.Controls.Add(wallparts[i]);}}}}
private void trackBar1_Scroll(object sender, EventArgs e)
{//change time
intervaltimer1.Interval = 501 - (5 * trackBar1.Value);}
private void timer1_Tick(object sender, EventArgs e){move();}
private void move()
{Point point = new Point(0, 0);
//moving each part of snake
for (int i = 0; i < snakesize; i++)
{if (i == 0)
{ point = snakeParts[i].Location;
if (direction == "Left")
{snakeParts[i].Location = new Point(snakeParts[i].Location.X - 15, snakeParts[i].Location.Y);}
if (direction == "Right")
{snakeParts[i].Location = new Point(snakeParts[i].Location.X + 15, snakeParts[i].Location.Y);}
if (direction == "Top")
{snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y - 15);}
if (direction == "Down")
{snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y + 15);}}
else
{Point newPoint = snakeParts[i].Location;
snakeParts[i].Location = point;
point = newPoint;}}
//hit food
if (snakeParts[0].Location == foodlocation)
{eatfood();drawfood();drawwall();}
//if snake hits wall
if (snakeParts[0].Location.X < 0 || snakeParts[0].Location.X >= 850 || snakeParts[0].Location.Y < 0 || snakeParts[0].Location.Y >= 480)
{stopgame();}
// snake eat itself
for (int i = 3; i < snakesize; i++)
{if(snakeParts[0].Location==snakeParts[i].Location)
{stopgame();}}
changingDirection = false;}
//control snake
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{if (keyData == (Keys.Up) && direction != "Down" && changingDirection != true) {
direction = "Top";
changingDirection = true;}
if (keyData == (Keys.Down) && direction != "Top" && changingDirection != true)
{direction = "Down";
changingDirection = true;}
if (keyData == (Keys.Left) && direction != "Right" && changingDirection != true)
{direction = "Left";
changingDirection = true;}
if (keyData == (Keys.Right) && direction != "Left" && changingDirection != true)
{direction = "Right";
changingDirection = true;}
return base.ProcessCmdKey(ref msg, keyData);}
private void eatfood()
{Random rnd = new Random();
int abrand = rnd.Next(1, 3);
 for (int ba = 1; ba <= abrand; ba++)
{snakesize++;
PictureBox[] oldsnake = snakeParts;
GamePanel.Controls.Clear();
snakeParts = new PictureBox[snakesize];
for (int i = 0; i < snakesize; i++)
{snakeParts[i] = new PictureBox();
snakeParts[i].Size = new Size(15, 15);
snakeParts[i].BackColor = Color.LawnGreen;
snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
if (i == 0)
{snakeParts[i].Location = foodlocation;}
else{snakeParts[i].Location = oldsnake[i - 1].Location;}
GamePanel.Controls.Add(snakeParts[i]);}
myTimer2.Enabled = false;
myTimer2.Stop();
if (snakesize >= a)
{GamePanel.Controls.Clear();
snakeParts = null; level ++;
level_count.Text = level + "";
snakesize = 3;
direction = "Right";
location = new Point(120, 120);
drawsnake();drawfood();drawwall();
double a1 = a + a / 3;
a = a1;}}
int currentScores = Int32.Parse(Score_count.Text);
 int newScore = currentScores + 50;
Score_count.Text = newScore+"";
int currentfruits = Int32.Parse(fruit_count.Text);
int newScorefr = currentfruits + 1;
fruit_count.Text = newScorefr + "";
int currentlong = Int32.Parse(longlabel.Text);
int newScoreln = snakesize;
longlabel.Text = newScoreln + ""}
private void stopgame()
{timer1.Stop();
Start.Enabled = true;
trackBar1.Enabled = true;
Pause.Enabled = false;
namebox.Enabled = true;
myTimer.Stop();
//game over text
Label over = new Label();
over.Text = "Game\nOver";
over.ForeColor = Color.Maroon;
over.Font = new Font("AgitProp", 100);
over.Size = over.PreferredSize;
over.TextAlign = ContentAlignment.MiddleCenter;
int X = GamePanel.Width / 2 - over.Width / 2;
int Y = GamePanel.Height / 2 - over.Height / 2;
over.Location = new Point(X, Y);
GamePanel.Controls.Add(over);
over.BringToFront();}}}
Brean вне форума Ответить с цитированием
Старый 29.05.2020, 13:25   #2
WorldMaster
Старожил
 
Аватар для WorldMaster
 
Регистрация: 25.08.2011
Сообщений: 2,541
По умолчанию

Раз не можете объяснить почему так происходит значит где то слямзили код и не понимаете как он работает. Не поверю что создатель этого кода не способен понять почему каждый раз обновляется окружение и стены.

вот вам решение.

Код:
List<PictureBox> walsBlocks = new List<PictureBox>();

private void drawwall(bool GenNew)
        {
            if (GenNew)
            {
                Random rnd = new Random();
                walsBlocks.Clear();
                int numwall = rnd.Next(3, 10);
                for (int a = 1; a < numwall; a++)
                {
                    int ranX = rnd.Next(50) * 15;
                    int ranY = rnd.Next(42) * 15;
                    int wallrnd = rnd.Next(2, 7);
                    wallparts = new PictureBox[wallrnd];
                    int xy = rnd.Next(1, 3);
                    if (xy == 1)
                    {
                        for (int i = 0; i < wallrnd; i++)
                        {
                            wallparts[i] = new PictureBox();
                            wallparts[i].Size = new Size(15, 15);
                            wallparts[i].BackColor = Color.Brown;
                            wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                            wallparts[i].Location = new Point(ranX - (15 * i), ranY);
                            GamePanel.Controls.Add(wallparts[i]);
                            walsBlocks.Add(wallparts[i]);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < wallrnd; i++)
                        {
                            wallparts[i] = new PictureBox();
                            wallparts[i].Size = new Size(15, 15);
                            wallparts[i].BackColor = Color.Brown;
                            wallparts[i].BorderStyle = BorderStyle.FixedSingle;
                            wallparts[i].Location = new Point(ranX, ranY - (15 * i));
                            GamePanel.Controls.Add(wallparts[i]);
                            walsBlocks.Add(wallparts[i]);
                        }
                    }
                }
            }
            else
            {
                foreach (var wall in walsBlocks)
                    GamePanel.Controls.Add(wall);
            }
        }

private void eatfood()
        {
            Random rnd = new Random();
            int abrand = rnd.Next(1, 3);
            for (int ba = 1; ba <= abrand; ba++)
            {
                snakesize++;
                PictureBox[] oldsnake = snakeParts;
                GamePanel.Controls.Clear();
                snakeParts = new PictureBox[snakesize];
                for (int i = 0; i < snakesize; i++)
                {
                    snakeParts[i] = new PictureBox();
                    snakeParts[i].Size = new Size(15, 15);
                    snakeParts[i].BackColor = Color.LawnGreen;
                    snakeParts[i].BorderStyle = BorderStyle.FixedSingle;
                    if (i == 0)
                    { snakeParts[i].Location = foodlocation; }
                    else { snakeParts[i].Location = oldsnake[i - 1].Location; }
                    GamePanel.Controls.Add(snakeParts[i]);
                }
                myTimer2.Enabled = false;
                myTimer2.Stop();
                if (snakesize >= a)
                {
                    GamePanel.Controls.Clear();
                    snakeParts = null; level++;
                    level_count.Text = level + "";
                    snakesize = 3;
                    direction = "Right";
                    location = new Point(120, 120);
                    drawsnake();
                    drawfood();
                    drawwall(true);
                    double a1 = a + a / 3;
                    a = a1;
                }
            }
            int currentScores = Int32.Parse(Score_count.Text);
            int newScore = currentScores + 50;
            Score_count.Text = newScore + "";
            int currentfruits = Int32.Parse(fruit_count.Text);
            int newScorefr = currentfruits + 1;
            fruit_count.Text = newScorefr + "";
            int currentlong = Int32.Parse(longlabel.Text);
            int newScoreln = snakesize;
            longlabel.Text = newScoreln + "";

        }

private void move()
        {
            Point point = new Point(0, 0);
            //moving each part of snake
            for (int i = 0; i < snakesize; i++)
            {
                if (i == 0)
                {
                    point = snakeParts[i].Location;
                    if (direction == "Left")
                    { snakeParts[i].Location = new Point(snakeParts[i].Location.X - 15, snakeParts[i].Location.Y); }
                    if (direction == "Right")
                    { snakeParts[i].Location = new Point(snakeParts[i].Location.X + 15, snakeParts[i].Location.Y); }
                    if (direction == "Top")
                    { snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y - 15); }
                    if (direction == "Down")
                    { snakeParts[i].Location = new Point(snakeParts[i].Location.X, snakeParts[i].Location.Y + 15); }
                }
                else
                {
                    Point newPoint = snakeParts[i].Location;
                    snakeParts[i].Location = point;
                    point = newPoint;
                }
            }
            //hit food
            if (snakeParts[0].Location == foodlocation)
            {
                eatfood();
                drawfood();
                drawwall(false);
            }
            //if snake hits wall
            if (snakeParts[0].Location.X < 0 || snakeParts[0].Location.X >= 850 || snakeParts[0].Location.Y < 0 || snakeParts[0].Location.Y >= 480)
            {
                stopgame();
            }
            // snake eat itself
            for (int i = 3; i < snakesize; i++)
            {
                if (snakeParts[0].Location == snakeParts[i].Location)
                { stopgame(); }
            }
            changingDirection = false;
        }
Skype - wmaster_s E-Mail - WorldMasters@gmail.com
Работаем по 3 критериям - быстро, качественно, недорого. Заказчик выбирает любые два.
WorldMaster вне форума Ответить с цитированием
Ответ

Здесь нужно купить рекламу за 20 тыс руб в месяц! ) пишите сюда - alarforum@yandex.ru
Без учёта ботов - 20000 человек в день, 350000 в месяц.

Опции темы


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Какие знания по php и mysql нужно иметь, что бы в игре сделать такой бой в онлайн текстовой игре jonikster Общие вопросы Web 4 15.06.2016 18:10
Обход динамичных препятствий CrHD Gamedev - cоздание игр: Unity, OpenGL, DirectX 4 19.05.2009 22:10


Проекты отопления, пеллетные котлы, бойлеры, радиаторы
интернет магазин respective.ru
Пеллетный котёл Emtas
котлы EMTAS