我刚刚学习XNA,并开始制作一个简单的打破方块游戏。我使用2d数组来表示屏幕顶部的块
bricks = new Bricks[18,16];
for (int y = 0; y < 16; y++)
{
for(int x = 0; x < 18; x++)
{
bricks[x, y] = new Bricks(BrickTexture, new Rectangle(x * BrickTexture.Width, y * BrickTexture.Height, 38, 18), Color.Red);
if (y == 2 || y == 3)
{
bricks[x, y] = new Bricks(BrickTexture, new Rectangle(x * BrickTexture.Width, y * BrickTexture.Height, 38, 18), Color.Blue);
}
if (y == 4 || y == 5)
{
bricks[x, y] = new Bricks(BrickTexture, new Rectangle(x * BrickTexture.Width, y * BrickTexture.Height, 38, 18), Color.Green);
}
if (y == 6 || y == 7)
{
bricks[x, y] = new Bricks(BrickTexture, new Rectangle(x * BrickTexture.Width, y * BrickTexture.Height, 38, 18), Color.White);
}
if (y == 8 || y == 9)
{
bricks[x, y] = new Bricks(BrickTexture, new Rectangle(x * BrickTexture.Width, y * BrickTexture.Height, 38, 18), Color.Pink);
}
if (y == 10 || y == 11)
{
bricks[x, y] = new Bricks(BrickTexture, new Rectangle(x * BrickTexture.Width, y * BrickTexture.Height, 38, 18), Color.Purple);
}
if (y == 12 || y == 13)
{
bricks[x, y] = new Bricks(BrickTexture, new Rectangle(x * BrickTexture.Width, y * BrickTexture.Height, 38, 18), Color.Navy);
}
}
}
这就是块是如何构建的,它们是用foreeach循环绘制到屏幕上的。
foreach (Bricks brick in bricks)
{
brick.Draw(spriteBatch);
}
在我的Update方法中,我使用了另一个方法来执行每个循环,并检查球是否与它们中的任何一个碰撞,以及它们是否必须从屏幕上移除砖块。对于和碰撞的方法如下:
foreach (Bricks brick in bricks)
{
brick.CheckBrickBallCollision(ball);
}
public void CheckBrickBallCollision(Ball ball)
{
if (isVisible && ball.Ball2.Intersects(position))
{
isVisible = false;
ball.direction.X *= 0.85f;
ball.direction.Y *= -1;
}
}
我的问题是如何让所有砖块消失后的游戏获胜,然后通过改变游戏状态出现获胜画面。
有什么好主意吗
要做到这一点,无需更改任何代码,只需计算可见砖块的数量。
int visibleCount = 0;
foreach (Bricks brick in bricks)
{
brick.CheckBrickBallCollision(ball);
if (brick.isVisible)
{
visibleCount++;
}
}
//If there are no visible bricks then the player won!
if (visibleCount == 0)
{
//Win the Game!
}
作为另一种选择,您可以管理活动块的列表而不是管理它们的可见性。当砖块被击中时,你可以将其从列表中删除。当列表为空时,你就知道玩家赢了。
由于某种原因,看着上面的答案,这是最终的工作,我想我将分享
foreach (Bricks brick in bricks)
{
brick.CheckBrickBallCollision(ball);
if (brick.isVisible == true)
{
brokenBlocks -= 1;
}
}
if (brokenBlocks == 40)
{
currentGameState = GameState.Won;
}