Я создаю карточную игру в блэкджек и в своем методе LoadContent
. Я выбираю случайную карту, но проблема в том, что я не знаю, как правильно закончить этот метод, чтобы он выбрал одну случайную карту, а не цикл бесконечно. Сейчас две случайные карты мигают из-за бесконечного цикла.Бесконечная игровая петля
public class Kaart
{
public Vector2 asukoht = new Vector2(0, 0);
public List<Texture2D> tekstuur = new List<Texture2D>();
Random rand = new Random();
public void loadContent(ContentManager manager) // loading first card
{
for (int j = 3; j < 7; j++)
{
tekstuur.Add(manager.Load<Texture2D>("Risti" + j.ToString()));
}
}
public void loadContent2(ContentManager manager) // loading second card
{
for (int j = 3; j < 7; j++)
{
tekstuur.Add(manager.Load<Texture2D>("Risti" + j.ToString()));
}
}
public void Draw(SpriteBatch sprite) // here ill draw the random card
{
sprite.Draw(tekstuur[rand.Next(tekstuur.Count)], asukoht, Color.White);
sprite.Draw(tekstuur[rand.Next(tekstuur.Count)], asukoht, Color.White);
}
}
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Vector2 koht = new Vector2(0,0);
Kaart yks;
Kaart kaks;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
yks = new Kaart();
kaks = new Kaart();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
//loading cards
yks.loadContent(this.Content);
kaks.loadContent2(this.Content);
// card positions
yks.asukoht.X = 100;
yks.asukoht.Y = 300;
kaks.asukoht.X = 200;
kaks.asukoht.Y = 400;
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
// kaartide joonistamine
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
yks.Draw(this.spriteBatch);
kaks.Draw(this.spriteBatch);
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
Выглядит так, как будто вы даже не знаете, как работает основной игровой цикл. У вас есть цикл, и он обновляет состояние вашей игры (метод Update) и рисует все необходимое (метод Draw). Он повторяется снова и снова. Вам нужно сказать, чтобы он остановился в коде, иначе он просто сделает то, что он делает сейчас. Читайте об игровых циклах и основах XNA в целом. –
Да, я полный noob в XNA. Но если я понял, то мне нужно получить состояние этого цикла и разбить его в методе обновления? – user3024888
Нет. Вам нужно рассказать игре «сейчас самое время рисовать» или «не рисовать следующие карты сейчас, пришло время ждать ввода пользователя» или что-то подобное. Игровые состояния - это то, что вы ищете - вы обновляете его в Update(), а затем действуете соответственно (рисовать или нет) в Draw(). Я уверен, что есть много учебников по игровым состояниям в целом и как их реализовать в XNA там в Интернете. –