Archived
1
0
Fork 0
This repository has been archived on 2024-02-17. You can view files and clone it, but cannot push or open issues or pull requests.
Tetris/ViewsModels/GameViewModel.cs
2022-05-04 11:08:04 +02:00

91 lines
No EOL
2.9 KiB
C#

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Tetris.Models;
using Color = System.Drawing.Color;
namespace Tetris.ViewsModels;
public class GameViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public static readonly Game Game = new("...", new Grid(new Color[25, 50]));
private const int RendererHertz = 5;
private const int GameRendererHertz = (1 / RendererHertz) * 1000;
private const int Multiplier = 10;
private readonly int _width = (Game.Grid.MaxGrid.X + 1) * Multiplier;
private readonly int _height = (Game.Grid.MaxGrid.Y + 1) * Multiplier;
private readonly WriteableBitmap _writeableBitmap;
public GameViewModel()
{
_writeableBitmap = BitmapFactory.New(_width, _height);
var dispatcherRenderTimer = new DispatcherTimer
{
Interval = new TimeSpan(0, 0, 0, 0, GameRendererHertz)
};
dispatcherRenderTimer.Tick += Render;
dispatcherRenderTimer.Start();
var dispatcherUpdateTimer = new DispatcherTimer
{
Interval = new TimeSpan(0, 0, 0, 0, 100)
};
dispatcherUpdateTimer.Tick += Update;
dispatcherUpdateTimer.Start();
}
public ImageSource Source => _writeableBitmap;
private void Render(object? sender, EventArgs eventArgs)
{
_writeableBitmap.Lock();
_writeableBitmap.Clear(Colors.Black);
for (var x = 0; x < Game.Grid.MaxGrid.X + 1; x++)
{
for (var y = 0; y < Game.Grid.MaxGrid.Y + 1; y++)
{
var color = Game.Grid.CGrid[x, y];
_writeableBitmap.FillRectangle(x * Multiplier, y * Multiplier, x * Multiplier + Multiplier, y * Multiplier + Multiplier, color.ToArgb());
}
}
var tetrominoeWidth = Game.CurrentTetrominoe?.Shape.GetLength(0);
var tetrominoeHeight = Game.CurrentTetrominoe?.Shape.GetLength(1);
for (int x = 0; x < tetrominoeWidth; x++)
{
for (int y = 0; y < tetrominoeHeight; y++)
{
var currentPiece = Game.CurrentTetrominoe!;
if (currentPiece.Shape[x, y] == false) continue;
var color = currentPiece.Color;
_writeableBitmap.FillRectangle((currentPiece.Coordinates.X + x) * Multiplier, (currentPiece.Coordinates.Y + y) * Multiplier, (currentPiece.Coordinates.X + x) * Multiplier + Multiplier, (currentPiece.Coordinates.Y + y) * Multiplier + Multiplier, color.ToArgb());
}
}
_writeableBitmap.Unlock();
}
private void Update(object? sender, EventArgs eventArgs)
{
Game.CurrentTetrominoe?.GoDown();
if (Game.HitBottom())
{
Game.PrintTetrominoe();
}
}
}