Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

c# - BackColor property not changing properly in code. Any ideas as to what I'm doing wrong?

Intermediate C# dev here. Trying to transition into game programming by writing a simple Simon clone (private learning only, I do not own any copyrights or intend to distribute/sell) and I'm stuck.

Here's a link to the full code thus far: Simon

The problem lies in the PlayTile() method below:

private void PlayTile(Button btnColorOfTile, Color lightedTileColor, SoundPlayer tileSoundPlayer, Color originalTileColor)
    {
        // ***BUG03***
        TilePress(btnColorOfTile, lightedTileColor, tileSoundPlayer);
        // Small pause so tile can be lit before instantly changing back
        Thread.Sleep(SLEEP_TIME);
        TileRelease(btnColorOfTile, originalTileColor, tileSoundPlayer);
        // Small pause between each tile play so that you can distingish multiple plays of the same tile.
        Thread.Sleep(SLEEP_TIME);
    }

This is supposed to "light" up the tile by changing the BackColor property, pause for a half second (SLEEP_TIMEis set to 500ms) while playing the tile's sound, and change the BackColor back to the normal color.

The sound plays properly with the pause and everything, but the tiles are not changing color. I change the BackColor property in TilePress() and change it back in TileRelease() which is called in the MouseUp and MouseDown for the tile's event handlers and it works just fine.

Any ideas why PlayTile() is working for sound but not changing the BackColor property?

Also, if you see any glaring mistakes in the code, please let me know. This is all about learning for me so constructive criticism is desired.

Thanks in advance for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thread.Sleep blocks your UI thread(this means your form can not process any window messages like keyboard, mouse, move, paint etc. It is a "Not Responding" state and not a desired behavior).

You can use async/await instead.

Example:

async Task PlayTile()
{
    this.BackColor = Color.Red;
    await Task.Delay(500);
    this.BackColor = Color.White;
    await Task.Delay(500);
}

async private void button1_Click(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        await PlayTile();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...