Denna serie är gjorde med MonoGame 3.8.1. Du hittar källkod och övrigt material länkat.
MapGenerator.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
namespace WormsGame
{
internal class MapGenerator
{
public int Width { get; set; }
public int Height { get; set; }
public Texture2D LevelTexture { get; set; }
private Random rnd = new Random();
private Color[] colorData;
public MapGenerator(int width, int height)
{
Width = width;
Height = height;
}
public void Generate(GraphicsDevice device)
{
colorData = new Color[Width * Height];
List<double> HeightMap = new List<double> { 0, 0 };
LevelTexture = new Texture2D(device, Width, Height);
double Max = 1.0;
double Roughness = ((double)100 / 100.0);
for (int j = 0; j < 10; j++)
{
int count = HeightMap.Count;
for (int i = 0; i < count - 1; i++)
{
double tmp = (HeightMap[i * 2] + HeightMap[i * 2 + 1]) / 2.0;
double offset = (rnd.NextDouble() * 2.0 - 1.0) * Max;
HeightMap.Insert(i * 2 + 1, tmp + offset);
}
Max = Max * Math.Pow(2, -Roughness);
}
for(int x = 0; x < Width; x++)
{
double index = (x / (double)Width) * (HeightMap.Count - 1);
int start = (int)Math.Floor(index);
double r2 = index - Math.Floor(index);
double r1 = 1.0 - r2;
double height = HeightMap[start] * r1 + HeightMap[start + 1] * r2;
var yStart = (int)(300 + 250.0 * height);
for (int y = yStart; y < Height; y++)
colorData[y * Width + x] = Color.Chocolate;
}
LevelTexture.SetData(colorData);
}
}
}
Game1.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace WormsGame
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private MapGenerator mapGenerator;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
_graphics.PreferredBackBufferWidth = 1280;
_graphics.PreferredBackBufferHeight = 720;
}
protected override void Initialize()
{
mapGenerator = new MapGenerator(1280, 720);
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
mapGenerator.Generate(GraphicsDevice);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
var kbState = Keyboard.GetState();
if (kbState.IsKeyDown(Keys.R))
mapGenerator.Generate(GraphicsDevice);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();
_spriteBatch.Draw(mapGenerator.LevelTexture, Vector2.Zero, Color.White);
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
Senaste kommentarer