sneak/Jumpy.Shared/World.cs

103 lines
2.6 KiB
C#
Raw Normal View History

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
namespace Jumpy {
enum Terrain {
Empty,
Grass,
Rock
}
class Tile {
Texture2D texture;
Terrain terrain;
Rectangle position;
public Tile(Texture2D texture, Terrain terrain, Rectangle position) {
this.texture = texture;
this.terrain = terrain;
this.position = position;
}
public Rectangle Position { get { return position; } }
public Terrain Terrain { get { return terrain; } }
public void Draw(SpriteBatch spriteBatch) {
int size = World.TileSize;
switch (terrain) {
case Terrain.Grass: {
// TODO: hold these rectangles statically instead of making them anew constantly.
Rectangle source = new Rectangle(3 * size, 0 * size, size, size);
spriteBatch.Draw(texture, position, source, Color.White);
break;
}
case Terrain.Rock: {
Rectangle source = new Rectangle(3 * size, 1 * size, size, size);
spriteBatch.Draw(texture, position, source, Color.White);
break;
}
case Terrain.Empty:
default:
break;
}
}
}
class World {
public const int TileSize = 16;
int width;
int height;
Tile[,] tiles;
public int Width { get; }
public int Height { get; }
public World(Texture2D texture) {
width = Camera.Width / TileSize;
height = Camera.Height / TileSize + 1;
tiles = new Tile[width, height];
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
Terrain terrain;
if (j < height - 3) {
terrain = Terrain.Empty;
} else if (j == height - 3) {
terrain = Terrain.Grass;
} else {
terrain = Terrain.Rock;
}
if (j == 4 && 11 < i && i < 15) {
terrain = Terrain.Grass;
}
var position = new Rectangle(i * TileSize, j * TileSize, TileSize, TileSize);
tiles[i, j] = new Tile(texture, terrain, position);
}
}
}
public void Draw(SpriteBatch spriteBatch) {
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
tiles[i, j].Draw(spriteBatch);
}
}
}
public List<Rectangle> CollisionTargets() {
var result = new List<Rectangle>();
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
var t = tiles[i, j];
if (t.Terrain != Terrain.Empty) {
result.Add(t.Position);
}
}
}
return result;
}
}
}