ouled ilyes

ouled ilyes

  • NA
  • 5
  • 668

mis à jour des variables

Dec 31 2015 1:46 PM

Bonjour,

mon application lit des données issu du USB, et fait déplacer les blocks d'une Tetris selon ces donnée.

le problème que la valeur data2 ne se change pas durant l’exécution du programme, elle prend uniquement la première valeur lit de l'USB.

j'ai essayé plusieurs méthodes, c'est pourquoi vous allez trouver que mon code est un peu gênant!

SVP aidez moi :/

voici le code.

 


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.Ports;


namespace Tetris
{

    // This is basically the starting point of the program. A Game instance is created and
    // run in the Main method of Program.cs

    public partial class Game : Form
    {
        // The game screen will be a 9x16 grid of quadratic tiles
        // with side length 32. 
        int colWidth = 32, rowHeight = 32;
        int rows = 16, columns = 9;
        Color backColor = Color.FromArgb(20, 20, 20);

        // The time it initially takes for the player block to move one row down (in milliseconds)
        int updateTime = 500;

        // References to the active block and the World instance that 
        // represents the screen
        Block block;
        World newWorld;

        Random randomizer = new Random();
        int points;
        public SerialPort serialPort;
        public delegate void SerialPortStateChangedDelegate();
        public string data1 = "";
        public string w = "";
        public string data2 = "";

        public Game()
        {
            InitializeComponent();

                // Applying the settings to the WinForm window
                ClientSize = new Size(colWidth * columns, rowHeight * rows);
                BackColor = backColor;
                timer.Interval = updateTime;

                timer.Start();
                fastTimer.Start();
                

                Color randomColor = Color.FromArgb(randomizer.Next(105) + 150,
                            randomizer.Next(105) + 150,
                            randomizer.Next(105) + 50);

                newWorld = new World(Controls, backColor, rows, columns, colWidth, rowHeight);
                block = new Block((BlockType)(randomizer.Next((int)BlockType.count)),
                CreateRandomBlockColor(), newWorld, backColor);
                string[] ports = SerialPort.GetPortNames();
                foreach (string port in ports)
                {
                    comboBox1.Items.Add(port);
                }
                if (comboBox1.Text != "")
                {
                serialPort = new SerialPort(comboBox1.Text, 9600, Parity.None, 8, StopBits.One);
                serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                serialPort.Open();
            }
        }
        

        // fastTimer is needed to update the world immediately when the user 
        // presses a button. This timer's interval is set to 50 milliseconds so
        // this game runs in 20fps.
        private void fastTimer_Tick(object sender, EventArgs e)
        {
                    newWorld.ClearScreen();
                    block.Draw();
                    if (timer.Interval > 400)
                    {
                        this.Text = "Slow";
                    }
                    else if (timer.Interval > 300)
                    {
                        this.Text = "Medium";
                    }
                    else if (timer.Interval > 200)
                    {
                        this.Text = "Fast";
                    }
                    else
                    {
                        this.Text = "Turbo";
                    }
                    
                        jouer();
                        int g = 0;
                        g++;
                    
        }
        
      

        // Move the player block one row down
        private void timer_Tick(object sender, EventArgs e)
        {
            
                    // Update() checks if moving the block one down will make it collide with
                    // the environment.
                    bool blockIsAlive = block.Update();
                    points += 10;

                    if (!blockIsAlive)
                    {
                        FinishBlock();
                    }
               /* }
            }*/
            
        }

        // FinishBlock() is called when player block hits the environment or the player
        // presses the Down arrow key.
        public void FinishBlock()
        {
            // Push the block as far down as possible until it hits the environment. 
            // This is needed when this function is called in response to the player
            // pressing the Down arrow key.
            while (block.MoveDown()) ;

            // Draw the block in its new position
            block.Draw();

            // BlockToEnvironment checks if finishing the active block results in filled rows
            // and return the number.
            int rowsCleared = newWorld.BlockToEnvironment(block.position);

            // Timer gets faster everytime a block finishes even if no rows were cleared
            timer.Interval -= 10 * rowsCleared;

            // Extra poins for combos
            points += 100 * rowsCleared ^ 2;

            // Create a new active block
            MakeRandomBlock();
        }


        private void MakeRandomBlock()
        {
            bool result = block.CreateNew((BlockType)(randomizer.Next((int)BlockType.count)),
                CreateRandomBlockColor());

            // Creating a new block can fail if there is no space to place it at the top of
            // the screen. This results in a GAMEOVER.
            if (result == false)
            {
                block.Draw();
                timer.Stop();
                fastTimer.Stop();

                DialogResult diagAnswer = MessageBox.Show("You got " + points + " points! Start another game?",
                    "Congratulations", MessageBoxButtons.YesNo);

                if (diagAnswer == DialogResult.No)
                {
                    // The player wants to quit
                    this.Close();
                }

                // The player chooses to play another game
                newWorld.ClearEnvironment();
                newWorld.ClearScreen();
                timer.Start();
                fastTimer.Start();
                timer.Interval = updateTime;
                points = 0;
            }
        }
        void sErial(string Port_name)
        {
            serialPort = new SerialPort(Port_name, 9600, Parity.None, 8, StopBits.One);
            serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
            serialPort.Open();

        }
        public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {

            SerialPort sp = (SerialPort)sender;

            string w = sp.ReadExisting();
            if (w != String.Empty)
            {
                Invoke(new Action(() => richTextBox1.AppendText(w)));
                data2=w;
            }
        }

        // Handle the user's USB input
        private void jouer()
        {
            data1 = "300300100";
            int k = 0;
            if (w != "")
            {
                if (data1[0] == '@')
                {
                    k = 1;
                    data1 = "";

                    for (k = k; k < 10; k++)
                    {
                        
                        
                        try { data1 += w[k]; }
                        catch (TimeoutException)
                        {
                            data1 = "TimeoutException";
                        }
                    }
                }
                else
                {
                    data1 = "";
                    for (k = 0; k < 9; k++)
                    {
                        
                        try { data1 += w[k]; }
                        catch (TimeoutException)
                        {
                            data1 = "TimeoutException";
                        }
                    }
                    richTextBox2.Text = k.ToString();
                    
                    
                }
            }
            data2 = richTextBox1.Text;


                if (data2 != String.Empty)
                {
                    int i = 0;
                    string x = "";
                    string y = "";
                    string z = "";
                    int m = 0;
                    if (data2[0] == '@') m = 1;
                    else m = 0;
                    for (i = 0+m; i < 3+m; i++)
                    {
                        x += data2[i];
                    }


                    for (i = 3+m; i < 6+m; i++)
                    {
                        y += data2[i];

                    }
                    for (i = 6; i < 9; i++)
                    {
                        z += data2[i];

                    }
                    richTextBox2.Text = x;
                    if ((x == "300") && (z == "100"))
                    {
                        block.MoveLeft();
                    }
                    if ((z == "300") && (x == "100"))
                    {
                        block.MoveRight();
      
                    }
                    if ((y == "100") && (z == "100"))
                    {
                        FinishBlock();
                    }
                    if ((y == "100") && (z == "300"))
                    {
                        block.Rotate(true);
  
                    }
                    if ((x == "300") && (y == "300") && (z == "300"))
                    {
                        block.Rotate(true);
                    }
                }
                int l = 0;
                string data3="";
            for(l=0;l< data2.Length-19;l++)
            {
                data3 += data2[l+19];
            }
            data2 = data3;

            
                
        }
        private void Game_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Left:
                    block.MoveLeft();
                    break;
                case Keys.Right:
                    block.MoveRight();
                    break;
                case Keys.Down:
                    FinishBlock();
                    break;
                case Keys.P:
                    // Pressing 'P' pauses the game
                    if (timer.Enabled)
                    {
                        timer.Stop();
                        fastTimer.Stop();
                    }
                    else
                    {
                        timer.Start();
                        fastTimer.Start();
                    }
                    break;
                case Keys.Space:
                    block.Rotate(true);
                    break;
                default:
                    break;
            }
            
        }

        public Color CreateRandomBlockColor()
        {
            return Color.FromArgb(randomizer.Next(105) + 150,
                        randomizer.Next(105) + 150,
                        randomizer.Next(105) + 100);
        }

        private void openConnectionButton_Click(object sender, EventArgs e)
        {
         
            string data = "";
            data = comboBox1.Text.ToString();
            sErial(data);

            w = serialPort.ReadLine();

            if (w != String.Empty)
            {
                Invoke(new Action(() => richTextBox1.AppendText(w)));
                
                try { richTextBox1.Text += serialPort.ReadLine(); }
                catch (TimeoutException)
                {
                    richTextBox1.Text = "TimeoutException";
                }
                
            }
        
        }

        



    }
}

 


Answers (4)