This commit is contained in:
2025-12-01 18:38:47 +09:00
parent 514b49f7d9
commit ae1ebdc6bf
27 changed files with 1965 additions and 597 deletions
+134
View File
@@ -0,0 +1,134 @@
import '../model/item.dart';
class ItemTemplate {
final String name;
final String description;
final int baseAtk;
final int baseHp;
final int baseArmor;
final EquipmentSlot slot;
const ItemTemplate({
required this.name,
required this.description,
this.baseAtk = 0,
this.baseHp = 0,
this.baseArmor = 0,
required this.slot,
});
// Create an instance of Item based on this template, optionally scaling with stage
Item createItem({int stage = 1}) {
// Simple scaling logic: add stage-1 to relevant stats
// You can make this more complex (multiplier, tiering, etc.)
int scaledAtk = baseAtk > 0 ? baseAtk + (stage - 1) : 0;
int scaledHp = baseHp > 0 ? baseHp + (stage - 1) * 5 : 0;
int scaledArmor = baseArmor > 0 ? baseArmor + (stage - 1) : 0;
return Item(
name: "$name${stage > 1 ? ' +${stage - 1}' : ''}", // Append +1, +2 etc.
description: description,
atkBonus: scaledAtk,
hpBonus: scaledHp,
armorBonus: scaledArmor,
slot: slot,
);
}
}
class ItemTable {
static const List<ItemTemplate> weapons = [
ItemTemplate(
name: "Rusty Dagger",
description: "Old and rusty, but better than nothing.",
baseAtk: 3,
slot: EquipmentSlot.weapon,
),
ItemTemplate(
name: "Iron Sword",
description: "A standard soldier's sword.",
baseAtk: 8,
slot: EquipmentSlot.weapon,
),
ItemTemplate(
name: "Battle Axe",
description: "Heavy but powerful.",
baseAtk: 12,
slot: EquipmentSlot.weapon,
),
];
static const List<ItemTemplate> armors = [
ItemTemplate(
name: "Torn Tunic",
description: "Offers minimal protection.",
baseHp: 10,
slot: EquipmentSlot.armor,
),
ItemTemplate(
name: "Leather Vest",
description: "Light and flexible.",
baseHp: 30,
slot: EquipmentSlot.armor,
),
ItemTemplate(
name: "Chainmail",
description: "Reliable protection against cuts.",
baseHp: 60,
slot: EquipmentSlot.armor,
),
];
static const List<ItemTemplate> shields = [
ItemTemplate(
name: "Pot Lid",
description: "It was used for cooking.",
baseArmor: 1,
slot: EquipmentSlot.shield,
),
ItemTemplate(
name: "Wooden Shield",
description: "Sturdy oak wood.",
baseArmor: 3,
slot: EquipmentSlot.shield,
),
ItemTemplate(
name: "Kite Shield",
description: "Used by knights.",
baseArmor: 6,
slot: EquipmentSlot.shield,
),
];
static const List<ItemTemplate> accessories = [
ItemTemplate(
name: "Old Ring",
description: "A tarnished ring.",
baseAtk: 1,
baseHp: 5,
slot: EquipmentSlot.accessory,
),
ItemTemplate(
name: "Ruby Amulet",
description: "Glows with a faint red light.",
baseAtk: 3,
baseHp: 15,
slot: EquipmentSlot.accessory,
),
ItemTemplate(
name: "Hero's Badge",
description: "A badge of honor.",
baseAtk: 5,
baseHp: 25,
baseArmor: 1,
slot: EquipmentSlot.accessory,
),
];
static List<ItemTemplate> get allItems => [
...weapons,
...armors,
...shields,
...accessories,
];
}
-42
View File
@@ -1,42 +0,0 @@
// lib/game/game_instance.dart
/// 앱 실행 시 가장 먼저 생성되는 싱글톤 진입점.
/// 게임의 핵심 데이터를 로드하고 관리한다.
class GameInstance {
// 싱글톤 인스턴스
static final GameInstance _instance = GameInstance._internal();
// 팩토리 생성자를 통해 싱글톤 인스턴스를 반환한다.
factory GameInstance() {
return _instance;
}
// 내부 생성자. 외부에서 직접 인스턴스 생성을 막는다.
GameInstance._internal();
bool _isInitialized = false;
/// 게임이 초기화되었는지 여부를 반환한다.
bool get isInitialized => _isInitialized;
/// 게임 초기화 로직.
/// 필요한 게임 데이터를 로드하고 시스템을 설정한다.
Future<void> initialize() async {
if (_isInitialized) {
print('GameInstance already initialized.');
return;
}
print('Initializing GameInstance...');
// TODO: 여기에 실제 게임 데이터 로드 및 초기화 로직 구현
// 예: 몬스터 데이터, 아이템 데이터, 플레이어 초기 데이터 등 로드
await Future.delayed(const Duration(seconds: 1)); // 초기화 지연 시뮬레이션
_isInitialized = true;
print('GameInstance initialized successfully.');
}
// TODO: 게임 전역에서 공유될 데이터 및 유틸리티 메서드 추가
}
-92
View File
@@ -1,92 +0,0 @@
// lib/game/game_manager.dart
import 'package:flutter/foundation.dart'; // ChangeNotifier를 사용하기 위해 필요
import 'package:game_test/game/model/entity.dart';
import 'package:game_test/game/game_instance.dart';
/// 게임의 상태(State)와 흐름을 관리하는 지휘자.
/// ChangeNotifier를 상속받아 UI에 게임 상태 변경을 알릴 수 있다.
class GameManager extends ChangeNotifier {
Player? _player;
List<Enemy> _currentEnemies = [];
GameManager() {
_init();
}
void _init() async {
// GameInstance가 초기화되었는지 확인
if (!GameInstance().isInitialized) {
await GameInstance().initialize();
}
// TODO: 게임 시작 시 필요한 초기화 로직 구현
// 예: 새로운 플레이어 생성, 첫 스테이지 몬스터 로드 등
_player = Player(id: 'player_001', name: '용감한 검투사', baseHp: 100);
_currentEnemies = [
Enemy(id: 'goblin_001', name: '고블린', baseHp: 50),
Enemy(id: 'goblin_002', name: '고블린', baseHp: 55),
];
print('GameManager initialized. Player: ${_player?.name}, Enemies: ${_currentEnemies.length}');
notifyListeners(); // UI에 초기 상태 변경 알림
}
/// 현재 플레이어를 반환한다.
Player? get player => _player;
/// 현재 전투 중인 적 리스트를 반환한다.
List<Enemy> get currentEnemies => _currentEnemies;
/// 플레이어의 턴 로직.
/// 선택된 행동(공격, 방어 등)과 강도(Risk)에 따라 게임 상태를 변경한다.
void playerTurn({required String action, required double risk}) {
// TODO: 행동 및 강도에 따른 로직 구현
print('Player performs $action with risk $risk');
// 예시: 간단한 공격 로직
if (action == 'attack' && _currentEnemies.isNotEmpty) {
final targetEnemy = _currentEnemies.first; // 첫 번째 적 공격
double damage = _player!.attack.value * risk; // 플레이어의 공격력과 강도에 따라 피해량 계산
targetEnemy.takeDamage(damage);
print('${_player?.name} attacked ${targetEnemy.name} for ${damage.toInt()} damage.');
print('${targetEnemy.name} HP: ${targetEnemy.hp.value.toInt()}');
if (!targetEnemy.isAlive) {
_currentEnemies.remove(targetEnemy);
print('${targetEnemy.name} defeated!');
}
}
notifyListeners(); // 게임 상태 변경 알림
// TODO: 적 턴 시작 로직 호출
if (_currentEnemies.isNotEmpty) {
_enemyTurn();
} else {
print('All enemies defeated! Moving to next stage.');
// TODO: 다음 스테이지 로직 구현
}
}
/// 적의 턴 로직.
void _enemyTurn() {
print('Enemy turn...');
for (var enemy in _currentEnemies) {
if (enemy.isAlive && _player != null) {
// TODO: 적 AI 로직 구현
double damageToPlayer = enemy.attack.value; // 적의 공격력 사용
_player!.takeDamage(damageToPlayer);
print('${enemy.name} attacked ${_player!.name} for ${damageToPlayer.toInt()} damage.');
print('${_player!.name} HP: ${_player!.hp.value.toInt()}');
if (!_player!.isAlive) {
print('Game Over!');
// TODO: 게임 오버 로직 구현
break;
}
}
}
notifyListeners(); // 게임 상태 변경 알림
}
// TODO: 추가적인 게임 흐름 관리 메서드 (예: 아이템 사용, 스킬 사용, 스테이지 전환 등)
}
+91 -105
View File
@@ -1,126 +1,112 @@
// lib/game/model/entity.dart
import 'item.dart';
import 'package:game_test/game/model/stat.dart';
import 'package:game_test/game/model/item.dart'; // Add this import
/// 모든 게임 엔티티의 기본 클래스.
/// 고유 ID와 이름을 가진다.
abstract class BaseEntity {
final String id;
class Character {
String name;
int hp;
int baseMaxHp;
int armor; // Current temporary shield/armor points in battle
int baseAtk;
int baseDefense; // Base defense stat
Map<EquipmentSlot, Item> equipment = {};
List<Item> inventory = [];
final int maxInventorySize = 16;
BaseEntity({required this.id, required this.name});
Character({
required this.name,
int? hp,
required int maxHp,
required this.armor,
required int atk,
this.baseDefense = 0,
}) : baseMaxHp = maxHp,
baseAtk = atk,
hp = hp ?? maxHp;
@override
String toString() => '$name (ID: $id)';
}
/// 생명력을 가진 엔티티 (플레이어, 적 등)의 추상 클래스.
/// BaseEntity를 상속받고, 체력(HP)과 스탯 맵을 포함한다.
abstract class LivingEntity extends BaseEntity {
Stat hp; // Health Points
final Map<String, Stat> stats = {}; // 다양한 스탯들을 관리하는 맵
LivingEntity({
required super.id,
required super.name,
required double baseHp,
}) : hp = Stat(baseValue: baseHp);
/// 특정 스탯을 추가한다.
void addStat(String statName, Stat stat) {
stats[statName] = stat;
int get totalMaxHp {
int bonus = equipment.values.fold(0, (sum, item) => sum + item.hpBonus);
return baseMaxHp + bonus;
}
/// 특정 스탯을 가져온다.
Stat? getStat(String statName) {
return stats[statName];
int get totalAtk {
int bonus = equipment.values.fold(0, (sum, item) => sum + item.atkBonus);
return baseAtk + bonus;
}
/// 엔티티가 살아있는지 여부를 반환한다.
bool get isAlive => hp.value > 0;
int get totalDefense {
int bonus = equipment.values.fold(0, (sum, item) => sum + item.armorBonus);
return baseDefense + bonus;
}
/// 엔티티에게 피해를 입힌다.
void takeDamage(double amount) {
hp.baseValue -= amount; // HP는 baseValue를 직접 감소시키는 것으로 처리.
if (hp.baseValue < 0) {
hp.baseValue = 0;
bool get isDead => hp <= 0;
// Adds an item to inventory, returns true if successful, false if inventory is full
bool addToInventory(Item item) {
if (inventory.length < maxInventorySize) {
inventory.add(item);
return true;
}
return false;
}
/// 엔티티를 치유한다.
void heal(double amount) {
hp.baseValue += amount;
// TODO: 최대 HP 제한 로직 추가 필요
}
// Equips an item (swapping if necessary)
// Returns true if successful
bool equip(Item newItem) {
if (!inventory.contains(newItem)) return false;
@override
String toString() {
return '${super.toString()}, HP: ${hp.value.toInt()}/${hp.baseValue.toInt()}';
}
}
// 1. Calculate current HP ratio before any changes
double hpRatio = totalMaxHp > 0 ? hp / totalMaxHp : 0.0; // Avoid division by zero
/// 플레이어 엔티티 클래스.
/// LivingEntity를 상속받으며 플레이어 특유의 로직을 추가할 수 있다.
class Player extends LivingEntity {
// 장비 슬롯 맵
final Map<EquipmentSlot, Weapon> _equippedWeapons = {};
/// 플레이어의 공격 스탯.
Stat attack;
Player({
required super.id,
required super.name,
required super.baseHp,
}) : attack = Stat(baseValue: 0.0) { // 공격 스탯 초기화
// 시작 시 맨손 무장
equipWeapon(Weapon.unArmed);
}
/// 현재 장비된 무기를 반환한다.
Weapon? get equippedWeapon => _equippedWeapons[EquipmentSlot.mainHand];
/// 무기를 장비한다.
/// 기존에 해당 슬롯에 장비된 무기가 있다면 해제하고 새로운 무기를 장비한다.
void equipWeapon(Weapon newWeapon) {
// 기존 무기가 있다면 해제
final currentWeapon = _equippedWeapons[newWeapon.slot];
if (currentWeapon != null) {
attack.removeModifier(currentWeapon.attackModifier);
// 2. Handle Swap: If slot is occupied, unequip the old item first
if (equipment.containsKey(newItem.slot)) {
Item oldItem = equipment[newItem.slot]!;
equipment.remove(newItem.slot);
inventory.add(oldItem);
}
// 새로운 무기 장비 및 수정자 적용
_equippedWeapons[newWeapon.slot] = newWeapon;
attack.addModifier(newWeapon.attackModifier);
// 3. Move new item: Inventory -> Equipment
inventory.remove(newItem);
equipment[newItem.slot] = newItem;
// 4. Update current HP based on the new totalMaxHp and previous ratio
hp = (totalMaxHp * hpRatio).toInt();
if (hp < 0) hp = 0; // Ensure HP does not go below zero
if (hp > totalMaxHp) {
hp = totalMaxHp; // Final Safety Clamp, though hpRatio <= 1.0 should prevent this
}
return true;
}
/// 장비된 무기를 해제한다.
/// 맨손 상태로 돌아간다.
void unequipWeapon(EquipmentSlot slot) {
final currentWeapon = _equippedWeapons[slot];
if (currentWeapon != null && currentWeapon != Weapon.unArmed) {
attack.removeModifier(currentWeapon.attackModifier);
_equippedWeapons.remove(slot);
// 맨손 상태로 복귀
equipWeapon(Weapon.unArmed);
// Unequips an item
// Returns true if successful (inventory has space)
bool unequip(Item item) {
if (!equipment.containsValue(item)) return false;
// 1. Calculate current HP ratio before any changes
double hpRatio = totalMaxHp > 0 ? hp / totalMaxHp : 0.0; // Avoid division by zero
if (inventory.length < maxInventorySize) {
equipment.remove(item.slot);
inventory.add(item);
// 2. Update current HP based on the new totalMaxHp and previous ratio
hp = (totalMaxHp * hpRatio).toInt();
if (hp < 0) hp = 0; // Ensure HP does not go below zero
if (hp > totalMaxHp) {
hp = totalMaxHp; // Final Safety Clamp, though hpRatio <= 1.0 should prevent this
}
return true;
}
return false;
}
void heal(int amount) {
if (isDead) return; // Cannot heal if dead
hp += amount;
if (hp > totalMaxHp) {
hp = totalMaxHp;
}
}
// TODO: 플레이어 고유의 인벤토리, 장비, 스킬 등의 시스템 추가
}
/// 적 엔티티 클래스.
/// LivingEntity를 상속받으며 적 특유의 로직을 추가할 수 있다.
class Enemy extends LivingEntity {
Stat attack; // 적도 공격 스탯을 가질 수 있도록 추가
Enemy({
required super.id,
required super.name,
required super.baseHp,
double baseAttack = 5.0, // 기본 공격력 설정
}) : attack = Stat(baseValue: baseAttack);
// TODO: 적 고유의 AI, 드롭 아이템 등의 시스템 추가
}
+24 -47
View File
@@ -1,55 +1,32 @@
// lib/game/model/item.dart
enum EquipmentSlot { weapon, armor, shield, accessory }
import 'package:game_test/game/model/stat.dart';
/// 장비할 수 있는 슬롯의 종류.
enum EquipmentSlot {
mainHand,
offHand,
head,
chest,
legs,
feet,
accessory,
}
/// 모든 게임 아이템의 기본 클래스.
/// ID, 이름, 설명을 가진다.
abstract class Item {
final String id;
class Item {
final String name;
final String description;
Item({
required this.id,
required this.name,
this.description = '',
});
@override
String toString() => name;
}
/// 무기 아이템 클래스.
/// 공격 스탯에 영향을 주는 수정자를 포함할 수 있다.
class Weapon extends Item {
final Modifier attackModifier;
final int atkBonus;
final int hpBonus;
final int armorBonus; // New stat for defense
final EquipmentSlot slot;
Weapon({
required super.id,
required super.name,
super.description,
required this.attackModifier,
this.slot = EquipmentSlot.mainHand,
Item({
required this.name,
required this.description,
required this.atkBonus,
required this.hpBonus,
this.armorBonus = 0, // Default to 0 for backward compatibility
required this.slot,
});
/// 플레이어가 무장하지 않았을 때의 기본 무기.
/// 베이스 공격력 1을 제공한다.
static Weapon get unArmed => Weapon(
id: 'unarmed_weapon',
name: '맨주먹',
description: '아무것도 장비하지 않은 상태의 공격.',
attackModifier: Modifier(type: ModifierType.flat, value: 1),
);
String get typeName {
switch (slot) {
case EquipmentSlot.weapon:
return "Weapon";
case EquipmentSlot.armor:
return "Armor";
case EquipmentSlot.shield:
return "Shield";
case EquipmentSlot.accessory:
return "Accessory";
}
}
}
+12 -108
View File
@@ -1,4 +1,7 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'providers/battle_provider.dart';
import 'screens/main_wrapper.dart';
void main() {
runApp(const MyApp());
@@ -7,116 +10,17 @@ void main() {
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => BattleProvider()),
],
child: MaterialApp(
title: "Colosseum's Choice",
theme: ThemeData.dark(),
home: const MainWrapper(),
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
}
+222
View File
@@ -0,0 +1,222 @@
import 'dart:math';
import 'package:flutter/foundation.dart';
import '../game/model/entity.dart';
import '../game/model/item.dart';
import '../game/data/item_table.dart'; // Import ItemTable
import '../utils/game_math.dart'; // Import GameMath
enum ActionType { attack, defend }
enum RiskLevel { safe, normal, risky }
class BattleProvider with ChangeNotifier {
late Character player;
late Character enemy;
List<String> battleLogs = [];
bool isPlayerTurn = true;
int stage = 1;
List<Item> rewardOptions = [];
bool showRewardPopup = false;
BattleProvider() {
initializeBattle();
}
void initializeBattle() {
stage = 1;
player = Character(name: "Player", maxHp: 100, armor: 0, atk: 10, baseDefense: 5); // Added baseDefense 5
// Provide starter equipment
final starterSword = Item(name: "Wooden Sword", description: "A basic sword", atkBonus: 5, hpBonus: 0, slot: EquipmentSlot.weapon);
final starterArmor = Item(name: "Leather Armor", description: "Basic protection", atkBonus: 0, hpBonus: 20, slot: EquipmentSlot.armor);
final starterShield = Item(name: "Wooden Shield", description: "A small shield", atkBonus: 0, hpBonus: 0, armorBonus: 3, slot: EquipmentSlot.shield);
final starterRing = Item(name: "Copper Ring", description: "A simple ring", atkBonus: 1, hpBonus: 5, slot: EquipmentSlot.accessory);
player.addToInventory(starterSword);
player.equip(starterSword);
player.addToInventory(starterArmor);
player.equip(starterArmor);
player.addToInventory(starterShield);
player.equip(starterShield);
player.addToInventory(starterRing);
player.equip(starterRing);
_spawnEnemy();
battleLogs.clear();
_addLog("Battle started! Stage $stage");
isPlayerTurn = true;
showRewardPopup = false;
notifyListeners();
}
void _spawnEnemy() {
int enemyHp = 5 + (stage - 1) * 20;
int enemyAtk = 8 + (stage - 1) * 2;
enemy = Character(name: "Enemy", maxHp: enemyHp, armor: 0, atk: enemyAtk);
}
void playerAction(ActionType type, RiskLevel risk) {
if (!isPlayerTurn || player.isDead || enemy.isDead || showRewardPopup) return;
isPlayerTurn = false;
notifyListeners();
_addLog("Player chose to ${type.name} with ${risk.name} risk.");
final random = Random();
bool success = false;
double efficiency = 1.0;
switch (risk) {
case RiskLevel.safe:
success = random.nextDouble() < 1.0; // 100%
efficiency = 0.5; // 50%
break;
case RiskLevel.normal:
success = random.nextDouble() < 0.8; // 80%
efficiency = 1.0; // 100%
break;
case RiskLevel.risky:
success = random.nextDouble() < 0.4; // 40%
efficiency = 2.0; // 200%
break;
}
if (success) {
if (type == ActionType.attack) {
int damage = (player.totalAtk * efficiency).toInt();
_applyDamage(enemy, damage);
_addLog("Player dealt $damage damage to Enemy.");
} else {
int armorGained = (player.totalDefense * efficiency).toInt(); // Changed to totalDefense
player.armor += armorGained;
_addLog("Player gained $armorGained armor.");
}
} else {
_addLog("Player's action missed!");
}
if (enemy.isDead) {
_onVictory();
return;
}
Future.delayed(const Duration(seconds: 1), () => _enemyTurn());
}
Future<void> _enemyTurn() async {
if (!isPlayerTurn && (player.isDead || enemy.isDead)) return; // Check if it's the enemy's turn and battle is over
_addLog("Enemy's turn...");
// Enemy attacks player
await Future.delayed(const Duration(seconds: 1)); // Simulating thinking time
int incomingDamage = enemy.totalAtk;
int damageToHp = 0;
if (player.armor > 0) {
if (player.armor >= incomingDamage) {
player.armor -= incomingDamage;
damageToHp = 0;
_addLog("Armor absorbed all $incomingDamage damage.");
} else {
damageToHp = incomingDamage - player.armor;
_addLog("Armor absorbed ${player.armor} damage.");
player.armor = 0;
}
} else {
damageToHp = incomingDamage;
}
if (damageToHp > 0) {
_applyDamage(player, damageToHp);
_addLog("Enemy dealt $damageToHp damage to Player HP.");
}
// Player's turn starts, armor decays
if (player.armor > 0) {
player.armor = (player.armor * 0.5).toInt();
_addLog("Player's armor decayed to ${player.armor}.");
}
if (player.isDead) {
_addLog("Player defeated! Enemy wins!");
}
isPlayerTurn = true;
notifyListeners();
}
void _applyDamage(Character target, int damage) {
target.hp -= damage;
if (target.hp < 0) target.hp = 0;
}
void _addLog(String message) {
battleLogs.add(message);
notifyListeners();
}
void _onVictory() {
_addLog("Enemy defeated! Choose a reward.");
final random = Random();
List<ItemTemplate> allTemplates = List.from(ItemTable.allItems);
allTemplates.shuffle(random); // Shuffle to randomize selection
// Take first 3 items (ensure distinct templates if possible, though list is small now)
int count = min(3, allTemplates.length);
rewardOptions = allTemplates.sublist(0, count).map((template) {
return template.createItem(stage: stage);
}).toList();
showRewardPopup = true;
notifyListeners();
}
void selectReward(Item item) {
bool added = player.addToInventory(item);
if (added) {
_addLog("Added ${item.name} to inventory.");
} else {
_addLog("Inventory is full! ${item.name} discarded.");
}
// Heal player after selecting reward
int healAmount = GameMath.floor(player.totalMaxHp * 0.5);
player.heal(healAmount);
_addLog("Stage Cleared! Recovered $healAmount HP.");
stage++;
showRewardPopup = false;
_spawnEnemy();
_addLog("Stage $stage started! A wild ${enemy.name} appeared.");
isPlayerTurn = true;
notifyListeners();
}
void equipItem(Item item) {
if (player.equip(item)) {
_addLog("Equipped ${item.name}.");
} else {
_addLog("Failed to equip ${item.name}."); // Should not happen if logic is correct
}
notifyListeners();
}
void unequipItem(Item item) {
if (player.unequip(item)) {
_addLog("Unequipped ${item.name}.");
} else {
_addLog("Failed to unequip ${item.name} (Inventory might be full).");
}
notifyListeners();
}
}
+313
View File
@@ -0,0 +1,313 @@
import 'package:flutter/material.dart';
import 'package:game_test/game/model/item.dart';
import 'package:provider/provider.dart';
import '../providers/battle_provider.dart';
import '../game/model/entity.dart';
class BattleScreen extends StatefulWidget {
const BattleScreen({super.key});
@override
State<BattleScreen> createState() => _BattleScreenState();
}
class _BattleScreenState extends State<BattleScreen> {
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
// Scroll to the bottom of the log when new messages are added
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _showRiskLevelSelection(BuildContext context, ActionType actionType) {
final player = context.read<BattleProvider>().player;
final baseValue = actionType == ActionType.attack
? player.totalAtk
: player.totalDefense;
showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: Text("Select Risk Level for ${actionType.name}"),
children: RiskLevel.values.map((risk) {
String infoText = "";
Color infoColor = Colors.black;
double efficiency = 0.0;
int expectedValue = 0;
switch (risk) {
case RiskLevel.safe:
efficiency = 0.5;
infoColor = Colors.green;
break;
case RiskLevel.normal:
efficiency = 1.0;
infoColor = Colors.blue;
break;
case RiskLevel.risky:
efficiency = 2.0;
infoColor = Colors.red;
break;
}
expectedValue = (baseValue * efficiency).toInt();
String valueUnit = actionType == ActionType.attack
? "Dmg"
: "Armor";
String successRate = "";
switch (risk) {
case RiskLevel.safe:
successRate = "100%";
break;
case RiskLevel.normal:
successRate = "80%";
break;
case RiskLevel.risky:
successRate = "40%";
break;
}
infoText =
"Success: $successRate, Eff: ${(efficiency * 100).toInt()}% ($expectedValue $valueUnit)";
return SimpleDialogOption(
onPressed: () {
context.read<BattleProvider>().playerAction(actionType, risk);
Navigator.pop(context);
// Ensure the log scrolls to the bottom after action
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
});
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
risk.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
Text(
infoText,
style: TextStyle(fontSize: 12, color: infoColor),
),
],
),
);
}).toList(),
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Consumer<BattleProvider>(
builder: (context, provider, child) =>
Text("Colosseum's Choice - Stage ${provider.stage}"),
),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () => context.read<BattleProvider>().initializeBattle(),
),
],
),
body: Consumer<BattleProvider>(
builder: (context, battleProvider, child) {
return Stack(
children: [
Column(
children: [
// Top (Status Area)
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildCharacterStatus(
battleProvider.enemy,
isEnemy: true,
),
_buildCharacterStatus(
battleProvider.player,
isEnemy: false,
),
],
),
),
// Middle (Log Area)
Expanded(
child: Container(
color: Colors.black87,
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
controller: _scrollController,
itemCount: battleProvider.battleLogs.length,
itemBuilder: (context, index) {
return Text(
battleProvider.battleLogs[index],
style: const TextStyle(
color: Colors.white,
fontFamily: 'Monospace',
fontSize: 12,
),
);
},
),
),
),
// Bottom (Control Area)
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildActionButton(
context,
"ATTACK",
ActionType.attack,
battleProvider.isPlayerTurn &&
!battleProvider.player.isDead &&
!battleProvider.enemy.isDead &&
!battleProvider.showRewardPopup,
),
_buildActionButton(
context,
"DEFEND",
ActionType.defend,
battleProvider.isPlayerTurn &&
!battleProvider.player.isDead &&
!battleProvider.enemy.isDead &&
!battleProvider.showRewardPopup,
),
],
),
),
],
),
if (battleProvider.showRewardPopup)
Container(
color: Colors.black54,
child: Center(
child: SimpleDialog(
title: const Text("Victory! Choose a Reward"),
children: battleProvider.rewardOptions.map((item) {
return SimpleDialogOption(
onPressed: () {
battleProvider.selectReward(item);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
_buildItemStatText(item), // Display stats here
Text(
item.description,
style: const TextStyle(
fontSize: 12,
color: Colors.grey,
),
),
],
),
);
}).toList(),
),
),
),
],
);
},
),
);
}
Widget _buildItemStatText(Item item) {
List<String> stats = [];
if (item.atkBonus > 0) stats.add("+${item.atkBonus} ATK");
if (item.hpBonus > 0) stats.add("+${item.hpBonus} HP");
if (item.armorBonus > 0) stats.add("+${item.armorBonus} DEF");
if (stats.isEmpty) return const SizedBox.shrink(); // Hide if no stats
return Padding(
padding: const EdgeInsets.only(top: 4.0, bottom: 4.0),
child: Text(
stats.join(", "),
style: const TextStyle(fontSize: 12, color: Colors.blueAccent),
),
);
}
Widget _buildCharacterStatus(Character character, {bool isEnemy = false}) {
return Column(
children: [
Text(
"${character.name}: HP ${character.hp}/${character.totalMaxHp}",
style: TextStyle(
color: character.isDead ? Colors.red : Colors.white,
fontWeight: FontWeight.bold,
),
),
SizedBox(
width: 100,
child: LinearProgressIndicator(
value: character.totalMaxHp > 0
? character.hp / character.totalMaxHp
: 0,
color: isEnemy ? Colors.red : Colors.green,
backgroundColor: Colors.grey,
),
),
if (!isEnemy) ...[
Text("Armor: ${character.armor}"),
Text("ATK: ${character.totalAtk}"),
Text("DEF: ${character.totalDefense}"),
],
],
);
}
Widget _buildActionButton(
BuildContext context,
String text,
ActionType actionType,
bool isEnabled,
) {
return ElevatedButton(
onPressed: isEnabled
? () => _showRiskLevelSelection(context, actionType)
: null,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 15),
backgroundColor: Colors.blueGrey,
foregroundColor: Colors.white,
textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
child: Text(text),
);
}
}
+408
View File
@@ -0,0 +1,408 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/battle_provider.dart';
import '../game/model/item.dart';
import '../game/model/entity.dart';
class InventoryScreen extends StatelessWidget {
const InventoryScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Inventory & Stats")),
body: Consumer<BattleProvider>(
builder: (context, battleProvider, child) {
final player = battleProvider.player;
return Column(
children: [
// Player Stats Header
Card(
margin: const EdgeInsets.all(16.0),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text(
player.name,
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 8),
Text("Stage: ${battleProvider.stage}"),
const Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_buildStatItem(
"HP",
"${player.hp}/${player.totalMaxHp}",
),
_buildStatItem("ATK", "${player.totalAtk}"),
_buildStatItem("DEF", "${player.totalDefense}"),
_buildStatItem("Shield", "${player.armor}"), // Temporary armor points
],
),
],
),
),
),
// Equipped Items Section (Slot based)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 8.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
"Equipped Items",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: EquipmentSlot.values.map((slot) {
final item = player.equipment[slot];
return Expanded(
child: InkWell(
onTap: item != null
? () => _showUnequipConfirmationDialog(context, battleProvider, item)
: null,
child: Card(
color: item != null
? Colors.blueGrey[600]
: Colors.grey[800],
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text(
slot.name.toUpperCase(),
style: const TextStyle(
fontSize: 10,
fontWeight: FontWeight.bold,
color: Colors.grey,
),
),
const SizedBox(height: 4),
Icon(
_getIconForSlot(slot),
size: 24,
color: item != null
? Colors.white
: Colors.grey,
),
const SizedBox(height: 4),
Text(
item?.name ?? "Empty",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: item != null
? Colors.white
: Colors.grey,
),
overflow: TextOverflow.ellipsis,
),
if (item != null) _buildItemStatText(item),
],
),
),
),
),
);
}).toList(),
),
],
),
),
// Inventory (Bag) Section
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 8.0,
),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
"Bag (${player.inventory.length}/${player.maxInventorySize})",
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
),
Expanded(
child: GridView.builder(
padding: const EdgeInsets.all(16.0),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
),
itemCount: player.maxInventorySize,
itemBuilder: (context, index) {
if (index < player.inventory.length) {
final item = player.inventory[index];
return InkWell(
onTap: () {
// Show confirmation dialog before equipping
_showEquipConfirmationDialog(
context,
battleProvider,
item,
);
},
child: Card(
color: Colors.blueGrey[700],
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.backpack, size: 32),
Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
item.name,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 10),
overflow: TextOverflow.ellipsis,
),
),
_buildItemStatText(item),
],
),
),
);
} else {
// Empty slot
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
color: Colors.grey[800],
),
child: const Center(
child: Icon(Icons.add_box, color: Colors.grey),
),
);
}
},
),
),
],
);
},
),
);
}
IconData _getIconForSlot(EquipmentSlot slot) {
switch (slot) {
case EquipmentSlot.weapon:
return Icons.g_mobiledata; // Using a generic 'game' icon for weapon
case EquipmentSlot.armor:
return Icons.checkroom;
case EquipmentSlot.shield:
return Icons.shield;
case EquipmentSlot.accessory:
return Icons.diamond;
}
}
Widget _buildStatItem(String label, String value) {
return Column(
children: [
Text(label, style: const TextStyle(color: Colors.grey, fontSize: 12)),
Text(
value,
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
],
);
}
void _showEquipConfirmationDialog(
BuildContext context,
BattleProvider provider,
Item newItem,
) {
final player = provider.player;
final oldItem = player.equipment[newItem.slot];
// Calculate predicted stats
final currentMaxHp = player.totalMaxHp;
final currentAtk = player.totalAtk;
final currentDef = player.totalDefense;
final currentHp = player.hp;
// Predict new stats
int newMaxHp = currentMaxHp - (oldItem?.hpBonus ?? 0) + newItem.hpBonus;
int newAtk = currentAtk - (oldItem?.atkBonus ?? 0) + newItem.atkBonus;
int newDef = currentDef - (oldItem?.armorBonus ?? 0) + newItem.armorBonus;
// Predict HP (Percentage Logic)
double ratio = currentMaxHp > 0 ? currentHp / currentMaxHp : 0.0;
int newHp = (newMaxHp * ratio).toInt();
if (newHp < 0) newHp = 0;
if (newHp > newMaxHp) newHp = newMaxHp;
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Change Equipment"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Equip ${newItem.name}?",
style: const TextStyle(fontWeight: FontWeight.bold),
),
if (oldItem != null)
Text(
"Replaces ${oldItem.name}",
style: const TextStyle(fontSize: 12, color: Colors.grey),
),
const SizedBox(height: 16),
_buildStatChangeRow("Max HP", currentMaxHp, newMaxHp),
_buildStatChangeRow("Current HP", currentHp, newHp),
_buildStatChangeRow("ATK", currentAtk, newAtk),
_buildStatChangeRow("DEF", currentDef, newDef),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text("Cancel"),
),
ElevatedButton(
onPressed: () {
provider.equipItem(newItem);
Navigator.pop(ctx);
},
child: const Text("Confirm"),
),
],
),
);
}
void _showUnequipConfirmationDialog(
BuildContext context,
BattleProvider provider,
Item itemToUnequip,
) {
final player = provider.player;
// Calculate predicted stats
final currentMaxHp = player.totalMaxHp;
final currentAtk = player.totalAtk;
final currentDef = player.totalDefense;
final currentHp = player.hp;
// Predict new stats (Subtract item bonuses)
int newMaxHp = currentMaxHp - itemToUnequip.hpBonus;
int newAtk = currentAtk - itemToUnequip.atkBonus;
int newDef = currentDef - itemToUnequip.armorBonus;
// Predict HP (Percentage Logic)
double ratio = currentMaxHp > 0 ? currentHp / currentMaxHp : 0.0;
int newHp = (newMaxHp * ratio).toInt();
if (newHp < 0) newHp = 0;
if (newHp > newMaxHp) newHp = newMaxHp;
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Unequip Item"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Unequip ${itemToUnequip.name}?",
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
_buildStatChangeRow("Max HP", currentMaxHp, newMaxHp),
_buildStatChangeRow("Current HP", currentHp, newHp),
_buildStatChangeRow("ATK", currentAtk, newAtk),
_buildStatChangeRow("DEF", currentDef, newDef),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text("Cancel"),
),
ElevatedButton(
onPressed: () {
provider.unequipItem(itemToUnequip);
Navigator.pop(ctx);
},
child: const Text("Confirm"),
),
],
),
);
}
Widget _buildStatChangeRow(String label, int oldVal, int newVal) {
int diff = newVal - oldVal;
Color color = diff > 0
? Colors.green
: (diff < 0 ? Colors.red : Colors.grey);
String diffText = diff > 0 ? "(+$diff)" : (diff < 0 ? "($diff)" : "");
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label),
Row(
children: [
Text("$oldVal", style: const TextStyle(color: Colors.grey)),
const Icon(Icons.arrow_right, size: 16, color: Colors.grey),
Text(
"$newVal",
style: const TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(width: 4),
Text(
diffText,
style: TextStyle(
color: color,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
);
}
Widget _buildItemStatText(Item item) {
List<String> stats = [];
if (item.atkBonus > 0) stats.add("+${item.atkBonus} ATK");
if (item.hpBonus > 0) stats.add("+${item.hpBonus} HP");
if (item.armorBonus > 0) stats.add("+${item.armorBonus} DEF");
if (stats.isEmpty) return const SizedBox.shrink(); // Hide if no stats
return Padding(
padding: const EdgeInsets.only(top: 2.0, bottom: 2.0),
child: Text(
stats.join(", "),
style: const TextStyle(fontSize: 10, color: Colors.blueAccent),
),
);
}
}
+47
View File
@@ -0,0 +1,47 @@
import 'package:flutter/material.dart';
import 'battle_screen.dart';
import 'inventory_screen.dart';
class MainWrapper extends StatefulWidget {
const MainWrapper({super.key});
@override
State<MainWrapper> createState() => _MainWrapperState();
}
class _MainWrapperState extends State<MainWrapper> {
int _currentIndex = 0;
final List<Widget> _screens = [
const BattleScreen(),
const InventoryScreen(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _currentIndex,
children: _screens,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.flash_on),
label: 'Battle',
),
BottomNavigationBarItem(
icon: Icon(Icons.backpack),
label: 'Inventory',
),
],
),
);
}
}
+5
View File
@@ -0,0 +1,5 @@
class GameMath {
static int floor(double value) {
return value.floor();
}
}