dividir por zona de pontos

This commit is contained in:
2026-03-09 15:05:14 +00:00
parent f7efe47907
commit 3dbccdc823
2 changed files with 186 additions and 63 deletions

View File

@@ -9,7 +9,7 @@ class ShotRecord {
}
class PlacarController {
final String gameId; // O ID real do jogo na base de dados
final String gameId;
final String myTeam;
final String opponentTeam;
final VoidCallback onUpdate;
@@ -22,7 +22,7 @@ class PlacarController {
});
bool isLoading = true;
bool isSaving = false; // Para mostrar o ícone de loading a guardar
bool isSaving = false;
int myScore = 0;
int opponentScore = 0;
@@ -32,8 +32,8 @@ class PlacarController {
int myTimeoutsUsed = 0;
int opponentTimeoutsUsed = 0;
String? myTeamDbId; // ID da tua equipa na BD
String? oppTeamDbId; // ID da equipa adversária na BD
String? myTeamDbId;
String? oppTeamDbId;
List<String> myCourt = [];
List<String> myBench = [];
@@ -42,7 +42,7 @@ class PlacarController {
Map<String, String> playerNumbers = {};
Map<String, Map<String, int>> playerStats = {};
Map<String, String> playerDbIds = {}; // NOVO: Mapeia o Nome do jogador -> UUID na base de dados
Map<String, String> playerDbIds = {};
bool showMyBench = false;
bool showOppBench = false;
@@ -56,58 +56,87 @@ class PlacarController {
Timer? timer;
bool isRunning = false;
Future<void> loadPlayers() async {
// --- 🔄 CARREGAMENTO COMPLETO (DADOS REAIS + ESTATÍSTICAS SALVAS) ---
Future<void> loadPlayers() async {
final supabase = Supabase.instance.client;
try {
// 1. Limpeza de segurança para evitar duplicados em "Hot Reload"
myCourt.clear(); myBench.clear(); oppCourt.clear(); oppBench.clear();
playerStats.clear(); playerNumbers.clear(); playerDbIds.clear();
myFouls = 0; opponentFouls = 0;
await Future.delayed(const Duration(milliseconds: 1500));
// 2. Buscar dados do JOGO (Placar)
final gameResponse = await supabase.from('games').select().eq('id', gameId).single();
myScore = gameResponse['my_score'] ?? 0;
opponentScore = gameResponse['opponent_score'] ?? 0;
// 1. Limpar estados para evitar duplicação
myCourt.clear();
myBench.clear();
oppCourt.clear();
oppBench.clear();
playerStats.clear();
playerNumbers.clear();
playerDbIds.clear();
myFouls = 0;
opponentFouls = 0;
// 3. Buscar IDs das Equipas
// 2. Buscar dados básicos do JOGO
final gameResponse = await supabase.from('games').select().eq('id', gameId).single();
myScore = int.tryParse(gameResponse['my_score']?.toString() ?? '0') ?? 0;
opponentScore = int.tryParse(gameResponse['opponent_score']?.toString() ?? '0') ?? 0;
int totalSeconds = int.tryParse(gameResponse['remaining_seconds']?.toString() ?? '600') ?? 600;
duration = Duration(seconds: totalSeconds);
myTimeoutsUsed = int.tryParse(gameResponse['my_timeouts']?.toString() ?? '0') ?? 0;
opponentTimeoutsUsed = int.tryParse(gameResponse['opp_timeouts']?.toString() ?? '0') ?? 0;
currentQuarter = int.tryParse(gameResponse['current_quarter']?.toString() ?? '1') ?? 1;
// 3. Buscar os IDs das equipas
final teamsResponse = await supabase.from('teams').select('id, name').inFilter('name', [myTeam, opponentTeam]);
for (var t in teamsResponse) {
if (t['name'] == myTeam) myTeamDbId = t['id'];
if (t['name'] == opponentTeam) oppTeamDbId = t['id'];
}
// 4. Buscar Membros e ESTATÍSTICAS existentes
final myPlayers = myTeamDbId != null ? await supabase.from('members').select().eq('team_id', myTeamDbId!).eq('type', 'Jogador') : [];
final oppPlayers = oppTeamDbId != null ? await supabase.from('members').select().eq('team_id', oppTeamDbId!).eq('type', 'Jogador') : [];
// Buscar todas as stats deste jogo de uma vez
// 4. Buscar os Jogadores
List<dynamic> myPlayers = myTeamDbId != null ? await supabase.from('members').select().eq('team_id', myTeamDbId!).eq('type', 'Jogador') : [];
List<dynamic> oppPlayers = oppTeamDbId != null ? await supabase.from('members').select().eq('team_id', oppTeamDbId!).eq('type', 'Jogador') : [];
// 5. BUSCAR ESTATÍSTICAS JÁ SALVAS
final statsResponse = await supabase.from('player_stats').select().eq('game_id', gameId);
final Map<String, dynamic> savedStatsMap = {
for (var s in statsResponse) s['member_id'].toString(): s
final Map<String, dynamic> savedStats = {
for (var item in statsResponse) item['member_id'].toString(): item
};
// 5. Processar Minha Equipa
// 6. Registar a tua equipa
for (int i = 0; i < myPlayers.length; i++) {
String dbId = myPlayers[i]['id'].toString();
String name = myPlayers[i]['name'].toString();
_registerPlayer(name: name, number: myPlayers[i]['number']?.toString() ?? "0", dbId: dbId, isMyTeam: true, isCourt: i < 5);
if (savedStatsMap.containsKey(dbId)) {
_injectStats(name, savedStatsMap[dbId], true);
_registerPlayer(name: name, number: myPlayers[i]['number']?.toString() ?? "0", dbId: dbId, isMyTeam: true, isCourt: i < 5);
if (savedStats.containsKey(dbId)) {
var s = savedStats[dbId];
playerStats[name] = {
"pts": s['pts'] ?? 0, "rbs": s['rbs'] ?? 0, "ast": s['ast'] ?? 0,
"stl": s['stl'] ?? 0, "tov": s['tov'] ?? 0, "blk": s['blk'] ?? 0,
"fls": s['fls'] ?? 0, "fgm": s['fgm'] ?? 0, "fga": s['fga'] ?? 0,
};
myFouls += (s['fls'] as int? ?? 0);
}
}
_padTeam(myCourt, myBench, "Jogador", isMyTeam: true);
// 6. Processar Adversário
// 7. Registar a equipa adversária
for (int i = 0; i < oppPlayers.length; i++) {
String dbId = oppPlayers[i]['id'].toString();
String name = oppPlayers[i]['name'].toString();
_registerPlayer(name: name, number: oppPlayers[i]['number']?.toString() ?? "0", dbId: dbId, isMyTeam: false, isCourt: i < 5);
if (savedStatsMap.containsKey(dbId)) {
_injectStats(name, savedStatsMap[dbId], false);
if (savedStats.containsKey(dbId)) {
var s = savedStats[dbId];
playerStats[name] = {
"pts": s['pts'] ?? 0, "rbs": s['rbs'] ?? 0, "ast": s['ast'] ?? 0,
"stl": s['stl'] ?? 0, "tov": s['tov'] ?? 0, "blk": s['blk'] ?? 0,
"fls": s['fls'] ?? 0, "fgm": s['fgm'] ?? 0, "fga": s['fga'] ?? 0,
};
opponentFouls += (s['fls'] as int? ?? 0);
}
}
_padTeam(oppCourt, oppBench, "Adversário", isMyTeam: false);
@@ -115,29 +144,18 @@ class PlacarController {
isLoading = false;
onUpdate();
} catch (e) {
debugPrint("Erro ao carregar: $e");
debugPrint("Erro ao retomar jogo: $e");
_padTeam(myCourt, myBench, "Falha", isMyTeam: true);
_padTeam(oppCourt, oppBench, "Falha Opp", isMyTeam: false);
isLoading = false;
onUpdate();
}
}
// Função auxiliar para injetar os dados salvos
void _injectStats(String playerName, Map<String, dynamic> s, bool isMyTeam) {
playerStats[playerName] = {
"pts": s['pts'] ?? 0, "rbs": s['rbs'] ?? 0, "ast": s['ast'] ?? 0,
"stl": s['stl'] ?? 0, "tov": s['tov'] ?? 0, "blk": s['blk'] ?? 0,
"fls": s['fls'] ?? 0, "fgm": s['fgm'] ?? 0, "fga": s['fga'] ?? 0,
};
if (isMyTeam) myFouls += (s['fls'] as int? ?? 0);
else opponentFouls += (s['fls'] as int? ?? 0);
}
void _registerPlayer({required String name, required String number, String? dbId, required bool isMyTeam, required bool isCourt}) {
if (playerNumbers.containsKey(name)) name = "$name (Opp)";
playerNumbers[name] = number;
if (dbId != null) playerDbIds[name] = dbId; // Só guarda na lista de IDs se for um jogador real da BD
if (dbId != null) playerDbIds[name] = dbId;
playerStats[name] = {"pts": 0, "rbs": 0, "ast": 0, "stl": 0, "tov": 0, "blk": 0, "fls": 0, "fgm": 0, "fga": 0};
if (isMyTeam) {
@@ -154,7 +172,6 @@ class PlacarController {
}
// --- TEMPO E TIMEOUTS ---
// (Mantive o teu código original igualzinho aqui)
void toggleTimer(BuildContext context) {
if (isRunning) {
timer?.cancel();
@@ -195,7 +212,7 @@ class PlacarController {
String formatTime() => "${duration.inMinutes.toString().padLeft(2, '0')}:${duration.inSeconds.remainder(60).toString().padLeft(2, '0')}";
// --- LÓGICA DE JOGO ---
// --- LÓGICA DE JOGO & VALIDAÇÃO GEOMÉTRICA DE ZONAS ---
void handleActionDrag(BuildContext context, String action, String playerData) {
String name = playerData.replaceAll("player_my_", "").replaceAll("player_opp_", "");
final stats = playerStats[name]!;
@@ -239,16 +256,66 @@ class PlacarController {
onUpdate();
}
void registerShotLocation(Offset position) {
// AGORA RECEBE CONTEXT E SIZE PARA A MATEMÁTICA
void registerShotLocation(BuildContext context, Offset position, Size size) {
if (pendingAction == null || pendingPlayer == null) return;
bool is3Pt = pendingAction!.contains("_3");
bool is2Pt = pendingAction!.contains("_2");
// Validação
if (is3Pt || is2Pt) {
bool isValid = _validateShotZone(position, size, is3Pt);
if (!isValid) {
// Se a validação falhar, fudeo. Bloqueia.
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(' Local de lançamento incompatível com a pontuação.'),
backgroundColor: Colors.red,
duration: Duration(seconds: 2),
)
);
return; // Aborta!
}
}
bool isMake = pendingAction!.startsWith("add_pts_");
matchShots.add(ShotRecord(position, isMake));
commitStat(pendingAction!, pendingPlayer!);
isSelectingShotLocation = false;
pendingAction = null;
pendingPlayer = null;
onUpdate();
}
// A MATEMÁTICA DA ZONA
bool _validateShotZone(Offset pos, Size size, bool is3Pt) {
double w = size.width;
double h = size.height;
// Ajusta o 0.12 e 0.88 se os teus cestos na imagem estiverem mais para o lado
Offset leftHoop = Offset(w * 0.12, h * 0.5);
Offset rightHoop = Offset(w * 0.88, h * 0.5);
// O raio da linha de 3 pontos (Brinca com este 0.28 se a área ficar muito grande ou pequena)
double threePointRadius = w * 0.28;
Offset activeHoop = pos.dx < w / 2 ? leftHoop : rightHoop;
double distanceToHoop = (pos - activeHoop).distance;
// Zonas de canto (onde a linha de 3 é reta)
bool isCorner3 = (pos.dy < h * 0.15 || pos.dy > h * 0.85) &&
(pos.dx < w * 0.20 || pos.dx > w * 0.80);
if (is3Pt) {
return distanceToHoop >= threePointRadius || isCorner3;
} else {
return distanceToHoop < threePointRadius && !isCorner3;
}
}
void cancelShotLocation() {
isSelectingShotLocation = false;
pendingAction = null;
@@ -296,25 +363,25 @@ class PlacarController {
// --- 💾 FUNÇÃO PARA GUARDAR DADOS NA BD ---
Future<void> saveGameStats(BuildContext context) async {
final supabase = Supabase.instance.client;
isSaving = true;
onUpdate();
try {
// 1. Atualizar o resultado final na tabela 'games'
await supabase.from('games').update({
'my_score': myScore,
'opponent_score': opponentScore,
'remaining_seconds': duration.inSeconds,
'my_timeouts': myTimeoutsUsed,
'opp_timeouts': opponentTimeoutsUsed,
'current_quarter': currentQuarter,
'status': currentQuarter >= 4 && duration.inSeconds == 0 ? 'Terminado' : 'Pausado',
}).eq('id', gameId);
// 2. Preparar a lista de estatísticas individuais
List<Map<String, dynamic>> batchStats = [];
playerStats.forEach((playerName, stats) {
String? memberDbId = playerDbIds[playerName]; // Vai buscar o UUID real do jogador
String? memberDbId = playerDbIds[playerName];
// Só guarda se for um jogador real (com ID) e se tiver feito ALGUMA coisa (pontos, faltas, etc)
if (memberDbId != null && stats.values.any((val) => val > 0)) {
bool isMyTeamPlayer = myCourt.contains(playerName) || myBench.contains(playerName);
String teamId = isMyTeamPlayer ? myTeamDbId! : oppTeamDbId!;
@@ -336,10 +403,8 @@ class PlacarController {
}
});
// 3. Apagar stats antigas deste jogo para não haver duplicados caso cliques no botão "Guardar" 2 vezes
await supabase.from('player_stats').delete().eq('game_id', gameId);
// 4. Inserir as novas estatísticas de todos os jogadores de uma vez
if (batchStats.isNotEmpty) {
await supabase.from('player_stats').insert(batchStats);
}

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:playmaker/controllers/placar_controller.dart';
import 'package:playmaker/widgets/placar_widgets.dart';
import 'dart:math' as math;
class PlacarPage extends StatefulWidget {
final String gameId, myTeam, opponentTeam;
@@ -17,7 +18,10 @@ class _PlacarPageState extends State<PlacarPage> {
@override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft]);
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
_controller = PlacarController(
gameId: widget.gameId,
@@ -37,7 +41,6 @@ class _PlacarPageState extends State<PlacarPage> {
super.dispose();
}
// Função auxiliar para criar o botão de arrastar faltas que não está no painel inferior
Widget _buildFloatingFoulBtn(String label, Color color, String action, IconData icon, double left, double right, double top, double h) {
return Positioned(
top: top,
@@ -47,7 +50,11 @@ class _PlacarPageState extends State<PlacarPage> {
data: action,
feedback: Material(
color: Colors.transparent,
child: CircleAvatar(radius: 30, backgroundColor: color.withOpacity(0.8), child: Icon(icon, color: Colors.white)),
child: CircleAvatar(
radius: 30,
backgroundColor: color.withOpacity(0.8),
child: Icon(icon, color: Colors.white)
),
),
child: Column(
children: [
@@ -66,9 +73,54 @@ class _PlacarPageState extends State<PlacarPage> {
@override
Widget build(BuildContext context) {
if (_controller.isLoading) {
return const Scaffold(
backgroundColor: Color(0xFF266174),
body: Center(child: CircularProgressIndicator(color: Colors.white)),
return Scaffold(
backgroundColor: const Color(0xFF16202C),
body: Stack(
children: [
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"PREPARANDO O PAVILHÃO",
style: TextStyle(color: Colors.white24, fontSize: 28, fontWeight: FontWeight.bold, letterSpacing: 2)
),
const SizedBox(height: 15),
StreamBuilder(
stream: Stream.periodic(const Duration(seconds: 3)),
builder: (context, snapshot) {
List<String> frases = [
"O Treinador está a desenhar a tática...",
"A encher as bolas com ar de campeão...",
"O árbitro está a testar o apito...",
"A verificar se o cesto está nivelado...",
"Os jogadores estão a terminar o aquecimento..."
];
String frase = frases[DateTime.now().second % frases.length];
return Text(
frase,
style: TextStyle(color: Colors.orange.withOpacity(0.7), fontSize: 18, fontStyle: FontStyle.italic)
);
},
),
],
),
),
TweenAnimationBuilder<double>(
tween: Tween(begin: 0.0, end: 1.0),
duration: const Duration(milliseconds: 1500),
builder: (context, value, child) {
double bounce = (math.sin(value * math.pi * 4)).abs();
return AnimatedAlign(
duration: const Duration(milliseconds: 1500),
alignment: Alignment(value > 0.5 ? 0.9 : -0.9, 0.7 - (bounce * 0.4)),
child: const Icon(Icons.sports_basketball, size: 70, color: Colors.orange),
);
},
onEnd: () => setState(() {}),
),
],
),
);
}
@@ -89,7 +141,14 @@ class _PlacarPageState extends State<PlacarPage> {
// --- MAPA DO CAMPO ---
GestureDetector(
onTapDown: (details) {
if (_controller.isSelectingShotLocation) _controller.registerShotLocation(details.localPosition);
if (_controller.isSelectingShotLocation) {
// AQUI É QUE A MAGIA ACONTECE! Passamos o tamanho exato do layout
_controller.registerShotLocation(
context,
details.localPosition,
Size(w, h)
);
}
},
child: Container(
decoration: const BoxDecoration(
@@ -120,7 +179,6 @@ class _PlacarPageState extends State<PlacarPage> {
],
// --- BOTÕES DE FALTA (FLUTUANTES) ---
// Estes são os botões que você pediu, posicionados em relação ao centro
if (!_controller.isSelectingShotLocation) ...[
_buildFloatingFoulBtn("FALTA +", Colors.orange, "add_foul", Icons.sports, w * 0.38, 0, h * 0.30, h),
_buildFloatingFoulBtn("FALTA -", Colors.redAccent, "sub_foul", Icons.block, 0, w * 0.38, h * 0.30, h),