【问题标题】:How to detect and set image to only 1 picture box that is empty?如何检测并将图像设置为只有 1 个空的图片框?
【发布时间】:2015-03-01 23:42:16
【问题描述】:

我有一个带有 7 个图片框的 GameForm 来代表玩家手中的牌。中间有2个播放器和2个图片框。中间的图片是供玩家出牌的,另一个是抽牌的。当玩家点击图像时,卡片将进入丢弃堆图片框,从而使手中的图片框为空。我怎么做才能让玩家在抽牌时进入一个空的图片框? !

我试过用这个方法

if (pictureBox1.Image == null) {
        pictureBox1.ImageLocation = images[n];
        }
 ...
 ...
if (pictureBox7.Image == null) {
        pictureBox7.ImageLocation = images[n];
        }

但是如果我这样做了,那么如果 2 Picturebox 是空的,两个都将被随机抽取的卡片填充.. 关于如何每次只画 1 张卡片并设置为 1 个空图片框的任何建议? 提前致谢!

【问题讨论】:

    标签: c# picturebox


    【解决方案1】:

    只需使用else if 而不是if,以确保将卡片分配到可用位置后,不会意外地将其分配到其他位置。

    if (pictureBox1.Image == null)
        pictureBox1.ImageLocation = images[n];
    else if (pictureBox2.Image == null)
        pictureBox2.ImageLocation = images[n];
    ...
    ...
    else if (pictureBox7.Image == null)
        pictureBox7.ImageLocation = images[n];
    

    或者,您可以在程序启动时将 PictureBox 控件存储在这样的集合中:

    List<PictureBox> hand = new List<PictureBox> { pictureBox1, ..., pictureBox7 };
    

    然后当你需要找到第一个可用位置时,使用 LINQ:

    // Find the first slot in the player's hand with a null Image, if any
    var availableSlot = hand.FirstOrDefault(x => x.Image == null);
    
    // If an empty slot was found, set it to the image from the "draw" pile
    if (availableSlot != null)
        availableSlot.Image = images[n];
    

    【讨论】:

    • 谢谢!!先生您真是个天才! =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多