Студопедия Главная Случайная страница Обратная связь

Разделы: Автомобили Астрономия Биология География Дом и сад Другие языки Другое Информатика История Культура Литература Логика Математика Медицина Металлургия Механика Образование Охрана труда Педагогика Политика Право Психология Религия Риторика Социология Спорт Строительство Технология Туризм Физика Философия Финансы Химия Черчение Экология Экономика Электроника

ПРИЛОЖЕНИЕ A




Исходный код программы:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using Microsoft.DirectX.AudioVideoPlayback;

 

namespace MySnake

{

static class Program

{

/// <summary>

/// Главная точка входа для приложения.

/// </summary>

[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new formGame());

}

}

public static class Input

{

private static Hashtable _keys = new Hashtable();//I:\MySnake\Input.cs

 

public static void ChangeState(Keys key, bool state)

{

_keys[key] = state;

}

/// <summary>

/// Returns whether or not "key" is being pressed.

/// </summary>

/// <param name="key"></param>

/// <returns></returns>

public static bool Press(Keys key)

{

if (_keys[key] == null)

_keys[key] = false;

return (bool)_keys[key];

}

}

public class RecordStats

{

public string X { get; set; }

public int Y { get; set; }

 

public RecordStats(string x , int y)

{

X = x;

Y = y;

}

}

public class SnakePart

{

public int X { get; set; }

public int Y { get; set; }

 

public SnakePart(int x, int y)

{

X = x;

Y = y;

}

}

public partial class formGame : Form

{

#region Constructor

#region Variables

int score = 0;

int level = 1;

bool pause = false;

bool gameover = false;

bool stayFoot = true;

int direction = 0; //0 -down, 1 - left, 2 - right , 3- up

List<SnakePart> snake = new List<SnakePart>();

List<RecordStats> record = new List<RecordStats>(5);

static string filedata = File.ReadAllText("Recfile.txt");

SnakePart food;

Timer gameLoop = new Timer();

Timer snakeLoop = new Timer();

int snakeRate = 2;

Bitmap Pbody = new Bitmap(Properties.Resources.body);

Bitmap Pfood = new Bitmap(Properties.Resources.flov);

Bitmap Phead = new Bitmap(Properties.Resources.head3);

Bitmap Phead3 = new Bitmap(Properties.Resources.head1);

Bitmap Phead2 = new Bitmap(Properties.Resources.head2);

Bitmap Phead0 = new Bitmap(Properties.Resources.head3);

Bitmap Phead1 = new Bitmap(Properties.Resources.head4);

Microsoft.DirectX.AudioVideoPlayback.Audio audio = new Microsoft.DirectX.AudioVideoPlayback.Audio(@"F:\MySnake\Backsound.mp3");

System.Media.SoundPlayer Eda = new System.Media.SoundPlayer(Properties.Resources.Eda);

System.Media.SoundPlayer Gameover1 = new System.Media.SoundPlayer(Properties.Resources.Gameover);

 

#endregion

 

public formGame()

{

InitializeComponent();

gameLoop.Tick += new EventHandler(Update);

snakeLoop.Tick += new EventHandler(UpdateSnake);

gameLoop.Interval = 1000 / 60;

snakeLoop.Interval = 1000 / snakeRate;

gameLoop.Start();

snakeLoop.Start();

StartGame();

}

#endregion

 

#region Form Events;

 

private void formGame_KeyDown(object sender, KeyEventArgs e)

{

Input.ChangeState(e.KeyCode, true);

}

 

private void formGame_KeyUp(object sender, KeyEventArgs e)

{

Input.ChangeState(e.KeyCode, false);

}

 

private void pbCanvas_Paint(object sender, PaintEventArgs e)

{

Draw(e.Graphics);

}

 

#endregion

 

#region Game Logic

private void StartGame()

{

snakeRate = 3;

snakeLoop.Interval = 1000 / snakeRate;

snake.Clear();

SnakePart head = new SnakePart(10, 8);

direction = 2;

snake.Add(head);

GenerateFood();

level = 1;

score = 0;

gameover = false;

stayFoot = true;

audio.Play();

}

 

private void Update(object sender, EventArgs e)

{

if (gameover)

{

if (Input.Press(Keys.Enter))

{

StartGame();

}

}

else

{

if (Input.Press(Keys.Left))

{

if (snake.Count < 2 || snake[0].X == snake[1].X)

{

direction = 1;

Phead = new Bitmap(Phead1);

}

}

else if (Input.Press(Keys.Right))

{

if (snake.Count < 2 || snake[0].X == snake[1].X)

{

direction = 2;

Phead = new Bitmap(Phead2);

}

}

else if (Input.Press(Keys.Up))

{

if (snake.Count < 2 || snake[0].Y == snake[1].Y)

{

direction = 3;

Phead = new Bitmap(Phead3);

}

}

else if (Input.Press(Keys.Down))

{

if (snake.Count < 2 || snake[0].Y == snake[1].Y)

{

direction = 0;

Phead = new Bitmap(Phead0);

}

}

 

else if (Input.Press(Keys.P))

{

Pause();

}

else if (Input.Press(Keys.R))

{

Continue();

}

 

}

pbCanvas.Invalidate();

}

 

private void UpdateSnake(object sender, EventArgs e)

{

if (!gameover)

{

for (int i = snake.Count - 1; i >= 0; i--)

{

if (i == 0)

{

switch (direction)

{

case 0:

snake[0].Y++;

break;

case 1:

snake[0].X--;

break;

case 2:

snake[0].X++;

break;

case 3:

snake[0].Y--;

break;

}

 

// Check for out of bounds

SnakePart head = snake[0];

if (head.X >= 20 || head.X < 0 || head.Y >= 20 || head.Y < 0)

Gameover();

 

//Check for collision with body

for (int j = 1; j < snake.Count; j++)

if (head.X == snake[j].X && head.Y == snake[j].Y)

Gameover();

//Check for collision with food

if (head.X == food.X && head.Y == food.Y)

{

SnakePart part = new SnakePart(snake[snake.Count - 1].X, snake[snake.Count - 1].Y);

snake.Add(part);

score++;

Eda.Play();

GenerateFood();

if ((score % 5) == 0 )

{

snakeRate ++;

level++;

snakeLoop.Interval = 1000 / snakeRate;

}

}

}

else

{

snake[i].X = snake[i - 1].X;

snake[i].Y = snake[i - 1].Y;

}

}

 

}

 

}

 

 

private void Draw(Graphics canvas)

{

Font font = this.Font;

if (gameover)

{

SizeF message = canvas.MeasureString("Gameover", font);

canvas.DrawString("Gameover", font, Brushes.White, new PointF(200 - message.Width / 2, 140));

message = canvas.MeasureString("Final Score " + score.ToString(), font);

canvas.DrawString("Final Score " + score.ToString(), font, Brushes.White, new PointF(200 - message.Width / 2, 160));

message = canvas.MeasureString("Press Enter to Start a New Game", font);

canvas.DrawString("Press Enter to Start a New Game", font, Brushes.White, new PointF(200 - message.Width / 2, 200));

}

else

{

 

lscore.Text = "Score: " + score.ToString();

llevel.Text = "Level: " + level.ToString();

for (int i = 0; i < snake.Count; i++)

{

SnakePart currentPart = snake[i];

if (i == 0)

canvas.DrawImage(Phead, currentPart.X * 20, currentPart.Y * 20);

else

canvas.DrawImage(Pbody, currentPart.X * 20, currentPart.Y * 20);

}

canvas.DrawImage(Pfood, food.X * 20, food.Y * 20);

 

if (pause)

{

Font Pfont = new System.Drawing.Font("Modern No. 20", 25.2F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

SizeF message = canvas.MeasureString("Pause", Pfont);

canvas.DrawString("Pause", Pfont, Brushes.Black, new PointF(200 - message.Width / 2, 140));

message = canvas.MeasureString("Press R to continue!", Pfont);

canvas.DrawString("Press R to continue!", Pfont, Brushes.Black, new PointF(200 - message.Width / 2, 180));

}

}

}

 

private void Gameover()

{

audio.Stop();

// audio.Stop();

gameover = true;

Gameover1.Play();

 

}

 

private void Pause()

{

pause = true;

snakeLoop.Stop();

}

 

private void Continue()

{

pause = false;

snakeLoop.Start();

}

 

private void GenerateFood()

{

while (stayFoot)

{

stayFoot = false;

Random random = new Random();

food = new SnakePart(random.Next(0, 20), random.Next(0, 20));

for (int i = 0; i < snake.Count; i++)

if (food.X == snake[i].X && food.Y == snake[i].Y)

{

stayFoot = true;

break;

}

}

stayFoot = true;

 

}

 

#endregion

 

#region Menu

private void exitToolStripMenuItem_Click(object sender, EventArgs e)

{

Close();

}

 

private void aboutToolStripMenuItem_Click(object sender, EventArgs e)

{

(new About()).ShowDialog();

}

 

 

private void recordsToolStripMenuItem_Click(object sender, EventArgs e)

{

string FinalScore = score.ToString();

(new Records(FinalScore)).ShowDialog();

}

#endregion

}

public partial class Records : Form

{

protected string score;

 

public Records(string score)

{

InitializeComponent();

YouScore.Text = score;

this.score = score;

}

 

public struct Stats

{

public string NamePlayer

{

get;

set;

}

public int ScorePlayer

{

get;

set;

}

}

private void ShowRecord()

{

StreamReader reader = new StreamReader(@"F:\MySnake\bin\Debug\Recfile.txt");

List<Stats> points = new List<Stats>();

string s = string.Empty;

while ((s = reader.ReadLine()) != null)

{

string[] splits = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

points.Add(new Stats

{

NamePlayer = splits[0],

ScorePlayer = int.Parse(splits[1]),

});

}

points.Sort((a, b) => a.ScorePlayer.CompareTo(b.ScorePlayer) * -1);

player1.Text = points[0].NamePlayer + " " + points[0].ScorePlayer;

player2.Text = points[1].NamePlayer + " " + points[1].ScorePlayer;

player3.Text = points[2].NamePlayer + " " + points[2].ScorePlayer;

player4.Text = points[3].NamePlayer + " " + points[3].ScorePlayer;

player5.Text = points[4].NamePlayer + " " + points[4].ScorePlayer;

reader.Close();

}

 

private void Records_Shown(object sender, EventArgs e)

{

ShowRecord();

 

}

 

public void button1_Click(object sender, EventArgs e)

{

System.IO.StreamWriter NewRecord = new System.IO.StreamWriter(@"F:\MySnake\bin\Debug\Recfile.txt", true);

NewRecord.WriteLine(PlayerName.Text + " " + score);

MessageBox.Show("Рекорд успешно записан");

NewRecord.Close();

ShowRecord();

score = "0";

PlayerName.Text = "";

YouScore.Text = "0";

 

}

}

public partial class About : Form

{

public About()

{

InitializeComponent();

}

}

}


Поможем в написании учебной работы
Поможем с курсовой, контрольной, дипломной, рефератом, отчетом по практике, научно-исследовательской и любой другой работой





Дата добавления: 2015-08-30; просмотров: 300. Нарушение авторских прав; Мы поможем в написании вашей работы!

Studopedia.info - Студопедия - 2014-2022 год . (0.106 сек.) русская версия | украинская версия
Поможем в написании
> Курсовые, контрольные, дипломные и другие работы со скидкой до 25%
3 569 лучших специалисов, готовы оказать помощь 24/7