Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ПЗ_Пятнашки.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
2.87 Mб
Скачать

Приложение а. Game1.Cs.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Diagnostics;

using System.Runtime.InteropServices;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Content;

using Microsoft.Xna.Framework.GamerServices;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Media;

namespace Пятнашки

{

/// <summary>

/// This is the main type for your game

/// </summary>

public class Game1 : Microsoft.Xna.Framework.Game

{

[DllImport("user32.dll", CharSet = CharSet.Auto)]

public static extern uint MessageBox(IntPtr hWnd, String text, String caption, uint type);

byte flag = 0,flag_mus=1;

GraphicsDeviceManager graphics;

SpriteBatch spriteBatch;

spriteComp[] gameObject=new spriteComp[16];

Texture2D texture, backTexture,but1,but2;

Rectangle scrBounds;

int[] index = new int[16];//массив индексов

private Vector2 position = new Vector2(0, 0);

int[] ii = new int[16];

int peredv = 0,//число передвижений

flag_mb = 0;//флаг сообщения

SpriteFont font;//для шрифта

Stopwatch stopWatch = new Stopwatch();//время

Stopwatch stopWatch_mus = new Stopwatch();//время для музыки

string elapsedTime = String.Format("{0:00}:{1:00}", 5, 0);//время

TimeSpan ts,dts,music_timer;//время

SoundEffect soundEffect;//музыка

public Game1()

{

graphics = new GraphicsDeviceManager(this);

Content.RootDirectory = "Content";

graphics.PreferredBackBufferWidth = 810; //ширина экрана

graphics.PreferredBackBufferHeight = 600; //его высота

}

protected override void Initialize()

{

base.Initialize();

this.IsMouseVisible = true;

dts=soundEffect.Duration;

}

protected override void LoadContent()

{

soundEffect = Content.Load<SoundEffect>("music");//загружаем аудиофайл

font = this.Content.Load<SpriteFont>("SpriteFont1");

spriteBatch = new SpriteBatch(GraphicsDevice);

Services.AddService(typeof(SpriteBatch), spriteBatch);

texture = Content.Load<Texture2D>("123");

backTexture = Content.Load<Texture2D>("фон44");

scrBounds = new Rectangle(0, 0,

this.Window.ClientBounds.Width,

this.Window.ClientBounds.Height);

but1 = Content.Load<Texture2D>("start");

but2 = Content.Load<Texture2D>("exit");

CreateNewObject();

}

protected void CreateNewObject()

{

int i, n, f;

Random r = new Random();

int[] c = new int[16];//счётчик числа выведенных объектов

int x1, x = 0, y = 0;//координаты х1 для изображения, х,у куда выводить

for (i = 0; i < 16; i++)

{

f = 0;

do

{

n = r.Next(16);//рандомно генерируется номер

if (c[n] < 1)

{

c[n]++;

f = 1;

x1 = n * 150;

if (i == 4 || i == 8 || i == 12)

{

x = 0;

y += 150;

}

gameObject[i] = new spriteComp(this, ref texture,

new Rectangle(x1, 0, 150, 150), new Vector2(x, y));

Components.Add(gameObject[i]);

x += 150;

}

} while (f == 0);

index[i] = n;

ii[i] = i;

}

}

protected override void UnloadContent()

{

// TODO: Unload any non ContentManager content here

}

protected override void Update(GameTime gameTime)

{

int i, z, x1 = 0, x2 = 150, y1 = 0, y2 = 150;

stopWatch_mus.Start();

music_timer = stopWatch_mus.Elapsed;

if ((dts.Minutes - music_timer.Minutes == 0) && (dts.Seconds - music_timer.Seconds == 0))

flag_mus = 1;

if (flag_mus == 1)

{

soundEffect.Play();// воспроизводим звук

stopWatch_mus.Restart();

flag_mus = 0;

}

if (peredv > 0 && flag_mb != 2)

{

stopWatch.Start();

ts = stopWatch.Elapsed;

elapsedTime = String.Format("{0:00}:{1:00}", 4-ts.Minutes, 59-ts.Seconds);//секундомер

}

if (ts.Minutes == 1)//если время кончилось

{

flag_mb = 2;

stopWatch.Stop();

stopWatch.Reset();

ts = stopWatch.Elapsed;

elapsedTime = String.Format("{0:00}:{1:00}", 0, 0);

}

if (flag_mb != 2)

{

flag_mb = 0;

for (i = 0; i < 16; i++)

{

if (index[i] != i)

{

flag_mb = 1;

break;

}

}

}

if (flag_mb == 0)

{

stopWatch.Stop();

}

// TODO: Add your update logic here

MouseState mState = Mouse.GetState();

if (mState.LeftButton == ButtonState.Released)//если кнопка отпущена

flag = 0;

if (mState.LeftButton == ButtonState.Pressed)//если кнопка нажата

{

if ((mState.X > 650) & (mState.X < 750) & (mState.Y > 50) & (mState.Y < 100))//нажали на "новая игра"

{

flag++;

if (flag == 1)

{

flag_mb = 1;

for (i = 0; i < 16; i++)

gameObject[i].Visible = false;

stopWatch.Reset();

elapsedTime = String.Format("{0:00}:{1:00}", 5, 0);

CreateNewObject();

peredv = 0;

}

}

if ((mState.X > 650) & (mState.X < 750) & (mState.Y > 130) & (mState.Y < 180))//нажали на "выйти"

Exit();

x1 = 0; y1 = 0;

if (flag_mb == 1)//если время не закончилось и игра не пройдена

{

for (i = 0; i < 16; i++)

{

if (i == 4 | i == 8 | i == 12)//переход на новую строку

{

x1 = 0;

y1 = y1 + 150;

}

x2 = x1 + 150;

y2 = y1 + 150;

if ((mState.X > x1) & (mState.X < x2) & (mState.Y > y1) & (mState.Y < y2))

{

flag++;

if (index[i] != 15 & flag == 1)//

{

if (i > 3)//если не верхние

{

if (index[i - 4] == 15)//если клетка сверху свободна

{

gameObject[ii[i]].sprPosition.Y -= 150;

index[i - 4] = index[i];

index[i] = 15;

z = ii[i];

ii[i] = ii[i - 4];

ii[i - 4] = z;

peredv++;

break;

}

}

if (i != 0 & i != 4 & i != 8 & i != 12)//если не левые

{

if (index[i - 1] == 15)//если клетка слева свободна

{

gameObject[ii[i]].sprPosition.X -= 150;

index[i - 1] = index[i];

index[i] = 15;

z = ii[i];

ii[i] = ii[i - 1];

ii[i - 1] = z;

peredv++;

break;

}

}

if (i != 3 & i != 7 & i != 11 & i != 15)//если не правые

{

if (index[i + 1] == 15)//если клетка справа свободна

{

gameObject[ii[i]].sprPosition.X += 150;

index[i + 1] = index[i];

index[i] = 15;

z = ii[i];

ii[i] = ii[i + 1];

ii[i + 1] = z;

peredv++;

break;

}

}

if (!(i > 11))//если не нижние

{

if (index[i + 4] == 15)//если клетка снизу свободна

{

gameObject[ii[i]].sprPosition.Y += 150;

index[i + 4] = index[i];

index[i] = 15;

z = ii[i];

ii[i] = ii[i + 4];

ii[i + 4] = z;

peredv++;

break;

}

}

}

break;

}

x1 = x1 + 150;

}

}

}

base.Update(gameTime);

}

protected override void Draw(GameTime gameTime)

{

graphics.GraphicsDevice.Clear(Color.CadetBlue);

// TODO: Add your drawing code here

spriteBatch.Begin();

spriteBatch.Draw(backTexture, new Rectangle(0, 0, 600, 600), Color.White);

spriteBatch.DrawString(font, "Count of movings:" + peredv, new Vector2(605, 200), Color.Aqua);

spriteBatch.DrawString(font, "Remaining time:" + elapsedTime, new Vector2(605, 220), Color.Aqua);

if (flag_mb == 2)//если время кончилось

{

spriteBatch.DrawString(font, "Time is up.\nGame over.", new Vector2(605, 250), Color.Yellow);

}

if (flag_mb == 0&&peredv>0)//если игра пройдена

{

spriteBatch.DrawString(font, "You are win!!!\nCongratulations!", new Vector2(605, 250), Color.Yellow);

}

spriteBatch.Draw(but1, new Rectangle(650, 50, 100, 50), Color.White);

spriteBatch.Draw(but2, new Rectangle(650, 130, 100, 50), Color.White);

base.Draw(gameTime);

spriteBatch.End();

}

}

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]