Archived
1
0
Fork 0
This repository has been archived on 2024-02-17. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
Tetris/Tetris/Models/Game.cs

121 lines
3 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
namespace Tetris.Models;
public class Game : INotifyPropertyChanged {
private Random _random = new Random();
private string _userName;
public string UserName {
get => _userName;
set {
_userName = value;
OnPropertyChanged("UserName");
}
}
private int _score;
public int Score {
get => _score;
set {
_score = value;
OnPropertyChanged("Score");
}
}
private bool _playing = true;
public bool Playing {
get => _playing;
set {
_playing = value;
OnPropertyChanged("Playing");
}
}
private Grid _grid;
public Grid Grid => _grid;
private Tetrominoe? _currentTetrominoe;
public Tetrominoe? CurrentTetrominoe => _currentTetrominoe;
private Tetrominoe? _nextTetrominoe;
public Tetrominoe? NextTetrominoe => _nextTetrominoe;
public Game(string userName, Grid grid) {
_userName = userName;
_grid = grid;
_currentTetrominoe = GetNewTetrominoe();
_nextTetrominoe = GetNewTetrominoe();
}
public bool HitBottom() {
if (_currentTetrominoe == null)
return false;
return !_grid.CanGo(_currentTetrominoe, _currentTetrominoe.Coordinates + new Size(0, 1));
}
public bool HitTop() {
if (_currentTetrominoe == null)
return false;
else if (_grid.CanGo(_currentTetrominoe, _currentTetrominoe.Coordinates + new Size(0, 1)))
return false;
return _grid.MinGrid.Y == _currentTetrominoe.Coordinates.Y;
}
public void ClearLine()
{
int line = _grid.LineFull();
while (line != -1)
{
_grid.ClearLine(line);
Score += Grid.CGrid.GetLength(0);
line = _grid.LineFull();
}
}
public void PrintTetrominoe() {
if (_currentTetrominoe == null)
return;
_grid.PrintTetrominoe(_currentTetrominoe);
if (Playing) {
_currentTetrominoe = _nextTetrominoe;
_nextTetrominoe = GetNewTetrominoe();
} else {
_currentTetrominoe = null;
_nextTetrominoe = null;
}
}
public Tetrominoe GetNewTetrominoe() {
List<String> tetrominoes = TetrominoeParser.List();
return new Tetrominoe(_grid, tetrominoes[_random.Next(tetrominoes.Count)]);
}
public void SaveGame() {
Console.WriteLine("Game over");
using var db = new ScoreContext();
var score = new Score{Points = Score, UserName = UserName};
db.Scores.Add(score);
db.SaveChanges();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}