Найти в Дзене
KNL Games

Код Игра Шарики в Windows Forms на C#

Введение Разработка игр — увлекательный процесс, который позволяет не только проявить творческие способности, но и углубить знания в области программирования. В этой статье мы рассмотрим создание простой, но интересной игры «Шарики» с использованием Windows Forms на языке C#. Шаг 1: настройка проекта Шаг 2: создание самой игры Код: using System; using System.Windows.Forms; namespace KNLGamesBallon { public partial class GameForm : Form { int speed; int score; Random rand = new Random(); bool gameOver; public GameForm() { InitializeComponent(); RestartGame(); } private void MainTimerEvent(object sender, EventArgs e) { txtScore.Text = "Очки: " + score; if (gameOver == true) { gameTimer.Stop(); txtScore.Text = "Score: " + score + " Игра окончена, нажмите Enter для перезапуска!"; } foreach (Control x in this.Controls) { if (x is PictureBox) { x.Top -= speed; if (x.Top < -100) { x.Top = rand.Next(700, 1000); x.Left = rand.Next(5, 500); } if ((string)x.Tag == "balloon") { if (x.Top < -50) {

Введение

Разработка игр — увлекательный процесс, который позволяет не только проявить творческие способности, но и углубить знания в области программирования. В этой статье мы рассмотрим создание простой, но интересной игры «Шарики» с использованием Windows Forms на языке C#.

Шаг 1: настройка проекта

  1. Откройте Visual Studio и создайте новый проект Windows Forms.
  2. Выберите шаблон проекта «Windows Forms App» и укажите имя проекта, например, «BallGame».
  3. Добавьте необходимые элементы управления на форму, такие как кнопки, текстовые поля и панели.

Шаг 2: создание самой игры Код:

using System;

using System.Windows.Forms;

namespace KNLGamesBallon

{

public partial class GameForm : Form

{

int speed;

int score;

Random rand = new Random();

bool gameOver;

public GameForm()

{

InitializeComponent();

RestartGame();

}

private void MainTimerEvent(object sender, EventArgs e)

{

txtScore.Text = "Очки: " + score;

if (gameOver == true)

{

gameTimer.Stop();

txtScore.Text = "Score: " + score + " Игра окончена, нажмите Enter для перезапуска!";

}

foreach (Control x in this.Controls)

{

if (x is PictureBox)

{

x.Top -= speed;

if (x.Top < -100)

{

x.Top = rand.Next(700, 1000);

x.Left = rand.Next(5, 500);

}

if ((string)x.Tag == "balloon")

{

if (x.Top < -50)

{

gameOver = true;

}

if (bomb.Bounds.IntersectsWith(x.Bounds))

{

x.Top = rand.Next(700, 1000);

x.Left = rand.Next(5, 500);

}

}

}

}

if (score > 5)

{

speed = 8;

}

if (score > 15 && score < 25)

{

speed = 12;

}

}

private void PopBalloon(object sender, EventArgs e)

{

if (gameOver == false)

{

var balloon = (PictureBox)sender;

balloon.Top = rand.Next(750, 1000);

balloon.Left = rand.Next(5, 500);

score += 1;

}

}

private void GoBoom(object sender, EventArgs e)

{

if (gameOver == false)

{

bomb.Image = Properties.Resources.Explosion;

gameOver = true;

}

}

private void KeyIsUp(object sender, KeyEventArgs e)

{

if (e.KeyCode == Keys.Enter && gameOver == true)

{

RestartGame();

}

}

private void RestartGame()

{

speed = 5;

score = 0;

gameOver = false;

bomb.Image = Properties.Resources.Bomba;

foreach (Control x in this.Controls)

{

if (x is PictureBox)

{

x.Top = rand.Next(750, 1000);

x.Left = rand.Next(5, 500);

}

}

gameTimer.Start();

}

}

}

using System.Windows.Forms;

using System.Drawing;

namespace KNLGamesBallon

{

partial class GameForm

{

private PictureBox bomb;

private PictureBox[] titles;

private Label txtScore;

private Timer gameTimer;

private System.ComponentModel.IContainer components = null;

protected override void Dispose(bool disposing)

{

if (disposing && (components != null))

{

components.Dispose();

}

base.Dispose(disposing);

}

#region Windows Form Designer generated code

private void InitializeComponent()

{

this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

this.BackColor = System.Drawing.Color.AliceBlue;

this.ClientSize = new System.Drawing.Size(634, 661);

this.Name = "Game";

this.Text = "Лопай шарики";

components = new System.ComponentModel.Container();

titles = new PictureBox[4];

bomb = new PictureBox();

txtScore = new Label();

txtScore.AutoSize = true;

txtScore.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

txtScore.Location = new System.Drawing.Point(13, 13);

txtScore.Name = "txtScore";

txtScore.Size = new System.Drawing.Size(88, 24);

txtScore.TabIndex = 1;

txtScore.Text = "Score: 0";

gameTimer = new System.Windows.Forms.Timer(this.components);

((System.ComponentModel.ISupportInitialize)(this.bomb)).BeginInit();

SuspendLayout();

this.bomb.Image = global::KNLGamesBallon.Properties.Resources.Bomba;

this.bomb.Location = new System.Drawing.Point(150, 423);

this.bomb.Name = "bomb";

this.bomb.Size = new System.Drawing.Size(100, 98);

this.bomb.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;

this.bomb.TabIndex = 0;

this.bomb.TabStop = false;

this.bomb.Click += new System.EventHandler(GoBoom);

this.gameTimer.Interval = 20;

this.gameTimer.Tick += new System.EventHandler(MainTimerEvent);

this.Controls.Add(this.txtScore);

this.Controls.Add(this.bomb);

InitializingObjects(titles[0], 50, 173, 100, 143, global::KNLGamesBallon.Properties.Resources.Ball1, "pictureBox1", "balloon");

InitializingObjects(titles[1], 182, 73, 111, 116, global::KNLGamesBallon.Properties.Resources.Ball2, "pictureBox2", "balloon");

InitializingObjects(titles[2], 347, 141, 111, 116, global::KNLGamesBallon.Properties.Resources.Ball3, "pictureBox3", "balloon");

InitializingObjects(titles[3], 358, 328, 111, 116, global::KNLGamesBallon.Properties.Resources.Ball4, "pictureBox4", "balloon");

this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.KeyIsUp);

((System.ComponentModel.ISupportInitialize)(this.bomb)).EndInit();

this.ResumeLayout(false);

this.PerformLayout();

}

#endregion

private void InitializingObjects(PictureBox titleObj, int x, int y, int w, int h, Image image, string name, string tag)

{

titleObj = new PictureBox();

((System.ComponentModel.ISupportInitialize)(titleObj)).BeginInit();

titleObj.Image = image;

titleObj.Location = new Point(x, y);

titleObj.Name = name;

titleObj.Size = new Size(w, h);

titleObj.SizeMode = PictureBoxSizeMode.AutoSize;

titleObj.TabIndex = 0;

titleObj.TabStop = false;

titleObj.Tag = tag;

titleObj.Click += new System.EventHandler(PopBalloon);

this.Controls.Add(titleObj);

((System.ComponentModel.ISupportInitialize)(titleObj)).EndInit();

}

}

}

using System;

using System.Windows.Forms;

namespace KNLGamesBallon

{

static class Program

{

[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new GameForm());

}

}

}

Заключение

Создание игры «Шарики» в Windows Forms на C# — это отличный способ научиться работать с графикой, событиями и логикой в играх. В этой статье мы рассмотрели основные шаги по созданию простой игры, но вы можете расширить её функциональность, добавив новые возможности и улучшив интерфейс.