Files
FOU/Scripts/Level.cs
rogo 7670b2982a added second element type: snow
added simple snow weather
2023-10-17 15:11:07 +02:00

108 lines
2.7 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<Snow>((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++) {
// if (_elements[x,y] == null) continue;
mImage.SetPixel(x,y, _elements[x,y].Color);
}
}
return mImage;
}
public void Swap(Element what, Vector2I swapTo) {
Element old = Get(swapTo);
Set(old, what.Position);
Set(what, swapTo);
}
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];
}
private void Set(Element what, Vector2I where) {
if (what == null) return;
what.Position = where;
_elements[where.X, where.Y] = what;
}
}