locked
mis à jour des variables RRS feed

  • Question

  • 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.

    Thursday, December 31, 2015 2:02 PM

All replies

  • 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";
                    }
                    
                }
            
            }
    
            
    
    
    
        }
    }
    

    Thursday, December 31, 2015 2:05 PM
  • Hi ilyes,

    This is English forum, please post your question in the right language forum for dedicated help.
    https://social.msdn.microsoft.com/Forums/fr-FR/home

    Best Regards,
    Li Wang


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, January 1, 2016 5:15 AM
  • Please select your language from the drop down list at the top of the page to post your question in the language of your choice. The forum you posted in is for English only. If you do not find the desired language, support options for additional international locations can be found by following the link below:
    *
    S'il vous plaît sélectionnez votre langue dans la liste déroulante en haut de la page pour poster vos questions dans la langue de votre choix vers le bas. Le forum où vous avez posté est en anglais seulement. Si vous ne trouvez pas la langue souhaitée, appuyer options de destinations internationales supplémentaires peut être trouvé en suivant le lien ci-dessous:
    *


    Wanikiya and Dyami--Team Zigzag Windows IT-PRO (MS-MVP)

    Friday, January 1, 2016 5:25 AM
  • Please select your language from the drop down list at the top of the page to post your question in the language of your choice. The forum you posted in is for English only. If you do not find the desired language, support options for additional international locations can be found by following the link below:
    *
    S'il vous plaît sélectionnez votre langue dans la liste déroulante en haut de la page pour poster vos questions dans la langue de votre choix vers le bas. Le forum où vous avez posté est en anglais seulement. Si vous ne trouvez pas la langue souhaitée, appuyer options de destinations internationales supplémentaires peut être trouvé en suivant le lien ci-dessous:
    *


    Wanikiya and Dyami--Team Zigzag Windows IT-PRO (MS-MVP)

    Friday, January 1, 2016 5:26 AM
  • Hello,

    The French C# forum is on: http://social.msdn.microsoft.com/Forums/vstudio/fr-FR/home?forum=visualcsharpfr&filter=alltypes&sort=lastpostdesc

    Salut,

    Le forum français C# est sur: http://social.msdn.microsoft.com/Forums/vstudio/fr-FR/home?forum=visualcsharpfr&filter=alltypes&sort=lastpostdesc

    Cordialement

    Karl


    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book: Windows PowerShell 2.0 Bible
    My E-mail: -join('6D73646E5F6B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

    Tuesday, January 5, 2016 8:46 PM