Files
FOU/Scripts/Level.cs
2023-11-05 20:09:18 +01:00

113 lines
2.9 KiB
C#

using System;
using FOU.Scripts.Elements;
using Godot;
namespace FOU.Scripts;
public class Level {
public int SizeX;
public int SizeY;
private Image mImage;
private int _frame;
private Element[,] _elements;
private Level _this;
private Main _main;
public Level(int x, int y, Main main) {
GD.Print($"Generating level ({x}:{y})");
_this = this;
_main = main;
SizeX = x;
SizeY = y;
_elements = new Element[x, y];
for (int i = 0; i < SizeX; i++) {
for (int j = 0; j < SizeY; j++) {
_elements[i,j] = new Element(i, j, _this);
}
}
mImage = Image.Create(SizeX, SizeY, false, Image.Format.Rgb8);
mImage.Fill(Colors.Black);
}
public void Update() {
for (int x = 0; x < SizeX; x++) {
for (int y = 0; y < SizeY; y++) {
if (_elements[x,y] != null)
_elements[x,y].Update(_frame);
}
}
_frame++;
MakeItRain(_main.RainAmount);
}
private void MakeItRain(float rainAmount) {
if (GD.Randf() < rainAmount) {
WritePixel<Water>((int)(GD.Randi() % SizeX), 0, 1);
}
}
public void WritePixel<T>(int x, int y, int size) {
int halfsize = size/2;
Type type = typeof(T);
for (int i = -halfsize; i <= halfsize; i++) {
for (int j = -halfsize; j <= halfsize; j++) {
int X = Mathf.Clamp(x + i, 0, SizeX-1);
int Y = Mathf.Clamp(y + j, 0, SizeY-1);
object o = Activator.CreateInstance(type, X, Y, _this);
_elements[X,Y] = o as Element;
}
}
}
public Image DrawLevel() {
for (int x = 0; x < SizeX; x++) {
for (int y = 0; y < SizeY; y++) {
mImage.SetPixel(x,y, _elements[x,y].Color);
}
}
return mImage;
}
public void Swap(Element what, Element swapTo) {
Element swap = new Element(what);
what.Position = swapTo.Position;
_elements[swapTo.Position.X, swapTo.Position.Y] = what;
swapTo.Position = swap.Position;
_elements[swap.Position.X, swap.Position.Y] = swapTo;
}
public void Swap(Element what, Vector2I pos) {
Swap(what, Get(pos));
}
public Element Get(Vector2I where) {
if (where.X < 0 || where.X >= SizeX) return null;
if (where.Y < 0 || where.Y >= SizeY) return null;
return _elements[where.X, where.Y];
}
public Element Get(int x, int y) {
if (x < 0 || x >= SizeX) return null;
if (y < 0 || y >= SizeY) return null;
return _elements[x,y];
}
public bool IsEmpty(Vector2I pos) {
if (pos.X < 0 || pos.X >= SizeX) return false;
if (pos.Y < 0 || pos.Y >= SizeY) return false;
return Get(pos).GetType() == typeof(Element);
}
}