-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFortnite Advanced Training Simulator
509 lines (412 loc) · 18.6 KB
/
Fortnite Advanced Training Simulator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
from pathlib import Path
import os
import pygame
import numpy as np
import random
import threading
import time
from dataclasses import dataclass
from typing import List, Dict, Tuple
import sqlite3
from enum import Enum
import math
import os
from pathlib import Path
# Константи
SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 768
FPS = 60
COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0)]
INITIAL_TARGET_LIFETIME = 2000 # милисекунди
INITIAL_SHOOT_DELAY = 100 # милисекунди
INACTIVITY_TIMEOUT = 100000 # милисекунди/100000 = 100 секунди
class GameState(Enum):
MENU = 1
PLAYING = 2
PAUSED = 3
GAME_OVER = 4
@dataclass
class PlayerStats:
reaction_times: List[float]
accuracy_by_section: Dict[int, List[bool]]
current_score: int
total_shots: int
successful_shots: int
last_activity_time: float
class Target:
def __init__(self, x: float, y: float, radius: float, color: Tuple[int, int, int],
is_fake: bool = False, hits_required: int = 1):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.is_fake = is_fake
self.hits_required = hits_required
self.current_hits = 0
self.creation_time = time.time()
self.velocity = [random.uniform(-2, 2), random.uniform(-2, 2)]
def update(self):
self.x += self.velocity[0]
self.y += self.velocity[1]
# Отскачане от стените
if self.x - self.radius <= 0 or self.x + self.radius >= SCREEN_WIDTH:
self.velocity[0] *= -1
if self.y - self.radius <= 0 or self.y + self.radius >= SCREEN_HEIGHT:
self.velocity[1] *= -1
def is_hit(self, mouse_x: float, mouse_y: float) -> bool:
distance = math.sqrt((mouse_x - self.x)**2 + (mouse_y - self.y)**2)
return distance <= self.radius
class ScreenAnalyzer:
def __init__(self, level: int):
self.level = level
self.sections = self._create_sections()
def _create_sections(self) -> List[Tuple[int, int, int, int]]:
base_sections = 6
sections_count = base_sections + (self.level - 1) * 2
# Създаване на мрежа от секции
cols = int(math.sqrt(sections_count))
rows = math.ceil(sections_count / cols)
section_width = SCREEN_WIDTH // cols
section_height = SCREEN_HEIGHT // rows
sections = []
for row in range(rows):
for col in range(cols):
if len(sections) >= sections_count:
break
sections.append((
col * section_width,
row * section_height,
section_width,
section_height
))
return sections
def get_section(self, x: float, y: float) -> int:
for i, (sx, sy, sw, sh) in enumerate(self.sections):
if sx <= x < sx + sw and sy <= y < sy + sh:
return i
return -1
class PlayerAnalyzer:
def __init__(self):
self.stats = PlayerStats([], {}, 0, 0, 0, time.time())
def update_stats(self, section: int, reaction_time: float, hit: bool):
self.stats.reaction_times.append(reaction_time)
if section not in self.stats.accuracy_by_section:
self.stats.accuracy_by_section[section] = []
self.stats.accuracy_by_section[section].append(hit)
self.stats.total_shots += 1
if hit:
self.stats.successful_shots += 1
# Изчисляване на точки за успешен изстрел
# По-бързата реакция носи повече точки
if reaction_time > 0: # Проверка дали има валидно време за реакция
speed_bonus = max(0, 1000 - reaction_time) / 10
accuracy_bonus = self.get_accuracy() * 100
self.stats.current_score += int(50 +
speed_bonus + accuracy_bonus)
self.stats.last_activity_time = time.time()
def get_accuracy(self) -> float:
if self.stats.total_shots == 0:
return 0
return self.stats.successful_shots / self.stats.total_shots
def get_weak_sections(self) -> List[int]:
weak_sections = []
for section, hits in self.stats.accuracy_by_section.items():
if len(hits) > 0 and sum(hits) / len(hits) < 0.5:
weak_sections.append(section)
return weak_sections
class SoundManager:
"""Клас за управление на звуците в играта.
Ако липсват звукови файлове или папката assets, играта продължава без звук."""
def __init__(self):
self.sounds = {}
self.sound_enabled = False
try:
pygame.mixer.init()
self.sound_enabled = True
self._load_sounds()
except (pygame.error, Exception) as e:
print(f"Warning: Sound system initialization failed: {e}")
self.sound_enabled = False
def _load_sounds(self):
"""Зарежда звуковите файлове от папката assets"""
sound_files = {
'shoot': 'assets/shoot.wav',
'hit': 'assets/hit.wav',
'level_up': 'assets/level_up.wav'
}
# Проверява дали съществува папката assets
if not Path('assets').exists():
print("Warning: 'assets' directory not found")
return
# Зарежда всеки звук поотделно
for sound_name, sound_path in sound_files.items():
try:
if Path(sound_path).exists():
self.sounds[sound_name] = pygame.mixer.Sound(sound_path)
else:
print(f"Warning: Sound file not found: {sound_path}")
except (pygame.error, FileNotFoundError) as e:
print(f"Warning: Failed to load sound '{sound_name}': {e}")
def play_sound(self, sound_name: str):
"""Възпроизвежда звук ако е наличен и системата работи"""
if not self.sound_enabled:
return
if sound_name in self.sounds:
try:
volume = random.uniform(0.6, 1.0)
self.sounds[sound_name].set_volume(volume)
self.sounds[sound_name].play()
except pygame.error as e:
print(f"Warning: Failed to play sound '{sound_name}': {e}")
def cleanup(self):
"""Освобождава ресурсите на звуковата система"""
try:
if self.sound_enabled:
pygame.mixer.quit()
except pygame.error:
pass
class DifficultyManager:
def __init__(self):
self.current_level = 1
self.current_score_threshold = 1000 # Начален праг за преминаване на ниво
def should_level_up(self, score: int, play_time: float) -> bool:
min_time_reached = play_time >= 30 # 1/2 минута минимум
score_threshold_reached = score >= self.current_score_threshold * 0.7
if min_time_reached and score_threshold_reached:
print(f"Level up! Score: {score}, Threshold: {
self.current_score_threshold * 0.7}")
return True
return False
def calculate_level_parameters(self) -> dict:
return {
'target_lifetime': max(500, INITIAL_TARGET_LIFETIME / (1 + 0.3 * self.current_level)),
'shoot_delay': min(500, INITIAL_SHOOT_DELAY * (1 + 0.2 * self.current_level)),
'fake_target_count': 3 + self.current_level,
'hits_required': 1 + self.current_level // 2,
'cursor_shake_intensity': max(0, (self.current_level - 2) * 5),
'enemy_fire_rate': max(0, (self.current_level - 2) * 0.5)
}
class TargetManager:
def __init__(self, screen_analyzer: ScreenAnalyzer, difficulty_manager: DifficultyManager):
self.targets: List[Target] = []
self.screen_analyzer = screen_analyzer
self.difficulty_manager = difficulty_manager
self.last_target_time = time.time()
def update_targets(self):
current_time = time.time()
params = self.difficulty_manager.calculate_level_parameters()
# Премахване на мишени, които са извън екрана
self.targets = [target for target in self.targets
if (current_time - target.creation_time) * 1000 < params['target_lifetime']]
# Обновяване на мишените
for target in self.targets:
target.update()
def spawn_target(self, weak_sections: List[int]):
params = self.difficulty_manager.calculate_level_parameters()
# Случайно място за появяване на мишените
if weak_sections and random.random() < 0.7:
section = random.choice(weak_sections)
section_rect = self.screen_analyzer.sections[section]
x = random.uniform(
section_rect[0], section_rect[0] + section_rect[2])
y = random.uniform(
section_rect[1], section_rect[1] + section_rect[3])
else:
x = random.uniform(0, SCREEN_WIDTH)
y = random.uniform(0, SCREEN_HEIGHT)
is_fake = random.random() < (params['fake_target_count'] / 20)
target = Target(
x=x,
y=y,
radius=20,
color=random.choice(COLORS),
is_fake=is_fake,
hits_required=params['hits_required']
)
self.targets.append(target)
class GameEngine:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Fortnite Aim Trainer")
self.clock = pygame.time.Clock()
self.game_state = GameState.MENU
self.difficulty_manager = DifficultyManager()
self.screen_analyzer = ScreenAnalyzer(
self.difficulty_manager.current_level)
self.target_manager = TargetManager(
self.screen_analyzer, self.difficulty_manager)
self.player_analyzer = PlayerAnalyzer()
self.sound_manager = SoundManager()
self.last_shot_time = 0
self.game_start_time = time.time()
self.cursor_pos = [SCREEN_WIDTH//2, SCREEN_HEIGHT//2]
def handle_input(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.handle_shot()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.game_state = GameState.MENU
elif event.key == pygame.K_SPACE and self.game_state == GameState.MENU:
self.start_new_game()
return True
def handle_shot(self):
current_time = time.time()
params = self.difficulty_manager.calculate_level_parameters()
if (current_time - self.last_shot_time) * 1000 < params['shoot_delay']:
return
self.last_shot_time = current_time
self.sound_manager.play_sound('shoot')
mouse_x, mouse_y = pygame.mouse.get_pos()
section = self.screen_analyzer.get_section(mouse_x, mouse_y)
hit = False
for target in self.target_manager.targets:
if not target.is_fake and target.is_hit(mouse_x, mouse_y):
target.current_hits += 1
if target.current_hits >= target.hits_required:
self.target_manager.targets.remove(target)
self.sound_manager.play_sound('hit')
hit = True
reaction_time = (current_time - target.creation_time) * 1000
self.player_analyzer.update_stats(section, reaction_time, True)
break
if not hit:
self.player_analyzer.update_stats(section, 0, False)
def update_cursor_position(self):
if self.difficulty_manager.current_level > 2:
params = self.difficulty_manager.calculate_level_parameters()
shake = params['cursor_shake_intensity']
self.cursor_pos[0] += random.uniform(-shake, shake)
self.cursor_pos[1] += random.uniform(-shake, shake)
# Ограничаване на позицията на курсора в границите на екрана
self.cursor_pos[0] = max(0, min(SCREEN_WIDTH, self.cursor_pos[0]))
self.cursor_pos[1] = max(0, min(SCREEN_HEIGHT, self.cursor_pos[1]))
pygame.mouse.set_pos(self.cursor_pos)
class GameEngine(GameEngine): # Продължение на класа
def render(self):
self.screen.fill((0, 0, 0)) # Черен фон
if self.game_state == GameState.MENU:
self.render_menu()
elif self.game_state == GameState.PLAYING:
self.render_game()
elif self.game_state == GameState.GAME_OVER:
self.render_game_over()
pygame.display.flip()
def render_menu(self):
font = pygame.font.Font(None, 74)
title = font.render('Fortnite Aim Trainer', True, (255, 255, 255))
start = font.render('Press SPACE to Start', True, (255, 255, 255))
self.screen.blit(
title, (SCREEN_WIDTH//2 - title.get_width()//2, SCREEN_HEIGHT//3))
self.screen.blit(
start, (SCREEN_WIDTH//2 - start.get_width()//2, SCREEN_HEIGHT//2))
def render_game(self):
# Рендериране на мишените
for target in self.target_manager.targets:
color = target.color if not target.is_fake else (100, 100, 100)
pygame.draw.circle(self.screen, color, (int(
target.x), int(target.y)), int(target.radius))
if target.hits_required > 1:
font = pygame.font.Font(None, 24)
hits_left = font.render(
str(target.hits_required - target.current_hits), True, (255, 255, 255))
self.screen.blit(
hits_left, (target.x - hits_left.get_width()//2, target.y - hits_left.get_height()//2))
# Рендериране на рамката (мигаща)
if self.difficulty_manager.current_level > 1:
border_color = (255, 0, 0) if time.time() % (
0.5 / self.difficulty_manager.current_level) < 0.25 else (0, 0, 0)
pygame.draw.rect(self.screen, border_color,
(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 3)
# Показване на статистика и ниво на играча
self.render_stats()
def render_stats(self):
font = pygame.font.Font(None, 36)
stats = [
f"Level: {self.difficulty_manager.current_level}",
f"Score: {self.player_analyzer.stats.current_score}",
f"Accuracy: {self.player_analyzer.get_accuracy():.1%}",
f"Time: {int(time.time() - self.game_start_time)}s"
]
for i, stat in enumerate(stats):
text = font.render(stat, True, (255, 255, 255))
self.screen.blit(text, (10, 10 + i * 30))
def render_game_over(self):
font = pygame.font.Font(None, 74)
game_over = font.render('Game Over', True, (255, 0, 0))
score = font.render(f'Final Score: {
self.player_analyzer.stats.current_score}', True, (255, 255, 255))
restart = font.render('Press SPACE to Restart', True, (255, 255, 255))
self.screen.blit(game_over, (SCREEN_WIDTH//2 -
game_over.get_width()//2, SCREEN_HEIGHT//3))
self.screen.blit(
score, (SCREEN_WIDTH//2 - score.get_width()//2, SCREEN_HEIGHT//2))
self.screen.blit(restart, (SCREEN_WIDTH//2 -
restart.get_width()//2, 2*SCREEN_HEIGHT//3))
def start_new_game(self):
self.game_state = GameState.PLAYING
self.difficulty_manager.current_level = 1
self.screen_analyzer = ScreenAnalyzer(
self.difficulty_manager.current_level)
self.target_manager = TargetManager(
self.screen_analyzer, self.difficulty_manager)
self.player_analyzer = PlayerAnalyzer()
self.game_start_time = time.time()
self.last_shot_time = 0
def update(self):
if self.game_state != GameState.PLAYING:
return
current_time = time.time()
# Проверка за неактивност
if current_time - self.player_analyzer.stats.last_activity_time > INACTIVITY_TIMEOUT / 1000:
self.game_state = GameState.GAME_OVER
return
# Обновяване на мишените
self.target_manager.update_targets()
# Създаване на нови мишени
if random.random() < 0.02: # 2% шанс на всеки фрейм
self.target_manager.spawn_target(
self.player_analyzer.get_weak_sections())
# Обновяване на позицията на курсора
self.update_cursor_position()
# Проверка за преминаване на следващо ниво
if self.difficulty_manager.should_level_up(
self.player_analyzer.stats.current_score,
current_time - self.game_start_time
):
self.level_up()
def level_up(self):
print(f"Advancing from level {self.difficulty_manager.current_level} to {self.difficulty_manager.current_level + 1}")
self.difficulty_manager.current_level += 1
# Увеличаване на прага за преминаване на следващо ниво
self.difficulty_manager.current_score_threshold *= 1.5
def run(self):
running = True
while running:
running = self.handle_input()
self.update()
self.render()
self.clock.tick(FPS)
def cleanup(self):
self.sound_manager.cleanup()
pygame.quit()
def run(self):
running = True
try:
while running:
running = self.handle_input()
self.update()
self.render()
self.clock.tick(FPS)
finally:
self.cleanup()
pygame.quit()
# Стартиране на играта
if __name__ == "__main__":
game = GameEngine()
game.run()
game.cleanup()
# Край на кода