Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

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

Купить рекламу на форуме - 42 тыс руб за месяц

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

Код:
namespace Snake
{public partial class Snake : Form
 {SoundPlayer sp = new SoundPlayer();
  Timer myTimer = new Timer();
Timer myTimer2 = new Timer();
 //Snake def
PictureBox[] snakeParts;
 int snakesize = 3;
 Point location = new Point(120, 120);
string direction = "Right";
bool changingDirection = false;
//fruit def
PictureBox food = new PictureBox();
Point foodlocation = new Point(0, 0);
PictureBox[] wallparts;
double a = 15;
int level = 1;
//database
static String path = Path.GetFullPath(Environment.CurrentDirectory);
static String dataBaseName = "date.mdf";
string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + @"\" + dataBaseName + "; Integrated Security=True";
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();
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)
{ foodlocation = new Point(Xrand, Yrand);
food.Size = new Size(15, 15);
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 trackBar1_Scroll(object sender, EventArgs e)
{
//change time interval
timer1.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();}
//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();
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();
 //add current score update score board
addCurrentScoresToDateBase();
UpdateScoreBoard();}
Brean вне форума Ответить с цитированием
Старый 25.05.2020, 21:19   #2
Brean
Новичок
Джуниор
 
Регистрация: 19.05.2020
Сообщений: 3
По умолчанию

Продолжение
Код:
private void UpdateScoreBoard(){
 //data from datebase
string query = "SELECT Date, Name, Score, Levels, Fruits FROM scores";
using(SqlConnection con = new SqlConnection(connectionString)){
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
var ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
dataGridView1.Sort(this.dataGridView1.Columns[2], ListSortDirection.Descending);}}
private void addCurrentScoresToDateBase(){
//insert score in database
 string query = "INSERT INTO scores(Date, Name, Score, Levels, Fruits) VALUES(@Date,@Name,@Score,@Levels,@Fruits);";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query,con))
{cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = namebox.Text;
cmd.Parameters.Add("@Score", SqlDbType.Int).Value = Score_count.Text;
cmd.Parameters.Add("@Levels", SqlDbType.Int).Value = level_count.Text;
cmd.Parameters.Add("@Fruits", SqlDbType.Int).Value = fruit_count.Text;
con.Open(); cmd.ExecuteNonQuery(); con.Close();}}
private void Snake_Load(object sender, EventArgs e)
{UpdateScoreBoard();
playmusic();}
private void musicon_Click(object sender, EventArgs e)
{playmusic();}
private void musicoff_Click(object sender, EventArgs e)
{ stopmusic();}
private void playmusic()
{sp.SoundLocation = "Chill.wav";
sp.PlayLooping();
 musicon.Enabled = false;
musicoff.Enabled = true;}
private void stopmusic()
{sp.Stop();
musicon.Enabled = true;
musicoff.Enabled = false;}}}
Brean вне форума Ответить с цитированием
Старый 26.05.2020, 08:21   #3
digitalis
Старожил
 
Аватар для digitalis
 
Регистрация: 04.02.2011
Сообщений: 4,536
По умолчанию

Ну и об чём эта тема?
digitalis вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
[C++ CLI] Создать классы для готовой программы anshnine Помощь студентам 3 17.12.2018 09:51
Две программы как одно целое. Классы и std::vector в функции CopyMemory silentsky Общие вопросы C/C++ 6 04.05.2017 18:25
Доработка программы.Классы.Язык С++. East Undia Trading Помощь студентам 15 09.04.2014 22:54
Прошу помощи. C++ Builder. Описать классы, обеспечивающие вычитание, деление и умножение целых чисел Kapelka Помощь студентам 7 24.02.2014 20:59