Files
PyGame-Tetris/hud.py
2025-04-23 13:45:29 +02:00

79 lines
2.8 KiB
Python

import pygame
import os
from globals import TILE_SIZE
from enums import BrickColor
class Hud:
def __init__(self, screen_width, screen_height, font_size=36, highscore_file="highscore.txt"):
self.highscore_file = highscore_file
self.highscore = self.load_highscore()
self.font = pygame.font.Font(None, font_size)
self.color = BrickColor.Red.value
self.screen_width = screen_width
self.screen_height = screen_height
self.reset()
def load_highscore(self):
if os.path.exists(self.highscore_file):
with open(self.highscore_file, 'r') as file:
try:
return int(file.read())
except ValueError:
return 0
return 0
def save_highscore(self):
with open(self.highscore_file, 'w') as file:
file.write(str(self.highscore))
def add_points(self, points):
self.score += points
if self.score > self.highscore:
self.highscore = self.score
self.save_highscore()
def add_lines(self, lines):
self.lines += lines
if lines > 2:
self.add_points(lines * lines * 100)
else:
self.add_points(lines * 100)
def level_up(self):
self.level += 1
def reset(self, reset_score=True, reset_lines=True, reset_level=True):
if reset_score:
self.score = 0
if reset_lines:
self.lines = 0
if reset_level:
self.level = 1
def draw(self, screen):
# Score (top-left)
score_text = self.font.render(f"Score:", True, self.color)
score = self.font.render(f"{self.score}", True, self.color)
screen.blit(score_text, (TILE_SIZE / 2, TILE_SIZE))
screen.blit(score,(TILE_SIZE / 2, TILE_SIZE + 24))
lines_text = self.font.render(f"Lines:", True, self.color)
lines = self.font.render(f"{self.lines}", True, self.color)
screen.blit(lines_text, (TILE_SIZE / 2, TILE_SIZE * 2 + 24))
screen.blit(lines, (TILE_SIZE / 2, TILE_SIZE * 3))
level_text = self.font.render(f"Level:", True, self.color)
level = self.font.render(f"{self.level}", True, self.color)
screen.blit(level_text, (TILE_SIZE / 2, TILE_SIZE * 4))
screen.blit(level, (TILE_SIZE / 2, TILE_SIZE * 4 + 24))
# Highscore (top-center)
highscore_text = self.font.render(f"High Score:", True, self.color)
highscore = self.font.render(f"{self.highscore}", True, self.color)
screen.blit(highscore_text, (TILE_SIZE / 2, TILE_SIZE * 5 + 24))
screen.blit(highscore, (TILE_SIZE / 2, TILE_SIZE * 6))
next_text = self.font.render("Next:", True, self.color)
screen.blit(next_text, (TILE_SIZE * 15, TILE_SIZE))