diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp index 431763d87c..bf20cbee90 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.cpp @@ -15,7 +15,7 @@ const EnumDropdownDatabase& BBQuests_database(){ static EnumDropdownDatabase database{ {BBQuests::auto_10, "auto-10", "Defeat 10 wild Pokemon using Auto Battle!"}, {BBQuests::make_tm, "make-tm", "Make yourself a TM!"}, - //{BBQuests::pickup_10, "pickup-10", "Pick up items on the ground 10 times!"}, + {BBQuests::pickup_10, "pickup-10", "Pick up items on the ground 10 times!"}, {BBQuests::sneak_up, "sneak-up", "Successfully sneak up on 1 Pokemon and surprise them with a battle!"}, {BBQuests::photo_fly, "photo-fly", "Take a photo of a wild Pokemon in flight!"}, {BBQuests::photo_swim, "photo-swim", "Take a photo of a wild Pokemon that is swimming!"}, @@ -108,8 +108,9 @@ BBQuestTable::BBQuestTable() "Exclude the quests in the table. If you want to skip a quest, select it below. " "(Quests can be explicitly included, but this is not necessary.) " "Do not exclude too many quests, as rerolling costs BP. " - "The program will automatically reroll all quests if none are possible, but will not handle being out of BP. " - "Does not include egg hatching or pickup quests, as eggs are handled in other options and pickup is not possible. ", + "If no quest is possible, the program rerolls one quest it cannot do, or all quests if there is none. " + "Quests the program cannot do, such as pickup, are never run, but can be rerolled or skipped here. " + "Does not include egg hatching, as eggs are handled in other options. ", //"Duplicates of the same quest", //duplicates will work in table order. might lead to weird behavior like rerolling and then marking a quest as complete. //won't break the program though. @@ -149,7 +150,7 @@ BBQOption::BBQOption(OCR::LanguageOCROption* language_option) 1000 ) , SAVE_NUM_QUESTS( - "Save and reset the game after attempting this many quests:
This preserves progress and prevents potential game lags from long runs.
0 disables this option.", + "Save and reset the game after completing this many quests:
This preserves progress and prevents potential game lags from long runs.
0 disables this option.", LockMode::UNLOCK_WHILE_RUNNING, 50 ) , INVERTED_FLIGHT( @@ -190,6 +191,16 @@ BBQOption::BBQOption(OCR::LanguageOCROption* language_option) "Number of Retries:
Reattempt a quest this many times if it fails.", LockMode::UNLOCK_WHILE_RUNNING, 1, 0, 5 ) + , OUT_OF_RETRIES( + "Out of Retries:
When a quest fails all its retries, do the selected option.", + { + {OutOfRetries::Skip, "skip", "Skip Quest - Not attempted again while it stays on the panel"}, + {OutOfRetries::Reroll, "reroll", "Reroll Quest - Costs BP"}, + {OutOfRetries::Stop, "stop", "Stop Program"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + OutOfRetries::Skip + ) , FIX_TIME_WHEN_DONE( "Fix Time when Done:
Fix the time after the program finishes.", LockMode::UNLOCK_WHILE_RUNNING, false @@ -210,6 +221,7 @@ BBQOption::BBQOption(OCR::LanguageOCROption* language_option) PA_ADD_OPTION(BATTLE_AI); PA_ADD_OPTION(CATCH_ON_WIN); PA_ADD_OPTION(NUM_RETRIES); + PA_ADD_OPTION(OUT_OF_RETRIES); PA_ADD_OPTION(FIX_TIME_WHEN_DONE); } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h index f5715a10c7..0f45903656 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h @@ -74,6 +74,12 @@ class BBQOption : public GroupOption{ KeepGoing, }; + enum class OutOfRetries{ + Skip, + Reroll, + Stop, + }; + OCR::LanguageOCROption& LANGUAGE; SimpleIntegerOption NUM_QUESTS; @@ -98,6 +104,7 @@ class BBQOption : public GroupOption{ TeraFarmerCatchOnWin CATCH_ON_WIN; SimpleIntegerOption NUM_RETRIES; + EnumDropdownOption OUT_OF_RETRIES; BooleanCheckBoxOption FIX_TIME_WHEN_DONE; diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.cpp new file mode 100644 index 0000000000..38295e00c7 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.cpp @@ -0,0 +1,102 @@ +/* BBQ Diagnostic Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "PokemonSV_BBQLogger.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +namespace{ + +constexpr std::string_view UNKNOWN = "unknown"; + +std::string_view quest_label(BBQuests quest){ + const std::string& slug = BBQuests_enum_to_string(quest); + return slug.empty() ? UNKNOWN : std::string_view(slug); +} + +void append_elapsed(std::ostream& out, std::string_view field, BBQAttemptLog::Clock::duration elapsed){ + const auto milliseconds = std::chrono::duration_cast(elapsed); + out << ' ' << field << "_ms=" << milliseconds.count() + << ' ' << field << "=\"" << duration_to_string(milliseconds) << '\"'; +} + +} // namespace + + +void BBQLogger::board(bool panel_detected, const std::vector& quests){ + std::ostringstream out; + out << "BBQ event=board panel_detected=" << panel_detected << " quests="; + bool first = true; + for (BBQuests quest : quests){ + if (!first){ + out << ','; + } + first = false; + out << quest_label(quest); + } + m_logger.log(out.str()); +} + +void BBQLogger::reroll_attempt(size_t slot, BBQuests quest){ + m_logger.log( + "Rerolling quest " + std::to_string(slot + 1) + " (" + std::string(quest_label(quest)) + ")." + ); +} + +void BBQLogger::battle_entry_timeout(BBQuests quest){ + std::ostringstream out; + out << "BBQ quest=" << quest_label(quest) << " event=battle_entry outcome=timeout"; + m_logger.log(out.str()); +} + +void BBQLogger::retry_exhausted(BBQuests quest){ + std::ostringstream out; + out << "BBQ quest=" << quest_label(quest) << " event=retry_exhausted recovery=skip_current_batch"; + m_logger.log(out.str(), COLOR_RED); +} + + +BBQAttemptLog::BBQAttemptLog( + Logger& logger, BBQuests quest, + unsigned attempt, unsigned limit, + Clock::time_point start +) + : m_logger(logger), m_start(start), m_route_end(start) +{ + std::ostringstream out; + out << "BBQ quest=" << quest_label(quest) << " attempt=" << attempt << " limit=" << limit; + m_attempt_description = out.str(); + out << " event=start"; + m_logger.log(out.str()); +} + +void BBQAttemptLog::route_return(Clock::time_point end){ + m_route_end = end; + std::ostringstream out; + out << m_attempt_description << " event=route_return"; + append_elapsed(out, "elapsed", end - m_start); + m_logger.log(out.str()); +} + +void BBQAttemptLog::result(bool completed, Clock::time_point end){ + std::ostringstream out; + out << m_attempt_description << " event=result outcome=" + << (completed ? "absent_from_board" : "still_on_board"); + append_elapsed(out, "verification", end - m_route_end); + append_elapsed(out, "total", end - m_start); + m_logger.log(out.str()); +} + + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.h new file mode 100644 index 0000000000..f6ab0adb7a --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.h @@ -0,0 +1,76 @@ +/* BBQ Diagnostic Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BBQLogger_H +#define PokemonAutomation_PokemonSV_BBQLogger_H + +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "VideoGames/PokemonSV/Options/PokemonSV_BBQuests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Formats one-line "BBQ ..." diagnostic events through an existing Logger. +// Does no image I/O and no controller input. +class BBQLogger{ +public: + explicit BBQLogger(Logger& logger) : m_logger(logger) {} + + // The quest board as read from one panel snapshot: whether the panel was + // detected, and the quests in board order. + void board(bool panel_detected, const std::vector& quests); + + // Logs a zero-based board slot before attempting its reroll, including failures. + void reroll_attempt(size_t slot, BBQuests quest); + + // A catch quest gave up waiting for the battle menu after navigating to its target. + void battle_entry_timeout(BBQuests quest); + + // A quest used all of its attempts and the rest of the batch will be skipped. + void retry_exhausted(BBQuests quest); + +private: + Logger& m_logger; +}; + + +// The event sequence and monotonic timing of one quest attempt. +// Timestamps default to now; tests pass fixed values. +class BBQAttemptLog{ +public: + using Clock = std::chrono::steady_clock; + + // Logs the start of attempt number `attempt` out of `limit`. + BBQAttemptLog( + Logger& logger, BBQuests quest, + unsigned attempt, unsigned limit, + Clock::time_point start = Clock::now() + ); + + // The quest routine returned; logs the time since start. + void route_return(Clock::time_point end = Clock::now()); + + // The board was re-read. `completed` means the quest is no longer on it. + // Logs the verification time since route_return() and the total time. + void result(bool completed, Clock::time_point end = Clock::now()); + +private: + Logger& m_logger; + const Clock::time_point m_start; + Clock::time_point m_route_end; + std::string m_attempt_description; +}; + + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.cpp new file mode 100644 index 0000000000..a250b58cff --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.cpp @@ -0,0 +1,193 @@ +/* BBQ Diagnostic Logger Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "PokemonSV_BBQLogger.h" +#include "PokemonSV_BBQLogger_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +// Captures the production Logger interface without image or controller I/O. +class BBQTestLogger : public Logger{ +public: + virtual void log(const std::string& message, Color color) override{ + messages.push_back(message); + colors.push_back(color); + } + std::vector messages; + std::vector colors; +}; + +// One board snapshot and its detection outcome. +struct BoardLogInput{ + bool panel_detected; + std::vector quests; +}; + +// One timed attempt, including optional timeout and retry-exhaustion events. +struct AttemptLogInput{ + BBQuests quest; + unsigned attempt; + unsigned limit; + std::chrono::milliseconds route_duration; + std::chrono::milliseconds verification_duration; + bool completed; + bool battle_timeout = false; + bool retry_exhausted = false; +}; + +// A row exercises one board read or one complete attempt event sequence. +struct DiagnosticLogInput{ + std::string name; + std::variant event; +}; + +// Exact message order is part of the diagnostics contract. +struct DiagnosticLogExpectation{ + std::vector messages; + Color final_color{}; +}; + +// Each case keeps all inputs and expected output visible together. +struct DiagnosticLogCase{ + DiagnosticLogInput input; + DiagnosticLogExpectation expectation; +}; + +// Exercise the real formatter with a scripted board observation. +void emit_logs(Logger& logger, const BoardLogInput& input){ + BBQLogger(logger).board(input.panel_detected, input.quests); +} + +// Fixed monotonic timestamps make durations and event order deterministic. +void emit_logs(Logger& logger, const AttemptLogInput& input){ + const BBQAttemptLog::Clock::time_point start{}; + if (input.battle_timeout){ + BBQLogger(logger).battle_entry_timeout(input.quest); + } + BBQAttemptLog attempt(logger, input.quest, input.attempt, input.limit, start); + attempt.route_return(start + input.route_duration); + attempt.result(input.completed, start + input.route_duration + input.verification_duration); + if (input.retry_exhausted){ + BBQLogger(logger).retry_exhausted(input.quest); + } +} + +// Report the first missing, unexpected or mismatched message with its index. +class Test_BBQDiagnosticLogs : public UnitTest{ +public: + explicit Test_BBQDiagnosticLogs(DiagnosticLogCase test_case) + : UnitTest("PokemonSV::BBQDiagnosticLogs - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + BBQTestLogger logger; + std::visit([&](const auto& input){ emit_logs(logger, input); }, m_case.input.event); + const auto& expected = m_case.expectation.messages; + if (logger.messages.size() != expected.size()){ + return "Expected " + std::to_string(expected.size()) + " log messages; read " + + std::to_string(logger.messages.size()) + "."; + } + for (size_t index = 0; index < expected.size(); index++){ + if (logger.messages[index] != expected[index]){ + return "Message " + std::to_string(index) + ": expected [" + expected[index] + + "]; read [" + logger.messages[index] + "]."; + } + } + if (logger.colors.back() != m_case.expectation.final_color){ + return "Final message color differs from the expected severity."; + } + return true; + } + +private: + const DiagnosticLogCase m_case; +}; + +// Covers board order/unknown/empty output and success, exhaustion and long durations. +const DiagnosticLogCase DIAGNOSTIC_LOG_CASES[] = { + { + .input = {.name = "board-order", .event = BoardLogInput{ + .panel_detected = true, + .quests = {BBQuests::photo_swim, BBQuests::sneak_up, BBQuests::auto_10}, + }}, + .expectation = {.messages = { + "BBQ event=board panel_detected=1 quests=photo-swim,sneak-up,auto-10", + }}, + }, + { + .input = {.name = "undetected-board", .event = BoardLogInput{ + .panel_detected = false, .quests = {BBQuests::UnableToDetect}, + }}, + .expectation = {.messages = {"BBQ event=board panel_detected=0 quests=unknown"}}, + }, + { + .input = {.name = "empty-board", .event = BoardLogInput{ + .panel_detected = true, .quests = {}, + }}, + .expectation = {.messages = {"BBQ event=board panel_detected=1 quests="}}, + }, + { + .input = {.name = "success", .event = AttemptLogInput{ + .quest = BBQuests::make_tm, .attempt = 1, .limit = 2, + .route_duration = std::chrono::milliseconds(2000), + .verification_duration = std::chrono::milliseconds(500), .completed = true, + }}, + .expectation = {.messages = { + "BBQ quest=make-tm attempt=1 limit=2 event=start", + "BBQ quest=make-tm attempt=1 limit=2 event=route_return elapsed_ms=2000 elapsed=\"2.000 seconds\"", + "BBQ quest=make-tm attempt=1 limit=2 event=result outcome=absent_from_board verification_ms=500 verification=\"0.500 seconds\" total_ms=2500 total=\"2.500 seconds\"", + }}, + }, + { + .input = {.name = "retry-exhausted", .event = AttemptLogInput{ + .quest = BBQuests::catch_any, .attempt = 2, .limit = 2, + .route_duration = std::chrono::milliseconds(3345), + .verification_duration = std::chrono::milliseconds(765), .completed = false, + .battle_timeout = true, .retry_exhausted = true, + }}, + .expectation = {.messages = { + "BBQ quest=catch-any event=battle_entry outcome=timeout", + "BBQ quest=catch-any attempt=2 limit=2 event=start", + "BBQ quest=catch-any attempt=2 limit=2 event=route_return elapsed_ms=3345 elapsed=\"3.345 seconds\"", + "BBQ quest=catch-any attempt=2 limit=2 event=result outcome=still_on_board verification_ms=765 verification=\"0.765 seconds\" total_ms=4110 total=\"4.110 seconds\"", + "BBQ quest=catch-any event=retry_exhausted recovery=skip_current_batch", + }, .final_color = COLOR_RED}, + }, + { + .input = {.name = "long-duration", .event = AttemptLogInput{ + .quest = BBQuests::UnableToDetect, .attempt = 256, .limit = 256, + .route_duration = std::chrono::milliseconds(120000), + .verification_duration = std::chrono::milliseconds(0), .completed = false, + }}, + .expectation = {.messages = { + "BBQ quest=unknown attempt=256 limit=256 event=start", + "BBQ quest=unknown attempt=256 limit=256 event=route_return elapsed_ms=120000 elapsed=\"2.000 minutes\"", + "BBQ quest=unknown attempt=256 limit=256 event=result outcome=still_on_board verification_ms=0 verification=\"0.000 seconds\" total_ms=120000 total=\"2.000 minutes\"", + }}, + }, +}; + +} // namespace + +void add_tests_BBQDiagnosticLogs(UnitTestDatabase& database){ + for (const DiagnosticLogCase& test_case : DIAGNOSTIC_LOG_CASES){ + database.add(test_case); + } +} + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.h new file mode 100644 index 0000000000..24ba73f8ea --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.h @@ -0,0 +1,22 @@ +/* BBQ Diagnostic Logger Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BBQLogger_Tests_H +#define PokemonAutomation_PokemonSV_BBQLogger_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Registers deterministic event formatting and ordering tests; no console input. +void add_tests_BBQDiagnosticLogs(UnitTestDatabase& database); + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.cpp new file mode 100644 index 0000000000..9c3fd32ed3 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.cpp @@ -0,0 +1,85 @@ +/* BBQ Points Ledger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_BBQPointsLedger.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +void BBQPointsLedger::record(int read, WallClock when){ + if (read < 0){ + // The next read may include quest income, so this window can't be checked. + m_pending_unchecked |= m_pending_spend > 0; + return; + } + if (m_pending_spend > 0 && starting_balance >= 0 && !m_pending_unchecked){ + checked_windows++; + const int change = read - balance; + if (change != -m_pending_spend){ + mismatched_windows++; + last_mismatch = "rerolls should have cost " + std::to_string(m_pending_spend) + + " BP, but the balance went from " + std::to_string(balance) + + " to " + std::to_string(read); + } + } + m_pending_spend = 0; + m_pending_unchecked = false; + if (starting_balance < 0){ + starting_balance = read; + first_read = when; + }else if (read > balance){ + earned += read - balance; + }else{ + spent += balance - read; + } + balance = read; + last_read = when; +} + +void BBQPointsLedger::expect_spend(int bp){ + m_pending_spend += bp; + expected_spent += bp; +} +void BBQPointsLedger::skip_spend_check(){ + m_pending_unchecked = true; +} + +bool BBQPointsLedger::reconciled() const{ + return starting_balance >= 0 + && (int64_t)balance - starting_balance == net() + && mismatched_windows == 0; +} +std::string BBQPointsLedger::reconciliation() const{ + if (starting_balance < 0){ + return "BP check: no balance was read."; + } + std::string str = "BP check: " + std::string(reconciled() ? "OK" : "MISMATCH") + + ". Balance " + std::to_string(starting_balance) + " -> " + std::to_string(balance) + + " (change " + std::to_string((int64_t)balance - starting_balance) + + "), stats net " + std::to_string(net()) + + ". Rerolls expected to cost " + std::to_string(expected_spent) + + " BP; " + std::to_string(checked_windows - mismatched_windows) + "/" + + std::to_string(checked_windows) + " reroll windows matched the reads."; + if (mismatched_windows > 0){ + str += " Last mismatch: " + last_mismatch + "."; + } + return str; +} + +int64_t BBQPointsLedger::net_per_hour() const{ + const int64_t span_ms = std::chrono::duration_cast(last_read - first_read).count(); + if (starting_balance < 0 || span_ms <= 0){ + return 0; + } + return net() * 3600000 / span_ms; +} + + +} +} +} diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.h new file mode 100644 index 0000000000..eb65cd9c98 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.h @@ -0,0 +1,69 @@ +/* BBQ Points Ledger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BBQPointsLedger_H +#define PokemonAutomation_PokemonSV_BBQPointsLedger_H + +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// BP accounting from successive balance reads of the quest panel. +// A rise between two reads is income (quest rewards) and a drop is an +// expense (rerolls), so income and expense are only split correctly when +// they don't fall between the same two reads. The net is always exact. +struct BBQPointsLedger{ + int starting_balance = -1; // -1 until the first successful read. + int balance = -1; + WallClock first_read; + WallClock last_read; + uint64_t earned = 0; + uint64_t spent = 0; + + // Record a balance read at "when". Negative reads (OCR failures) are ignored. + void record(int read, WallClock when); + + // The program paid "bp" for a reroll it believes went through. The next + // successful read must show exactly that drop, since the farmer reads the + // panel again before doing any quest. A mismatch means a reroll that didn't + // happen, an unexpected BP change or a misread balance. + void expect_spend(int bp); + // A reroll whose cost is unknown (an unreadable slot): don't check this window. + void skip_spend_check(); + + uint64_t expected_spent = 0; // Sum of every expect_spend(). + uint64_t checked_windows = 0; + uint64_t mismatched_windows = 0; + std::string last_mismatch; + + // End-of-run reconciliation, one line for the log: the balance change + // against the stats' net, and the reroll spends against the reads. + bool reconciled() const; + std::string reconciliation() const; + + int64_t net() const{ + return (int64_t)earned - (int64_t)spent; + } + + // Net BP per hour between the first and the latest read. 0 until two reads + // are at least a millisecond apart. + int64_t net_per_hour() const; + +private: + int m_pending_spend = 0; + bool m_pending_unchecked = false; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.cpp new file mode 100644 index 0000000000..8821055279 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.cpp @@ -0,0 +1,56 @@ +/* BBQ Failure Snapshots + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/GlobalAutoPaths.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "PokemonSV_BBQSnapshot.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +std::string bbq_snapshot_directory(){ + return DEBUG_PATH() + "BBQ/"; +} + +std::string save_bbq_snapshot( + Logger& logger, const ImageViewRGB32& frame, + const std::string& directory, BBQuests quest, std::string_view reason +){ + const std::string& slug = BBQuests_enum_to_string(quest); + std::ostringstream path; + path << directory << now_to_filestring() << '-' + << (slug.empty() ? "unknown" : slug) << '-' << reason << ".png"; + const std::string filename = path.str(); + + const bool saved = frame.save(filename); + std::ostringstream out; + out << "BBQ event=snapshot saved=" << saved << " path=" << filename; + logger.log(out.str()); + return saved ? filename : std::string(); +} + + +void record_bbq_battle_entry_timeout(ConsoleHandle& console, BBQuests quest){ + BBQLogger(console.logger()).battle_entry_timeout(quest); + save_bbq_snapshot(console.logger(), console.video().snapshot(), bbq_snapshot_directory(), quest, "battle-entry-timeout"); +} + +void record_bbq_attempt_result( + ConsoleHandle& console, BBQAttemptLog& attempt, BBQuests quest, BBQAttemptOutcome outcome +){ + if (outcome == BBQAttemptOutcome::StillOnBoard){ + save_bbq_snapshot(console.logger(), console.video().snapshot(), bbq_snapshot_directory(), quest, "verification-failed"); + } + attempt.result(outcome == BBQAttemptOutcome::Completed); +} + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.h new file mode 100644 index 0000000000..ff2e5af219 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.h @@ -0,0 +1,54 @@ +/* BBQ Failure Snapshots + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BBQSnapshot_H +#define PokemonAutomation_PokemonSV_BBQSnapshot_H + +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSV_BBQLogger.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Where BBQ failure screenshots are saved: DEBUG_PATH()/BBQ/. +std::string bbq_snapshot_directory(); + +// Save a screenshot of a failed quest attempt into `directory` (created if +// missing) as --.png, and log the outcome as a +// "BBQ event=snapshot" line. Unlike dump_image(), this stays on the local +// machine and sends nothing to telemetry. +// Returns the path written, or an empty string if the image was not saved. +std::string save_bbq_snapshot( + Logger& logger, const ImageViewRGB32& frame, + const std::string& directory, BBQuests quest, std::string_view reason +); + + +// Board verification decides whether the attempt completed; capturing evidence does not. +enum class BBQAttemptOutcome{ + Completed, + StillOnBoard, +}; + +// Log a battle-entry timeout and save its current frame locally; no controller input. +void record_bbq_battle_entry_timeout(ConsoleHandle& console, BBQuests quest); + +// Save the verification-failure frame when needed, then log the attempt result. +// The caller retains all retry/counting decisions; this performs no controller input. +void record_bbq_attempt_result( + ConsoleHandle& console, BBQAttemptLog& attempt, BBQuests quest, BBQAttemptOutcome outcome +); + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.cpp new file mode 100644 index 0000000000..b3fd3f6876 --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.cpp @@ -0,0 +1,131 @@ +/* BBQ Snapshot Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Filesystem/Filesystem.h" +#include "Common/Cpp/TestRunners/UnitTestDatabase.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "PokemonSV_BBQSnapshot.h" +#include "PokemonSV_BBQSnapshot_Tests.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace{ + +// Capture evidence through the real logging interface without controller input. +class SnapshotTestLogger : public Logger{ +public: + virtual void log(const std::string& message, Color) override{ + messages.push_back(message); + } + std::vector messages; +}; + +// State of the screenshot destination before the attempted write. +enum class SnapshotDestination{ + MissingDirectory, + BlockedByFile, +}; + +// A quest failure and the destination state to exercise. +struct SnapshotInput{ + std::string name; + SnapshotDestination destination; + BBQuests quest; + std::string reason; +}; + +// The path contract and outcome prefix expected in the one emitted log line. +struct SnapshotExpectation{ + bool saved; + std::string suffix; + std::string log_prefix; +}; + +// Each row keeps its input and expectation together. +struct SnapshotCase{ + SnapshotInput input; + SnapshotExpectation expectation; +}; + +// Check real local image output in an automatically removed temporary directory. +class Test_BBQSnapshot : public UnitTest{ +public: + explicit Test_BBQSnapshot(SnapshotCase test_case) + : UnitTest("PokemonSV::BBQSnapshot - " + test_case.input.name) + , m_case(std::move(test_case)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + QTemporaryDir temp; + if (!temp.isValid()){ + return "Could not create the snapshot test directory."; + } + const std::string base = temp.path().toStdString() + "/BBQ"; + if (m_case.input.destination == SnapshotDestination::BlockedByFile){ + QFile block(QString::fromStdString(base)); + if (!block.open(QIODevice::WriteOnly)){ + return "Could not create the blocking-file fixture."; + } + block.write("not a folder"); + } + const std::string directory = base + "/"; + ImageRGB32 frame(4, 4); + frame.fill(0xff00ff00); + SnapshotTestLogger logger; + const std::string path = save_bbq_snapshot(logger, frame, directory, m_case.input.quest, m_case.input.reason); + if (path.empty() == m_case.expectation.saved){ + return "Expected saved=" + std::to_string(m_case.expectation.saved) + "; read path [" + path + "]."; + } + if (logger.messages.size() != 1){ + return "Expected exactly one snapshot log; read " + std::to_string(logger.messages.size()) + "."; + } + const std::string prefix = m_case.expectation.log_prefix + directory; + const std::string& message = logger.messages[0]; + if (!message.starts_with(prefix) || !message.ends_with(m_case.expectation.suffix)){ + return "Expected snapshot log prefix [" + prefix + "] and suffix [" + m_case.expectation.suffix + "]; read [" + message + "]."; + } + if (m_case.expectation.saved && (!message.ends_with(path) || !Filesystem::is_regular_file(Filesystem::Path(path)))){ + return "Expected the logged file to exist at the returned path [" + path + "]."; + } + return true; + } + +private: + const SnapshotCase m_case; +}; + +// Both original screenshot cases: a new folder and a destination blocked by a file. +const SnapshotCase SNAPSHOT_CASES[] = { + { + .input = {.name = "saves into a new folder", .destination = SnapshotDestination::MissingDirectory, + .quest = BBQuests::make_tm, .reason = "verification-failed"}, + .expectation = {.saved = true, .suffix = "-make-tm-verification-failed.png", + .log_prefix = "BBQ event=snapshot saved=1 path="}, + }, + { + .input = {.name = "reports a failed save", .destination = SnapshotDestination::BlockedByFile, + .quest = BBQuests::make_tm, .reason = "verification-failed"}, + .expectation = {.saved = false, .suffix = "-make-tm-verification-failed.png", + .log_prefix = "BBQ event=snapshot saved=0 path="}, + }, +}; + +} // namespace + +void add_tests_BBQSnapshot(UnitTestDatabase& database){ + for (const SnapshotCase& test_case : SNAPSHOT_CASES){ + database.add(test_case); + } +} + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.h new file mode 100644 index 0000000000..475244dd6c --- /dev/null +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.h @@ -0,0 +1,22 @@ +/* BBQ Snapshot Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BBQSnapshot_Tests_H +#define PokemonAutomation_PokemonSV_BBQSnapshot_Tests_H + +#include "Common/Cpp/TestRunners/UnitTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Registers local screenshot-write and failure-reporting cases without a console. +void add_tests_BBQSnapshot(UnitTestDatabase& database); + +} // namespace PokemonSV +} // namespace NintendoSwitch +} // namespace PokemonAutomation +#endif diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp index fcfa3182fa..c7226c0cbd 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp @@ -4,7 +4,9 @@ * */ +#include #include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" #include "CommonFramework/Notifications/ProgramNotifications.h" #include "CommonFramework/ProgramStats/StatsTracking.h" #include "CommonTools/StartupChecks/StartProgramChecks.h" @@ -20,6 +22,7 @@ #include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" //#include "VideoGames/PokemonSV/PokemonSV_Settings.h" #include "VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h" +#include "VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.h" #include "PokemonSV_BBQSoloFarmer.h" namespace PokemonAutomation{ @@ -48,14 +51,45 @@ struct BBQSoloFarmer_Descriptor::Stats : public StatsTracker{ : questsCompleted(m_stats["Quests Completed"]) , saves(m_stats["Saves"]) , errors(m_stats["Errors"]) + , bp_earned(m_stats["BP Earned"]) + , bp_spent(m_stats["BP Spent"]) { m_display_order.emplace_back("Quests Completed"); m_display_order.emplace_back("Saves"); m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("BP Earned"); + m_display_order.emplace_back("BP Spent"); } + + void update_BP(const BBQPointsLedger& ledger){ + bp_earned.store(ledger.earned, std::memory_order_relaxed); + bp_spent.store(ledger.spent, std::memory_order_relaxed); + bp_per_hour.store(ledger.net_per_hour(), std::memory_order_relaxed); + has_bp_per_hour.store(true, std::memory_order_relaxed); + } + + // Net and BP/hour are derived, so they are shown but not saved. Past runs + // have no BP/hour since their time span isn't saved. + virtual std::string to_str(PrintMode mode) const override{ + std::string str = StatsTracker::to_str(mode); + if (mode == SAVE_TO_STATS_FILE){ + return str; + } + const int64_t net = (int64_t)bp_earned.load(std::memory_order_relaxed) - (int64_t)bp_spent.load(std::memory_order_relaxed); + str += " - Net BP: " + tostr_u_commas(net); + if (has_bp_per_hour.load(std::memory_order_relaxed)){ + str += " - BP/hour: " + tostr_u_commas(bp_per_hour.load(std::memory_order_relaxed)); + } + return str; + } + std::atomic& questsCompleted; std::atomic& saves; std::atomic& errors; + std::atomic& bp_earned; + std::atomic& bp_spent; + std::atomic bp_per_hour{0}; + std::atomic has_bp_per_hour{false}; }; std::unique_ptr BBQSoloFarmer_Descriptor::make_stats() const{ return std::unique_ptr(new Stats()); @@ -74,100 +108,410 @@ BBQSoloFarmer::BBQSoloFarmer() PA_ADD_OPTION(NOTIFICATIONS); } -void BBQSoloFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StartProgramChecks::check_performance_class_wired_or_wireless(context); - assert_16_9_720p_min(env.logger(), env.console); +namespace{ - BBQSoloFarmer_Descriptor::Stats& stats = env.current_stats(); +// Forget the failed quests that are gone from the panel, so a quest that +// comes back later gets its attempts again. The first 3 slots are always +// read, as UnableToDetect when OCR fails, but a 4th slot is only there when +// OCR reads it. So only a read of 4 known quests proves a quest is gone; a +// missed read must not give a failing quest new attempts. +void forget_quests_gone_from_panel(std::set& failed_quests, const std::vector& panel){ + if (panel.size() < 4 || std::find(panel.begin(), panel.end(), BBQuests::UnableToDetect) != panel.end()){ + return; + } + std::erase_if(failed_quests, [&](BBQuests quest){ + return std::find(panel.begin(), panel.end(), quest) == panel.end(); + }); +} - //Make sure console type is set - if (env.console.state().console_type() == ConsoleType::Unknown){ - throw UserSetupError(env.console, "Console Type (Switch 1 or 2) must be specified."); +// When nothing on the panel is doable, the farmer rerolls it and reads it +// again. If no blue quest can ever be doable, that loop never ends, so the +// settings are checked before starting. +// A quest is done if any exclusion row says run, matching process_quest_list(). +bool exclusions_leave_a_blue_quest(const BBQOption& options){ + const std::vector> exclusions = options.QUEST_EXCLUSIONS.copy_snapshot(); + for (BBQuests quest : blue_quests){ + if (not_possible_quests.contains(quest)){ + continue; + } + bool in_table = false; + bool run = false; + for (const std::unique_ptr& row : exclusions){ + if (row->quest == quest){ + in_table = true; + run = run || row->action == BBQAction::run; + } + } + if (!in_table || run){ + return true; + } } + return false; +} - // Connect the controller. - require_player(env.console, context, BUTTON_LCLICK); - - //Fly to plaza - open_map_from_overworld(env.program_info(), env.console, context); - fly_to_overworld_from_map(env.program_info(), env.console, context); +// Valid settings can still produce a panel with nothing doable, which the +// next reroll fixes. If only 3 of the 31 blue quests are doable, a panel has +// nothing doable 73% of the time, and 30 such panels in a row happen with +// probability 0.008%. More than that means rerolling does not help: the game +// language is wrong so no quest is read, or there is no BP left to reroll. +const size_t MAX_READS_WITHOUT_DOABLE_QUEST = 30; + +} + +// Quests done at Central Plaza with no flight out: they start at its fly +// point and fly back to it, so the player is where the round actions and the +// next quest expect. Every other route flies to another plaza or area. +bool bbq_quest_is_no_trip(BBQuests quest){ + return quest == BBQuests::make_tm || quest == BBQuests::travel_500; +} + +namespace{ + +// Whether a round that took the completed count from previous_completed +// to completed crossed a nonzero multiple of the save interval. +bool bbq_save_due(uint64_t previous_completed, uint64_t completed, uint64_t interval){ + return interval != 0 && completed > previous_completed + && completed / interval > previous_completed / interval; +} + +} + +void run_bbq_rounds(Logger& logger, const BBQOption& options, BBQGameActions& game){ + if (!exclusions_leave_a_blue_quest(options)){ + throw UserSetupError(logger, "The quest exclusions table skips or rerolls every blue quest the program can do."); + } std::vector quest_list; //all quests std::vector quests_to_do; //do-able quests uint8_t eggs_hatched = 0; //Track eggs uint64_t num_completed_quests = 0; - //Test a specific quest - /* - BBQuests test_quest = BBQuests::catch_water; - bool questTest = process_and_do_quest(env, env.console, context, BBQ_OPTIONS, test_quest, eggs_hatched); - if (questTest){ - env.log("Finished quest."); - } - */ + // Quests that failed every attempt do_quest() made. A failed quest stays + // on the panel, so without this it gets NUM_RETRIES more attempts every + // round, forever, e.g. a sneak-up whose target does not spawn. + std::set failed_quests; + std::optional> observed_panel; + std::optional> dispatch_panel; + auto read_panel = [&](){ + std::vector panel = game.read_quests(); + forget_quests_gone_from_panel(failed_quests, panel); + return panel; + }; - while (num_completed_quests < BBQ_OPTIONS.NUM_QUESTS){ - if (BBQ_OPTIONS.OUT_OF_EGGS == BBQOption::OOEggs::Stop && eggs_hatched >= BBQ_OPTIONS.NUM_EGGS){ - env.log("Stop when out of eggs selected. Stopping program."); + while (num_completed_quests < options.NUM_QUESTS){ + if (options.OUT_OF_EGGS == BBQOption::OOEggs::Stop && eggs_hatched >= options.NUM_EGGS){ + logger.log("Stop when out of eggs selected. Stopping program."); break; } //Get and reroll quests until we can at least one + size_t reads_without_doable_quest = 0; while (quests_to_do.size() < 1){ - quest_list = read_quests(env.program_info(), env.console, context, BBQ_OPTIONS); - quests_to_do = process_quest_list(env.program_info(), env.console, context, BBQ_OPTIONS, quest_list, eggs_hatched); + if (reads_without_doable_quest++ == MAX_READS_WITHOUT_DOABLE_QUEST){ + throw UserSetupError( + logger, + "No doable quest after " + std::to_string(MAX_READS_WITHOUT_DOABLE_QUEST) + + " quest panel reads. Check the game language and that you have BP to reroll." + ); + } + if (observed_panel){ + logger.log("Reusing verified quest panel for scheduling."); + quest_list = std::move(*observed_panel); + observed_panel.reset(); + forget_quests_gone_from_panel(failed_quests, quest_list); + }else{ + logger.log("Reading quest panel for scheduling."); + quest_list = read_panel(); + } + BBQuestBatch batch = game.process_quest_list(quest_list, eggs_hatched); + quests_to_do = std::move(batch.to_do); + observed_panel = std::move(batch.observed_panel); + //Work is only returned when nothing changed in game, so the panel + //it was chosen from is still current for the first dispatch. + if (!quests_to_do.empty() && !observed_panel){ + dispatch_panel = quest_list; + } + + // Rerolling costs BP and the failed quests may be doable another + // time, so stop instead of spending BP to replace them. + const bool found_doable = !quests_to_do.empty(); + std::erase_if(quests_to_do, [&](BBQuests quest){ + return failed_quests.contains(quest); + }); + if (found_doable && quests_to_do.empty()){ + logger.log("Every doable quest on the panel failed all its attempts. Stopping program.", COLOR_RED); + return; + } //Clear out the regular quest list. quest_list.clear(); } + //Never carry an observation across quest actions or a save and reset. + observed_panel.reset(); + const uint64_t completed_before_round = num_completed_quests; + bool replan_after_reroll = false; + std::optional> rerolled_panel; + //The panel read that checked a completed no-trip quest. Nothing runs + //between it and the next dispatch or plan, so a no-trip quest next or + //the next plan starts from it instead of reading again. + std::optional> no_trip_panel; for (auto current_quest : quests_to_do){ //Check if quest was already completed (ex. 500 meters completed while navigating to take a photo) - quest_list = read_quests(env.program_info(), env.console, context, BBQ_OPTIONS); + if (dispatch_panel){ + logger.log("Reusing verified quest panel for first dispatch."); + quest_list = std::move(*dispatch_panel); + dispatch_panel.reset(); + }else if (no_trip_panel && bbq_quest_is_no_trip(current_quest)){ + logger.log("Reusing quest panel read after a no-trip quest for dispatch."); + quest_list = std::move(*no_trip_panel); + no_trip_panel.reset(); + forget_quests_gone_from_panel(failed_quests, quest_list); + }else{ + no_trip_panel.reset(); + logger.log("Reading quest panel before dispatch."); + quest_list = read_panel(); + } if (std::find(quest_list.begin(), quest_list.end(), current_quest) != quest_list.end()){ - env.log("Current quest exists on list. Doing quest."); - bool questSuccess = process_and_do_quest(env, env.console, context, BBQ_OPTIONS, current_quest, eggs_hatched); + logger.log("Current quest exists on list. Doing quest."); + std::vector panel_after; + bool questSuccess = game.do_quest(current_quest, eggs_hatched, panel_after); if (questSuccess){ - env.log("Quest completed successfully."); - stats.questsCompleted++; - env.update_stats(); + logger.log("Quest completed successfully."); + game.quest_completed(); num_completed_quests++; + if (bbq_quest_is_no_trip(current_quest)){ + no_trip_panel = std::move(panel_after); + } }else{ - env.log("Quest did not complete successfully."); + logger.log("Quest did not complete successfully."); + switch (options.OUT_OF_RETRIES){ + case BBQOption::OutOfRetries::Skip: + failed_quests.insert(current_quest); + break; + case BBQOption::OutOfRetries::Reroll: + logger.log("Reroll selected. Rerolling the failed quest."); + rerolled_panel = game.reroll_quest(current_quest); + logger.log("Reroll finished. Discarding the remaining batch before scheduling."); + replan_after_reroll = true; + break; + case BBQOption::OutOfRetries::Stop: + logger.log("Stop selected. Stopping program.", COLOR_RED); + return; + } } }else{ //Note: This doesn't account for case such as "sneak up" being added and then completed alongside the next quest - env.log("Current quest does not exist on list. Quest completed at some point."); - stats.questsCompleted++; - env.update_stats(); + logger.log("Current quest does not exist on list. Quest completed at some point."); + game.quest_completed(); num_completed_quests++; } quest_list.clear(); + if (replan_after_reroll){ + //A replacement belongs in the next plan, before more old queued + //work. Finish normal round actions so save milestones are kept. + break; + } } //Clear out the todo list quests_to_do.clear(); + uint64_t temp_save_num_option = options.SAVE_NUM_QUESTS; + // A round can cross a milestone without ending at an exact multiple. + const bool save = bbq_save_due(completed_before_round, num_completed_quests, temp_save_num_option); + + //A no-trip quest ended the round at Central Plaza, and fixing the date + //does not change the quests, so plan the next quests from its read + //at once. Round actions still run before a save or the last stop. + if (no_trip_panel && !save && num_completed_quests < options.NUM_QUESTS){ + logger.log("Chaining after a no-trip quest. Skipping round actions."); + observed_panel = std::move(no_trip_panel); + continue; + } + game.end_round(save); + + //The reroll was the last game action of the round. Fixing the date + //does not change the quests, so its verified read can seed the next + //plan. A save resets the game, so the panel is read again after one. + if (rerolled_panel && !save){ + observed_panel = std::move(rerolled_panel); + } + } +} + + +namespace{ + +class BBQSoloFarmerGameActions : public BBQGameActions{ +public: + BBQSoloFarmerGameActions( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + BBQOption& options, BBQSoloFarmer_Descriptor::Stats& stats, + EventNotificationOption& status_update + ) + : m_env(env), m_context(context) + , m_options(options), m_stats(stats) + , m_status_update(status_update) + {} + + virtual std::vector read_quests() override{ + int BP = -1; + std::vector quests = PokemonSV::read_quests(m_env.program_info(), m_env.console, m_context, m_options, &BP); + record_BP(BP); + return quests; + } + virtual BBQuestBatch process_quest_list( + const std::vector& quests, uint8_t eggs_hatched + ) override{ + BBQuestBatch batch = PokemonSV::process_quest_list( + m_env.program_info(), m_env.console, m_context, m_options, quests, eggs_hatched, &m_bp_ledger + ); + update_BP_stats(); + return batch; + } + virtual bool do_quest(BBQuests quest, uint8_t& eggs_hatched, std::vector& panel_after) override{ + return process_and_do_quest(m_env, m_env.console, m_context, m_options, quest, eggs_hatched, &panel_after); + } + virtual std::optional> reroll_quest(BBQuests quest) override{ + std::vector quests = read_quests(); + auto iter = std::find(quests.begin(), quests.end(), quest); + if (iter == quests.end()){ + m_env.log("Failed quest is no longer on the panel. Not rerolling."); + return std::nullopt; + } + std::optional> panel_after = reroll_quest_slot( + m_env.program_info(), m_env.console, m_context, m_options, quests, iter - quests.begin(), &m_bp_ledger + ); + update_BP_stats(); + return panel_after; + } + virtual void quest_completed() override{ + m_stats.questsCompleted++; + m_env.update_stats(); + } + virtual void end_round(bool save) override{ //Fix the time to prevent running out of years - pbf_wait(context, 2000ms); - context.wait_for_all_requests(); - go_home(env.console, context); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 160ms, 840ms); - pbf_press_button(context, BUTTON_A, 160ms, 840ms); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); + pbf_wait(m_context, 2000ms); + m_context.wait_for_all_requests(); + go_home(m_env.console, m_context); + home_to_date_time(m_env.console, m_context, false); + pbf_press_button(m_context, BUTTON_A, 160ms, 840ms); + pbf_press_button(m_context, BUTTON_A, 160ms, 840ms); + pbf_press_button(m_context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(m_env.console, m_context); - uint64_t temp_save_num_option = BBQ_OPTIONS.SAVE_NUM_QUESTS; - if (temp_save_num_option != 0 && num_completed_quests % temp_save_num_option == 0){ - env.log("Saving and resetting."); - save_game_from_overworld(env.program_info(), env.console, context); - reset_game(env.program_info(), env.console, context); - stats.saves++; + if (save){ + m_env.log("Saving and resetting."); + save_game_from_overworld(m_env.program_info(), m_env.console, m_context); + reset_game(m_env.program_info(), m_env.console, m_context); + m_stats.saves++; } - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + m_env.update_stats(); + send_program_status_notification(m_env, m_status_update); + } + + //BP is read from the quest panel screenshots the program already takes. + void record_BP(int BP){ + m_bp_ledger.record(BP, current_time()); + update_BP_stats(); + } + const BBQPointsLedger& bp_ledger() const{ return m_bp_ledger; } + +private: + void update_BP_stats(){ + m_env.log( + "BP: " + std::to_string(m_bp_ledger.balance) + " (start " + std::to_string(m_bp_ledger.starting_balance) + + ", earned " + std::to_string(m_bp_ledger.earned) + ", spent " + std::to_string(m_bp_ledger.spent) + ")" + ); + m_stats.update_BP(m_bp_ledger); + m_env.update_stats(); + } + + SingleSwitchProgramEnvironment& m_env; + ProControllerContext& m_context; + BBQOption& m_options; + BBQSoloFarmer_Descriptor::Stats& m_stats; + EventNotificationOption& m_status_update; + BBQPointsLedger m_bp_ledger; +}; + +//Checks before the first round, so that a setup problem stops the program at once instead of +//in the middle of a quest. +void check_before_start(SingleSwitchProgramEnvironment& env, ProControllerContext& context, const BBQOption& options){ + //The Switch dims the screen after a few idle minutes, which hides the overworld. Any button + //wakes it, and B is harmless on the overworld. + pbf_press_button(context, BUTTON_B, 160ms, 1000ms); + context.wait_for_all_requests(); + + if (options.NUM_EGGS > 0 && !box_has_egg(env.program_info(), env.console, context)){ + throw UserSetupError( + env.console, + "\"Hatch Quest - Number of Eggs\" is " + std::to_string((int)options.NUM_EGGS) + + ", but the current box (the one the box system opens on) has no egg. " + "Put eggs in that box, or set it to 0 and choose Reroll or Keep Going in " + "\"Hatch Quest - Zero Eggs\"." + ); + } +} + +void log_BP_check(SingleSwitchProgramEnvironment& env, const BBQPointsLedger& ledger, const std::string& note){ + env.log(ledger.reconciliation() + note, ledger.reconciled() ? COLOR_BLACK : COLOR_RED); +} + +//Run the quest rounds, then check the BP stats against the rerolls. The check is logged even +//when the run stops early. +void run_rounds_and_check_BP( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const BBQOption& options, BBQSoloFarmerGameActions& game +){ + try{ + run_bbq_rounds(env.logger(), options, game); + }catch (...){ + //The balance isn't read again, since the game may be on any screen. + log_BP_check(env, game.bp_ledger(), " Stopped early, so this is as of the last panel read."); + throw; + } + + //No quest panel is read after the last batch, so read the balance once more. + game.record_BP(read_BP(env.program_info(), env.console, context)); + log_BP_check(env, game.bp_ledger(), ""); +} + +} + +void BBQSoloFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StartProgramChecks::check_performance_class_wired_or_wireless(context); + assert_16_9_720p_min(env.logger(), env.console); + + BBQSoloFarmer_Descriptor::Stats& stats = env.current_stats(); + + //Make sure console type is set + if (env.console.state().console_type() == ConsoleType::Unknown){ + throw UserSetupError(env.console, "Console Type (Switch 1 or 2) must be specified."); } + + // Connect the controller. + require_player(env.console, context, BUTTON_LCLICK); + + check_before_start(env, context, BBQ_OPTIONS); + + //Fly to plaza + open_map_from_overworld(env.program_info(), env.console, context); + fly_to_overworld_from_map(env.program_info(), env.console, context); + + //Test a specific quest + /* + uint8_t eggs_hatched = 0; + BBQuests test_quest = BBQuests::catch_water; + bool questTest = process_and_do_quest(env, env.console, context, BBQ_OPTIONS, test_quest, eggs_hatched); + if (questTest){ + env.log("Finished quest."); + } + */ + + BBQSoloFarmerGameActions game(env, context, BBQ_OPTIONS, stats, NOTIFICATION_STATUS_UPDATE); + run_rounds_and_check_BP(env, context, BBQ_OPTIONS, game); env.update_stats(); if (BBQ_OPTIONS.FIX_TIME_WHEN_DONE){ diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h index 9917606334..2ffd76e766 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h @@ -7,15 +7,76 @@ #ifndef PokemonAutomation_PokemonSV_BBQSoloFarmer_H #define PokemonAutomation_PokemonSV_BBQSoloFarmer_H +#include +#include +#include +#include "Common/Cpp/Logging/AbstractLogger.h" #include "CommonFramework/Notifications/EventNotificationsTable.h" #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" #include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h" +#include "VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonSV{ + +// The game actions that run_bbq_rounds() depends on. They are injected so +// that the round loop (which quests to attempt, which ones count, when to +// stop, when to save) runs in tests without a Switch: BBQSoloFarmer performs +// them on the console, and tests replace them with scripted results. +class BBQGameActions{ +public: + virtual ~BBQGameActions() = default; + + // Open the quest panel and read the quests on it. + virtual std::vector read_quests() = 0; + + // Decide which of the quests just read are worth attempting this round. + // May reroll quests in game, so the returned list can be empty even when + // `quests` is not; a complete post-reroll observation can seed selection. + // Only returns quests to attempt when it changed nothing in game, so + // `quests` still shows the panel. + virtual BBQuestBatch process_quest_list( + const std::vector& quests, uint8_t eggs_hatched + ) = 0; + + // Attempt one quest that is on the panel, after process_quest_list() + // chose it. Returns true if it is no longer on the panel afterwards. + // Increments `eggs_hatched` when the quest hatches eggs. Sets + // `panel_after` to the quest panel read that checked the last attempt. + virtual bool do_quest(BBQuests quest, uint8_t& eggs_hatched, std::vector& panel_after) = 0; + + // Reroll a quest that failed all its attempts, if it is still on the + // panel. Spends BP. Returns the panel read to verify the reroll when + // reroll_quest() found it reusable, so scheduling can skip a read. + virtual std::optional> reroll_quest(BBQuests quest) = 0; + + // Progress reporting only: a quest was counted as completed. Lets stats + // update after every quest instead of once per round. + virtual void quest_completed() = 0; + + // A round has ended. The loop decides whether a save is due, because + // that depends on how many quests it has counted; how to fix the date, + // save and reset, and report the round is up to the game side. + virtual void end_round(bool save) = 0; +}; + +// Whether a quest is done at Central Plaza with no flight out. +bool bbq_quest_is_no_trip(BBQuests quest); + +// Run rounds of quests until NUM_QUESTS have been completed, or until +// eggs run out when OUT_OF_EGGS is Stop, or until every doable quest on the +// panel is one that already failed all its attempts, or until a quest fails +// all its attempts when OUT_OF_RETRIES is Stop. No-trip quests (see +// bbq_quest_is_no_trip()) are chained: the panel read that checked one is +// reused for a no-trip quest next or for the next plan, without the round +// actions between. +// Throws UserSetupError if the exclusions leave no blue quest to do, or if +// the panel shows nothing doable for many reads in a row. +void run_bbq_rounds(Logger& logger, const BBQOption& options, BBQGameActions& game); + + class BBQSoloFarmer_Descriptor : public SingleSwitchProgramDescriptor{ public: BBQSoloFarmer_Descriptor(); diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp index aa8ef76ecb..f821fee61c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp @@ -4,12 +4,19 @@ * */ +#include +#include +#include "Common/Cpp/Exceptions.h" #include "Common/Cpp/TestRunners/UnitTestDatabase.h" #include "CommonFramework/ImageTypes/ImageRGB32.h" #include "Tests/ImageUnitTest.h" #include "VideoGames/PokemonSV/Inference/PokemonSV_BlueberryPointsReader.h" #include "VideoGames/PokemonSV/Options/PokemonSV_BBQuests.h" +#include "PokemonSV_BBQLogger_Tests.h" +#include "PokemonSV_BBQSnapshot_Tests.h" #include "PokemonSV_BlueberryQuests.h" +#include "PokemonSV_BBQPointsLedger.h" +#include "PokemonSV_BBQSoloFarmer.h" #include "PokemonSV_BBQTests.h" namespace PokemonAutomation{ @@ -122,6 +129,1388 @@ static void add_tests_TeraEncounterAction(UnitTestDatabase& database){ } +namespace{ + +class NullLogger : public Logger{ +public: + virtual void log(const std::string&, Color) override{} +}; +class RecordingLogger : public Logger{ +public: + std::vector lines; + virtual void log(const std::string& line, Color) override{ + lines.push_back(line); + } +}; + +// A singleplayer quest panel that behaves like the game's: 3 blue quests, +// and a completed quest is replaced by a new one. process_quest_list() +// follows the rules of the real one that the round loop depends on: quests +// in not_possible_quests are skipped, quests in table_rerolls are rerolled +// in their slot as an exclusions table reroll row does, and if nothing is +// doable all quests are rerolled. After any reroll it returns nothing to do. +// Red quests are not modeled. Records the game actions taken. +// With out_of_bp, rerolls do nothing, as in the game when BP runs out. +// A run that reads the panel more than max_reads times is stuck: the read +// throws, and the test records "stuck". +class SimulatedBBQGameActions : public BBQGameActions{ +public: + std::vector panel; + // Each attempt returns the next outcome; once exhausted, attempts succeed. + std::vector outcomes = {}; + // Completing the first quest also completes the second, e.g. walking + // 500 meters while navigating to a photo target. + std::vector> also_completes = {}; + // Attempts at these always fail, e.g. a target that never spawns. + std::set never_completes = {}; + bool out_of_bp = false; + size_t max_reads = 1000; + // New quests are drawn from this list in turn, skipping any that are + // already on the panel. + std::vector new_quests = { + BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar, + BBQuests::photo_savanna, BBQuests::catch_any, BBQuests::catch_normal, + BBQuests::catch_fire, BBQuests::catch_water, BBQuests::catch_grass, + }; + // Quests that process_quest_list() rerolls in their slot. + std::set table_rerolls; + // Rerolls return the panel they read to verify the reroll, as + // reroll_quest() does when that read is reusable. + bool reuse_rerolled_panel = false; + + std::vector events; + std::vector attempted_quests; + + virtual std::vector read_quests() override{ + events.push_back("read"); + if (++m_reads > max_reads){ + throw std::runtime_error("Too many quest panel reads."); + } + return panel; + } + virtual BBQuestBatch process_quest_list( + const std::vector& quests, uint8_t + ) override{ + events.push_back("process"); + bool rerolled = false; + for (BBQuests& slot : panel){ + if (table_rerolls.contains(slot)){ + slot = next_new_quest(); + rerolled = true; + } + } + std::vector doable; + for (BBQuests quest : quests){ + if (!not_possible_quests.contains(quest)){ + doable.push_back(quest); + } + } + if (!rerolled && doable.empty() && !out_of_bp){ + for (BBQuests& slot : panel){ + slot = next_new_quest(); + } + rerolled = true; + } + if (rerolled){ + return {{}, reuse_rerolled_panel ? std::optional(panel) : std::nullopt}; + } + return {std::move(doable), std::nullopt}; + } + virtual bool do_quest(BBQuests quest, uint8_t&, std::vector& panel_after) override{ + events.push_back("do"); + attempted_quests.push_back(quest); + const bool success = !never_completes.contains(quest) + && (m_next_outcome < outcomes.size() ? outcomes[m_next_outcome++] : true); + if (success){ + complete(quest); + for (const auto& [done, extra] : also_completes){ + if (done == quest){ + complete(extra); + } + } + } + panel_after = panel; + return success; + } + virtual std::optional> reroll_quest(BBQuests quest) override{ + events.push_back("reroll"); + auto iter = std::find(panel.begin(), panel.end(), quest); + if (iter == panel.end()){ + return std::nullopt; + } + *iter = next_new_quest(); + return reuse_rerolled_panel ? std::optional(panel) : std::nullopt; + } + virtual void quest_completed() override{ + events.push_back("completed"); + } + virtual void end_round(bool save) override{ + events.push_back(save ? "end(save)" : "end"); + } + +private: + void complete(BBQuests quest){ + auto iter = std::find(panel.begin(), panel.end(), quest); + if (iter != panel.end()){ + *iter = next_new_quest(); + } + } + + BBQuests next_new_quest(){ + while (true){ + BBQuests quest = new_quests[m_next_new_quest++ % new_quests.size()]; + if (std::find(panel.begin(), panel.end(), quest) == panel.end()){ + return quest; + } + } + } + + size_t m_reads = 0; + size_t m_next_outcome = 0; + size_t m_next_new_quest = 0; +}; + +std::string join_events(const std::vector& events){ + std::string ret; + for (const std::string& event : events){ + if (!ret.empty()) ret += ' '; + ret += event; + } + return ret; +} + +// One simulated farmer run: option values, the panel it starts with and how +// quests turn out, and the game actions it must take. +struct BBQRoundsScenario{ + std::string name; + uint64_t num_quests; + uint64_t save_num_quests = 0; + bool stop_when_out_of_eggs = false; + std::vector panel = {BBQuests::make_tm, BBQuests::auto_10, BBQuests::sneak_up}; + std::vector outcomes = {}; + std::vector> also_completes = {}; + std::set never_completes = {}; + bool out_of_bp = false; + size_t max_reads = 1000; + std::vector new_quests = {}; + std::vector> exclusions = {}; + BBQOption::OutOfRetries out_of_retries = BBQOption::OutOfRetries::Skip; + std::set table_rerolls = {}; + bool reuse_rerolled_panel = false; + uint64_t expected_completed = 0; + std::vector expected_attempted = {}; + std::optional expected_reads = {}; + std::string expected; +}; + +class Test_BBQFarmerRounds : public UnitTest{ +public: + Test_BBQFarmerRounds(BBQRoundsScenario scenario) + : UnitTest("PokemonSV::BBQFarmerRounds - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + BBQOption options; + options.NUM_QUESTS.set(m_scenario.num_quests); + options.SAVE_NUM_QUESTS.set(m_scenario.save_num_quests); + if (m_scenario.stop_when_out_of_eggs){ + options.NUM_EGGS.set(0); + options.OUT_OF_EGGS.set(BBQOption::OOEggs::Stop); + } + for (const auto& [quest, action] : m_scenario.exclusions){ + auto row = std::make_unique(options.QUEST_EXCLUSIONS); + row->quest.set(quest); + row->action.set(action); + options.QUEST_EXCLUSIONS.append_row(std::move(row)); + } + options.OUT_OF_RETRIES.set(m_scenario.out_of_retries); + + SimulatedBBQGameActions game; + game.panel = m_scenario.panel; + game.outcomes = m_scenario.outcomes; + game.also_completes = m_scenario.also_completes; + game.never_completes = m_scenario.never_completes; + game.out_of_bp = m_scenario.out_of_bp; + game.max_reads = m_scenario.max_reads; + if (!m_scenario.new_quests.empty()){ + game.new_quests = m_scenario.new_quests; + } + game.table_rerolls = m_scenario.table_rerolls; + game.reuse_rerolled_panel = m_scenario.reuse_rerolled_panel; + + NullLogger logger; + try{ + run_bbq_rounds(logger, options, game); + }catch (UserSetupError&){ + game.events.push_back("error"); + }catch (std::runtime_error&){ + game.events.push_back("stuck"); + } + const uint64_t completed = (uint64_t)std::count(game.events.begin(), game.events.end(), "completed"); + if (completed != m_scenario.expected_completed){ + return "Expected " + std::to_string(m_scenario.expected_completed) + + " completed quests, counted " + std::to_string(completed); + } + if (!m_scenario.expected_attempted.empty() && game.attempted_quests != m_scenario.expected_attempted){ + std::vector expected_quests; + std::vector actual_quests; + for (BBQuests quest : m_scenario.expected_attempted){ + expected_quests.push_back(std::to_string((int)quest)); + } + for (BBQuests quest : game.attempted_quests){ + actual_quests.push_back(std::to_string((int)quest)); + } + return "Expected quest order: " + join_events(expected_quests) + + "\nActual quest order: " + join_events(actual_quests); + } + const size_t reads = (size_t)std::count(game.events.begin(), game.events.end(), "read"); + if (m_scenario.expected_reads && reads != *m_scenario.expected_reads){ + return "Expected " + std::to_string(*m_scenario.expected_reads) + + " quest panel reads, counted " + std::to_string(reads); + } + const std::string actual = join_events(game.events); + if (actual != m_scenario.expected){ + return "Expected: " + m_scenario.expected + "\nActual: " + actual; + } + return true; + } + +private: + const BBQRoundsScenario m_scenario; +}; + +// Every blue quest the program can do, each with the given action. +std::vector> every_doable_blue_quest(BBQAction action){ + std::vector> ret; + for (BBQuests quest : blue_quests){ + if (!not_possible_quests.contains(quest)){ + ret.emplace_back(quest, action); + } + } + return ret; +} + +static void add_tests_BBQFarmerRounds(UnitTestDatabase& database){ + const std::string round_of_3 = "read process do completed read do completed read do completed"; + std::string read_30_times; + for (int c = 0; c < 30; c++){ + read_30_times += "read process "; + } + std::vector> all_skipped_but_make_tm = every_doable_blue_quest(BBQAction::skip); + all_skipped_but_make_tm.emplace_back(BBQuests::make_tm, BBQAction::run); + const BBQRoundsScenario scenarios[] = { + { + .name = "failed reroll replans before queued photo and TM", + .num_quests = 1, + .panel = {BBQuests::catch_grass, BBQuests::photo_savanna, BBQuests::make_tm}, + .outcomes = {false}, + .new_quests = {BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .expected_completed = 3, + .expected_attempted = {BBQuests::catch_grass, BBQuests::travel_500, BBQuests::photo_savanna, BBQuests::make_tm}, + .expected = "read process do reroll end " + round_of_3 + " end", + }, + { + .name = "failed reroll on full board reuses its verified read after round actions", + .num_quests = 1, + .panel = {BBQuests::catch_grass, BBQuests::photo_savanna, BBQuests::make_tm, BBQuests::wash_pokemon}, + .outcomes = {false}, + .new_quests = {BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .reuse_rerolled_panel = true, + .expected_completed = 4, + .expected_attempted = {BBQuests::catch_grass, BBQuests::travel_500, BBQuests::photo_savanna, BBQuests::make_tm, BBQuests::wash_pokemon}, + .expected = "read process do reroll end process do completed read do completed read do completed read do completed end", + }, + { + .name = "replanning after failure preserves a crossed save milestone", + .num_quests = 2, + .save_num_quests = 1, + .panel = {BBQuests::make_tm, BBQuests::catch_grass, BBQuests::photo_savanna}, + .outcomes = {true, false}, + .new_quests = {BBQuests::photo_canyon, BBQuests::travel_500, BBQuests::photo_coastal, BBQuests::photo_polar}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .expected_completed = 4, + .expected_attempted = {BBQuests::make_tm, BBQuests::catch_grass, BBQuests::photo_canyon, BBQuests::travel_500, BBQuests::photo_savanna}, + .expected = "read process do completed read do reroll end(save) " + round_of_3 + " end(save)", + }, + { + .name = "reuses reroll observation for selection and first dispatch only", + .num_quests = 1, + .panel = {BBQuests::pickup_10, BBQuests::catch_flying, BBQuests::UnableToDetect, BBQuests::photo_flying}, + .reuse_rerolled_panel = true, + .expected_completed = 4, + .expected = "read process process do completed read do completed read do completed read do completed end", + }, + { + // reroll_quest() decides whether a 3-slot read is reusable. + .name = "reusable three-slot reroll observation is not read again", + .num_quests = 1, + .panel = {BBQuests::pickup_10, BBQuests::catch_flying, BBQuests::UnableToDetect}, + .reuse_rerolled_panel = true, + .expected_completed = 3, + .expected = "read process process do completed read do completed read do completed end", + }, + { + // Seen in a live run: catch-fighting fails and is rerolled into + // pickup-10, which the exclusions table rerolls into travel-500. + // Each reroll's verified read is reused, and so is the last one + // for the first dispatch. The round loop used to read the panel + // 3 times between the failed reroll and the next attempt. + .name = "failed reroll then table reroll reuse verified reads", + .num_quests = 1, + .panel = {BBQuests::catch_fighting, BBQuests::make_tm, BBQuests::photo_savanna}, + .outcomes = {false}, + .new_quests = {BBQuests::pickup_10, BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .table_rerolls = {BBQuests::pickup_10}, + .reuse_rerolled_panel = true, + .expected_completed = 3, + .expected_attempted = {BBQuests::catch_fighting, BBQuests::travel_500, BBQuests::make_tm, BBQuests::photo_savanna}, + .expected_reads = 2, + .expected = "read process do reroll end process process do completed do completed read do completed end", + }, + { + // As above, but neither reroll's read is reusable. Only the + // first dispatch skips a read: 2 reads before the next attempt + // instead of 3. make-tm starts from travel-500's read. + .name = "failed reroll then table reroll without reusable reads", + .num_quests = 1, + .panel = {BBQuests::catch_fighting, BBQuests::make_tm, BBQuests::photo_savanna}, + .outcomes = {false}, + .new_quests = {BBQuests::pickup_10, BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .table_rerolls = {BBQuests::pickup_10}, + .expected_completed = 3, + .expected_attempted = {BBQuests::catch_fighting, BBQuests::travel_500, BBQuests::make_tm, BBQuests::photo_savanna}, + .expected_reads = 4, + .expected = "read process do reroll end read process read process do completed do completed read do completed end", + }, + { + // The save resets the game, so the reroll's read is not reused. + .name = "failed reroll before a save reads the panel after it", + .num_quests = 2, + .save_num_quests = 1, + .panel = {BBQuests::make_tm, BBQuests::catch_grass, BBQuests::photo_savanna}, + .outcomes = {true, false}, + .new_quests = {BBQuests::photo_canyon, BBQuests::travel_500, BBQuests::photo_coastal, BBQuests::photo_polar}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .reuse_rerolled_panel = true, + .expected_completed = 4, + .expected = "read process do completed read do reroll end(save) " + round_of_3 + " end(save)", + }, + { + // The goal (4) is reached in the middle of round 2. The loop only + // checks the goal between rounds, so round 2 finishes and 6 quests + // complete. + .name = "finishes the round that reaches the quest goal", + .num_quests = 4, + .expected_completed = 6, + .expected = round_of_3 + " end " + round_of_3 + " end", + }, + { + // Doing photo_swim also completes travel_500, so travel_500 is + // gone when the loop reads the panel before attempting it. + .name = "quest already gone counts as completed", + .num_quests = 3, + .panel = {BBQuests::photo_swim, BBQuests::travel_500, BBQuests::make_tm}, + .also_completes = {{BBQuests::photo_swim, BBQuests::travel_500}}, + .expected_completed = 3, + .expected = "read process do completed read completed read do completed end", + }, + { + // The first attempt fails: 3 attempts, 2 completions. + .name = "failed quest does not count", + .num_quests = 2, + .outcomes = {false}, + .expected_completed = 2, + .expected = "read process do read do completed read do completed end", + }, + { + // Nothing on the panel is doable, so process_quest_list() rerolls + // all of it and returns nothing; the loop reads the panel again. + .name = "panel with nothing doable is rerolled", + .num_quests = 3, + .panel = {BBQuests::pickup_10, BBQuests::catch_flying, BBQuests::UnableToDetect}, + .expected_completed = 3, + .expected = "read process " + round_of_3 + " end", + }, + { + .name = "saves at each milestone", + .num_quests = 6, + .save_num_quests = 3, + .expected_completed = 6, + .expected = round_of_3 + " end(save) " + round_of_3 + " end(save)", + }, + { + .name = "stops when out of eggs", + .num_quests = 5, + .stop_when_out_of_eggs = true, + .expected_completed = 0, + .expected = "", + }, + + // The ways the loop used to get stuck or lose time. + { + // sneak-up fails in round 1 and is still on the panel in round 2, + // where only the two new quests are attempted. + .name = "failed quest is not attempted again", + .num_quests = 4, + .never_completes = {BBQuests::sneak_up}, + .expected_completed = 4, + .expected = + "read process do completed read do completed read do end " + "read process do completed read do completed end", + }, + { + .name = "stops when only failed quests are doable", + .num_quests = 3, + .panel = {BBQuests::sneak_up, BBQuests::pickup_10, BBQuests::catch_flying}, + .never_completes = {BBQuests::sneak_up}, + .expected_completed = 0, + .expected = "read process do end read process", + }, + { + // Rerolls change nothing, so the panel never becomes doable. + .name = "gives up when rerolling does not help", + .num_quests = 3, + .panel = {BBQuests::pickup_10, BBQuests::catch_flying, BBQuests::UnableToDetect}, + .out_of_bp = true, + .expected_completed = 0, + .expected = read_30_times + "error", + }, + { + // 0 -> 3 crosses the milestone at 2 without landing on it. + .name = "saves when a round skips past a milestone", + .num_quests = 6, + .save_num_quests = 2, + .expected_completed = 6, + .expected = round_of_3 + " end(save) " + round_of_3 + " end(save)", + }, + { + // Three partial rounds each fail and reroll their first quest. + // None may save while the completed count is still zero. + .name = "round without completions does not save", + .num_quests = 3, + .save_num_quests = 2, + .outcomes = {false, false, false}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .expected_completed = 3, + .expected = + "read process do reroll end read process do reroll end " + "read process do reroll end " + round_of_3 + " end(save)", + }, + { + // sneak-up fails, then leaves the panel along with make-tm. Round 2 + // plans round 2 from a full panel without it (make-tm's read, no + // round actions), and its replacement for photo-canyon brings it + // back. Round 3 attempts it again. + .name = "failed quest that leaves a full panel is attempted again", + .num_quests = 5, + .panel = {BBQuests::sneak_up, BBQuests::make_tm, BBQuests::pickup_10, BBQuests::catch_flying}, + .outcomes = {false}, + .also_completes = {{BBQuests::make_tm, BBQuests::sneak_up}}, + .new_quests = {BBQuests::auto_10, BBQuests::photo_canyon, BBQuests::sneak_up}, + .expected_completed = 5, + .expected = + "read process do read do completed " + "process do completed read do completed end " + "read process do completed read do completed end", + }, + { + // As above with 3 slots. A 4th quest could have been missed by + // OCR, so the read does not prove sneak-up left: it stays failed. + .name = "failed quest missing from a 3-slot panel stays failed", + .num_quests = 4, + .panel = {BBQuests::sneak_up, BBQuests::make_tm, BBQuests::pickup_10}, + .outcomes = {false}, + .also_completes = {{BBQuests::make_tm, BBQuests::sneak_up}}, + .new_quests = {BBQuests::auto_10, BBQuests::photo_canyon, BBQuests::sneak_up}, + .expected_completed = 4, + .expected = + "read process do read do completed " + "process do completed read do completed end " + "read process do completed end", + }, + { + // Rerolling could never produce a doable panel, so the run + // fails before reading the panel. + .name = "fails at start when every blue quest is excluded", + .num_quests = 3, + .exclusions = every_doable_blue_quest(BBQAction::reroll), + .expected_completed = 0, + .expected = "error", + }, + { + // A run row keeps the quest doable even when another row skips it. + .name = "a quest with a run row is not excluded", + .num_quests = 3, + .exclusions = all_skipped_but_make_tm, + .expected_completed = 3, + .expected = round_of_3 + " end", + }, + { + // sneak-up is rerolled to photo-polar, which round 2 attempts. + .name = "out of retries with reroll replaces the failed quest", + .num_quests = 3, + .never_completes = {BBQuests::sneak_up}, + .out_of_retries = BBQOption::OutOfRetries::Reroll, + .expected_completed = 5, + .expected = "read process do completed read do completed read do reroll end " + round_of_3 + " end", + }, + { + .name = "out of retries with stop stops at once", + .num_quests = 3, + .panel = {BBQuests::sneak_up, BBQuests::make_tm, BBQuests::auto_10}, + .never_completes = {BBQuests::sneak_up}, + .out_of_retries = BBQOption::OutOfRetries::Stop, + .expected_completed = 0, + .expected = "read process do", + }, + { + // make-tm ends round 1 back at Central Plaza: its read plans + // round 2 with no round actions between it and travel-500. + .name = "no-trip quests chain with no round actions between", + .num_quests = 5, + .panel = {BBQuests::auto_10, BBQuests::sneak_up, BBQuests::make_tm}, + .new_quests = {BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar}, + .expected_completed = 6, + .expected_attempted = { + BBQuests::auto_10, BBQuests::sneak_up, BBQuests::make_tm, + BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, + }, + .expected_reads = 5, + .expected = + "read process do completed read do completed read do completed " + "process do completed read do completed read do completed end", + }, + { + // make-tm, travel-500 and photo-canyon on one board: only + // travel-500 starts from make-tm's read. The trip quest reads + // the panel and ends the round as usual. + .name = "no-trip then trip quest keeps the trip's usual steps", + .num_quests = 3, + .panel = {BBQuests::make_tm, BBQuests::travel_500, BBQuests::photo_canyon}, + .new_quests = {BBQuests::photo_coastal, BBQuests::photo_polar, BBQuests::photo_savanna}, + .expected_completed = 3, + .expected_reads = 2, + .expected = "read process do completed do completed read do completed end", + }, + { + .name = "failed no-trip quest ends the round as usual", + .num_quests = 3, + .panel = {BBQuests::auto_10, BBQuests::sneak_up, BBQuests::make_tm}, + .outcomes = {true, true, false}, + .new_quests = {BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar}, + .expected_completed = 4, + .expected = + "read process do completed read do completed read do end " + "read process do completed read do completed end", + }, + { + .name = "no-trip quest does not chain past a save", + .num_quests = 6, + .save_num_quests = 3, + .panel = {BBQuests::auto_10, BBQuests::sneak_up, BBQuests::make_tm}, + .new_quests = {BBQuests::travel_500, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar}, + .expected_completed = 6, + .expected = + "read process do completed read do completed read do completed end(save) " + "read process do completed read do completed read do completed end(save)", + }, + { + .name = "no-trip quest that reaches the goal ends the round", + .num_quests = 3, + .panel = {BBQuests::auto_10, BBQuests::sneak_up, BBQuests::make_tm}, + .expected_completed = 3, + .expected = "read process do completed read do completed read do completed end", + }, + }; + for (const BBQRoundsScenario& scenario : scenarios){ + database.add(scenario); + } +} + +} + + +namespace{ + +// The quests read from the panel, the options that matter, and the plan +// plan_quests() must make. The default exclusions table has one row: +// auto-10, skip. +struct BBQuestPlanScenario{ + std::string name; + std::vector quests; + std::vector> extra_exclusions = {}; + std::optional bp = 1000; + uint8_t num_eggs = 1; + uint8_t eggs_hatched = 0; + BBQOption::OOEggs out_of_eggs = BBQOption::OOEggs::Reroll; + std::vector expected_to_do = {}; + std::vector expected_reroll_slots = {}; + bool expected_reroll_all = false; +}; + +std::string quests_to_string(const std::vector& quests){ + std::string ret; + for (BBQuests quest : quests){ + ret += std::to_string((int)quest) + " "; + } + return ret; +} +std::string slots_to_string(const std::vector& slots){ + std::string ret; + for (size_t slot : slots){ + ret += std::to_string(slot) + " "; + } + return ret; +} + +class Test_BBQuestPlan : public UnitTest{ +public: + Test_BBQuestPlan(BBQuestPlanScenario scenario) + : UnitTest("PokemonSV::BBQuestPlan - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + BBQOption options; + options.NUM_EGGS.set(m_scenario.num_eggs); + options.OUT_OF_EGGS.set(m_scenario.out_of_eggs); + for (const auto& [quest, action] : m_scenario.extra_exclusions){ + auto row = std::make_unique(options.QUEST_EXCLUSIONS); + row->quest.set(quest); + row->action.set(action); + options.QUEST_EXCLUSIONS.append_row(std::move(row)); + } + + NullLogger logger; + const BBQuestPlan plan = plan_quests(logger, options, m_scenario.quests, m_scenario.eggs_hatched, m_scenario.bp); + if (plan.to_do != m_scenario.expected_to_do){ + return "Expected quests to do: " + quests_to_string(m_scenario.expected_to_do) + + "got: " + quests_to_string(plan.to_do); + } + if (plan.reroll_slots != m_scenario.expected_reroll_slots){ + return "Expected reroll slots: " + slots_to_string(m_scenario.expected_reroll_slots) + + "got: " + slots_to_string(plan.reroll_slots); + } + if (plan.reroll_all != m_scenario.expected_reroll_all){ + return std::string("Expected reroll_all = ") + (m_scenario.expected_reroll_all ? "true" : "false"); + } + return true; + } + +private: + const BBQuestPlanScenario m_scenario; +}; + + +// A quest panel with a cursor. A reroll replaces the quest under the cursor +// with the next of `replacements`, unless out of BP. +class SimulatedQuestPanel : public BBQRerollActions{ +public: + std::vector quests; + std::vector replacements; + size_t cursor = 0; + bool panel_opens = true; + bool menu_seen = true; + bool out_of_bp = false; + int missed_reads = 0; // Reads that fail OCR on every slot. + std::optional> read_override; + + bool panel_open = false; + bool menu_open = false; + std::vector rerolled_slots; + + virtual bool open_panel() override{ + panel_open = panel_opens; + return panel_open; + } + virtual std::optional open_reroll_menu() override{ + menu_open = true; + if (!menu_seen){ + return std::nullopt; + } + return cursor; + } + virtual void close_reroll_menu() override{ + menu_open = false; + } + virtual void move_cursor(int slots) override{ + cursor = (size_t)((int)cursor + slots); + } + virtual void confirm_reroll() override{ + menu_open = false; + if (out_of_bp){ + return; + } + rerolled_slots.push_back(cursor); + quests[cursor] = replacements[rerolled_slots.size() - 1]; + } + virtual void close_panel() override{ + panel_open = false; + menu_open = false; + } + virtual std::vector read_quests() override{ + if (missed_reads > 0){ + missed_reads--; + return std::vector(quests.size(), BBQuests::UnableToDetect); + } + return read_override.value_or(quests); + } +}; + +struct BBQRerollScenario{ + std::string name; + std::vector quests; + std::vector replacements = {}; + size_t slot; + size_t cursor = 0; + bool panel_opens = true; + bool menu_seen = true; + bool out_of_bp = false; + int missed_reads = 0; + std::optional> read_override = {}; + BBQRerollResult expected; + std::vector expected_rerolled_slots = {}; + std::vector expected_quests; + std::optional> expected_observed_panel = {}; +}; + +std::string reroll_result_to_string(BBQRerollResult result){ + switch (result){ + case BBQRerollResult::Rerolled: return "Rerolled"; + case BBQRerollResult::PanelNotOpened: return "PanelNotOpened"; + case BBQRerollResult::MenuNotFound: return "MenuNotFound"; + case BBQRerollResult::NotReplaced: return "NotReplaced"; + } + return "?"; +} + +class Test_BBQReroll : public UnitTest{ +public: + Test_BBQReroll(BBQRerollScenario scenario) + : UnitTest("PokemonSV::BBQReroll - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + SimulatedQuestPanel panel; + panel.quests = m_scenario.quests; + panel.replacements = m_scenario.replacements; + panel.cursor = m_scenario.cursor; + panel.panel_opens = m_scenario.panel_opens; + panel.menu_seen = m_scenario.menu_seen; + panel.out_of_bp = m_scenario.out_of_bp; + panel.missed_reads = m_scenario.missed_reads; + panel.read_override = m_scenario.read_override; + + RecordingLogger logger; + std::vector quests = m_scenario.quests; + std::optional> observed_panel; + const BBQRerollResult result = reroll_quest(logger, panel, quests, m_scenario.slot, observed_panel); + //Each reroll logs one line naming its slot and quest, whatever the result. + const std::string reroll_line = "Rerolling quest " + std::to_string(m_scenario.slot + 1) + + " (" + BBQuests_enum_to_string(m_scenario.quests[m_scenario.slot]) + ")."; + const size_t reroll_lines = std::count_if(logger.lines.begin(), logger.lines.end(), [](const std::string& line){ + return line.starts_with("Rerolling quest "); + }); + if (reroll_lines != 1 || std::find(logger.lines.begin(), logger.lines.end(), reroll_line) == logger.lines.end()){ + return "Expected one log line \"" + reroll_line + "\", got " + std::to_string(reroll_lines) + " reroll lines."; + } + if (result != m_scenario.expected){ + return "Expected " + reroll_result_to_string(m_scenario.expected) + + ", got " + reroll_result_to_string(result); + } + if (panel.rerolled_slots != m_scenario.expected_rerolled_slots){ + return "Expected rerolled slots: " + slots_to_string(m_scenario.expected_rerolled_slots) + + "got: " + slots_to_string(panel.rerolled_slots); + } + if (quests != m_scenario.expected_quests){ + return "Expected quests: " + quests_to_string(m_scenario.expected_quests) + + "got: " + quests_to_string(quests); + } + if (observed_panel != m_scenario.expected_observed_panel){ + return "Expected observed panel: " + quests_to_string(m_scenario.expected_observed_panel.value_or(std::vector{})) + + ", got: " + quests_to_string(observed_panel.value_or(std::vector{})); + } + if (panel.panel_open || panel.menu_open){ + return "Panel left open."; + } + return true; + } + +private: + const BBQRerollScenario m_scenario; +}; + +} + +static void add_tests_BBQuestPlan(UnitTestDatabase& database){ + using enum BBQuests; + const BBQuestPlanScenario scenarios[] = { + { + .name = "default table skips auto-10", + .quests = {make_tm, auto_10, sneak_up}, + .expected_to_do = {make_tm, sneak_up}, + }, + { + // Left alone, it would hold its slot until something else is + // rerolled. A blue reroll costs 10 BP. + .name = "a blue quest not possible is rerolled while others are doable", + .quests = {make_tm, catch_flying, sneak_up}, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {1}, + }, + { + // An undetected quest is neither run nor rerolled. + .name = "a quest not possible is rerolled, an undetected one is not", + .quests = {pickup_10, make_tm, UnableToDetect}, + .expected_to_do = {make_tm}, + .expected_reroll_slots = {0}, + }, + { + // A red quest costs 50 BP to reroll, but pays 100-150 BP, and + // the next red quest cannot appear while it stays. + .name = "a red quest not possible is rerolled while the blues are doable", + .quests = {photo_flying, make_tm, sneak_up, travel_500}, + .expected_to_do = {make_tm, sneak_up, travel_500}, + .expected_reroll_slots = {0}, + }, + { + // The board that held 2 of 4 slots for 20 minutes. + .name = "a red and a blue quest not possible are both rerolled", + .quests = {photo_flying, make_tm, catch_flying, sneak_up}, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {0, 2}, + }, + { + // There is no longer a single slot to fall back on: every quest + // not possible was rerolled already, so not every quest is. + .name = "nothing doable rerolls each quest not possible, not all", + .quests = {photo_flying, auto_10, pickup_10, catch_flying}, + .expected_reroll_slots = {0, 2, 3}, + }, + { + .name = "a skip row keeps a red quest not possible", + .quests = {photo_flying, make_tm, catch_flying, sneak_up}, + .extra_exclusions = {{photo_flying, BBQAction::skip}}, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {2}, + }, + { + .name = "a run row keeps a blue quest not possible", + .quests = {photo_flying, make_tm, catch_flying, sneak_up}, + .extra_exclusions = {{catch_flying, BBQAction::run}}, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {0}, + }, + { + // A red reroll costs 50 BP, a blue one 10. + .name = "BP for a blue reroll but not a red one skips the red quest not possible", + .quests = {photo_flying, make_tm, catch_flying, sneak_up}, + .bp = 49, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {2}, + }, + { + .name = "BP for exactly a red reroll rerolls it and skips the blue one", + .quests = {photo_flying, make_tm, catch_flying, sneak_up}, + .bp = 55, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {0}, + }, + { + // Before, the reroll did not happen and the program stopped. + .name = "BP under a blue reroll skips quests not possible and runs the doable ones", + .quests = {photo_flying, make_tm, catch_flying, sneak_up}, + .bp = 9, + .expected_to_do = {make_tm, sneak_up}, + }, + { + .name = "unknown BP skips quests not possible and runs the doable ones", + .quests = {photo_flying, make_tm, catch_flying, sneak_up}, + .bp = std::nullopt, + .expected_to_do = {make_tm, sneak_up}, + }, + { + // A reroll row is paid for first. + .name = "BP left after a reroll row decides the quests not possible", + .quests = {make_tm, catch_flying, sneak_up, pickup_10}, + .extra_exclusions = {{sneak_up, BBQAction::reroll}}, + .bp = 25, + .expected_to_do = {make_tm}, + .expected_reroll_slots = {1, 2}, + }, + { + // Nothing else changes the panel, so BP does not hold it back. + .name = "nothing doable rerolls each quest not possible whatever the BP", + .quests = {photo_flying, auto_10, catch_flying}, + .bp = 0, + .expected_reroll_slots = {0, 2}, + }, + { + .name = "nothing doable and nothing not possible rerolls all", + .quests = {auto_10, sneak_up}, + .extra_exclusions = {{sneak_up, BBQAction::skip}}, + .expected_reroll_all = true, + }, + { + // An undetected quest is not known to be impossible. + .name = "an undetected quest is not rerolled alone", + .quests = {UnableToDetect, auto_10}, + .expected_reroll_all = true, + }, + { + .name = "a skipped quest not possible is not rerolled", + .quests = {pickup_10, auto_10, catch_flying}, + .extra_exclusions = {{pickup_10, BBQAction::skip}}, + .expected_reroll_slots = {2}, + }, + { + // Only skipped quests left: nothing changes the panel otherwise. + .name = "skip rows on every quest not possible reroll all when nothing is doable", + .quests = {photo_flying, auto_10, catch_flying}, + .extra_exclusions = { + {photo_flying, BBQAction::skip}, + {catch_flying, BBQAction::skip}, + }, + .expected_reroll_all = true, + }, + { + .name = "a reroll row rerolls a quest not possible", + .quests = {make_tm, sneak_up, pickup_10}, + .extra_exclusions = {{pickup_10, BBQAction::reroll}}, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {2}, + }, + { + .name = "a run row does not run a quest not possible", + .quests = {make_tm, pickup_10}, + .extra_exclusions = {{pickup_10, BBQAction::run}}, + .expected_to_do = {make_tm}, + }, + { + // The reroll replaces a quest, so the next read has something new. + .name = "a reroll row rerolls that slot", + .quests = {make_tm, sneak_up, travel_500}, + .extra_exclusions = {{travel_500, BBQAction::reroll}}, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {2}, + }, + { + // A reroll is already a change, so nothing more is rerolled. + .name = "a rerolled slot with nothing doable does not reroll all", + .quests = {pickup_10, sneak_up, auto_10}, + .extra_exclusions = {{sneak_up, BBQAction::reroll}}, + .expected_reroll_slots = {0, 1}, + }, + { + // Each row for a quest applies, in table order. + .name = "every table row for a quest applies", + .quests = {travel_500, auto_10}, + .extra_exclusions = { + {travel_500, BBQAction::run}, + {auto_10, BBQAction::run}, + {travel_500, BBQAction::run}, + }, + .expected_to_do = {travel_500, travel_500, auto_10}, + }, + { + .name = "egg quest is done while eggs remain", + .quests = {make_tm, hatch_egg, sneak_up}, + .expected_to_do = {make_tm, hatch_egg, sneak_up}, + }, + { + // The egg quest is rerolled where it is on the panel, not always + // in the top slot. + .name = "out of eggs rerolls the egg quest slot", + .quests = {make_tm, hatch_egg, sneak_up}, + .eggs_hatched = 1, + .expected_to_do = {make_tm, sneak_up}, + .expected_reroll_slots = {1}, + }, + { + .name = "out of eggs with keep going leaves the egg quest", + .quests = {make_tm, hatch_egg, sneak_up}, + .eggs_hatched = 1, + .out_of_eggs = BBQOption::OOEggs::KeepGoing, + .expected_to_do = {make_tm, sneak_up}, + }, + }; + for (const BBQuestPlanScenario& scenario : scenarios){ + database.add(scenario); + } +} + +static void add_tests_BBQReroll(UnitTestDatabase& database){ + using enum BBQuests; + const BBQRerollScenario scenarios[] = { + { + .name = "unknown fourth slot is not reusable", + .quests = {make_tm, travel_500, sneak_up, hatch_egg}, + .replacements = {catch_any}, + .slot = 2, + .read_override = std::vector{make_tm, travel_500, catch_any, UnableToDetect}, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, travel_500, catch_any, hatch_egg}, + }, + { + .name = "missing fourth slot is not reusable", + .quests = {make_tm, travel_500, sneak_up, hatch_egg}, + .replacements = {catch_any}, + .slot = 2, + .read_override = std::vector{make_tm, travel_500, catch_any}, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, travel_500, catch_any, hatch_egg}, + }, + { + .name = "another changed quest is not reusable", + .quests = {make_tm, travel_500, sneak_up, hatch_egg}, + .replacements = {catch_any}, + .slot = 2, + .read_override = std::vector{photo_canyon, travel_500, catch_any, hatch_egg}, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, travel_500, catch_any, hatch_egg}, + }, + { + // The panel used for the reroll had 3 slots, so a 3-slot read is + // not a missed fourth quest. + .name = "three-slot read of a three-slot panel is reusable", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {catch_any}, + .slot = 2, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, catch_any}, + .expected_observed_panel = std::vector{make_tm, sneak_up, catch_any}, + }, + { + .name = "three-slot read with an unknown slot is not reusable", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {catch_any}, + .slot = 2, + .read_override = std::vector{make_tm, UnableToDetect, catch_any}, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, catch_any}, + }, + { + .name = "three-slot read with another changed quest is not reusable", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {catch_any}, + .slot = 2, + .read_override = std::vector{photo_canyon, sneak_up, catch_any}, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, catch_any}, + }, + { + // The panel used for the reroll missed this fourth quest. + .name = "fourth quest not on the three-slot panel is not reusable", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {catch_any}, + .slot = 2, + .read_override = std::vector{make_tm, sneak_up, catch_any, hatch_egg}, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, catch_any}, + }, + { + .name = "complete observation after missed reads is reusable", + .quests = {make_tm, travel_500, sneak_up, hatch_egg}, + .replacements = {catch_any}, + .slot = 2, + .missed_reads = 2, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, travel_500, catch_any, hatch_egg}, + .expected_observed_panel = std::vector{make_tm, travel_500, catch_any, hatch_egg}, + }, + { + .name = "cursor on the top quest", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {catch_any}, + .slot = 2, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, catch_any}, + .expected_observed_panel = std::vector{make_tm, sneak_up, catch_any}, + }, + { + // Seen on a Switch: the panel can open with the cursor where it + // was left, so moving down from the top rerolls the wrong quest. + .name = "cursor left below the quest moves up", + .quests = {make_tm, travel_500, sneak_up, hatch_egg}, + .replacements = {catch_any}, + .slot = 1, + .cursor = 3, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {1}, + .expected_quests = {make_tm, catch_any, sneak_up, hatch_egg}, + .expected_observed_panel = std::vector{make_tm, catch_any, sneak_up, hatch_egg}, + }, + { + .name = "fourth quest", + .quests = {make_tm, travel_500, sneak_up, hatch_egg}, + .replacements = {catch_any}, + .slot = 3, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {3}, + .expected_quests = {make_tm, travel_500, sneak_up, catch_any}, + .expected_observed_panel = std::vector{make_tm, travel_500, sneak_up, catch_any}, + }, + { + .name = "panel not opened spends nothing", + .quests = {make_tm, sneak_up, travel_500}, + .slot = 2, + .panel_opens = false, + .expected = BBQRerollResult::PanelNotOpened, + .expected_quests = {make_tm, sneak_up, travel_500}, + }, + { + .name = "menu not seen spends nothing", + .quests = {make_tm, sneak_up, travel_500}, + .slot = 2, + .menu_seen = false, + .expected = BBQRerollResult::MenuNotFound, + .expected_quests = {make_tm, sneak_up, travel_500}, + }, + { + .name = "out of BP is not replaced", + .quests = {make_tm, sneak_up, travel_500}, + .slot = 2, + .out_of_bp = true, + .expected = BBQRerollResult::NotReplaced, + .expected_quests = {make_tm, sneak_up, travel_500}, + }, + { + .name = "a missed read is read again", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {catch_any}, + .slot = 2, + .missed_reads = 2, + .expected = BBQRerollResult::Rerolled, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, catch_any}, + .expected_observed_panel = std::vector{make_tm, sneak_up, catch_any}, + }, + { + .name = "three missed reads give up", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {catch_any}, + .slot = 2, + .missed_reads = 3, + .expected = BBQRerollResult::NotReplaced, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, travel_500}, + }, + { + // Cannot be told apart from out of BP. + .name = "replaced by the same quest is not replaced", + .quests = {make_tm, sneak_up, travel_500}, + .replacements = {travel_500}, + .slot = 2, + .expected = BBQRerollResult::NotReplaced, + .expected_rerolled_slots = {2}, + .expected_quests = {make_tm, sneak_up, travel_500}, + }, + }; + for (const BBQRerollScenario& scenario : scenarios){ + database.add(scenario); + } +} + + + +namespace{ + +// Balance reads in order, each at a minute offset from the first, and the +// ledger they must produce. A negative read is an OCR failure. "spend_before" +// is what the program paid for rerolls just before the read (-1: a reroll of +// unknown cost). +struct BBQPointsLedgerScenario{ + struct Read{ + int balance; + int minute; + int spend_before = 0; + }; + std::string name; + std::vector reads = {}; + int expected_start = -1; + uint64_t expected_earned = 0; + uint64_t expected_spent = 0; + int64_t expected_net = 0; + int64_t expected_per_hour = 0; + uint64_t expected_checked = 0; + uint64_t expected_mismatched = 0; +}; + +class Test_BBQPointsLedger : public UnitTest{ +public: + Test_BBQPointsLedger(BBQPointsLedgerScenario scenario) + : UnitTest("PokemonSV::BBQPointsLedger - " + scenario.name) + , m_scenario(std::move(scenario)) + {} + + virtual UnitTestResult run(Logger&, CancellableScope&) const override{ + const WallClock start = current_time(); + BBQPointsLedger ledger; + for (const BBQPointsLedgerScenario::Read& read : m_scenario.reads){ + if (read.spend_before < 0){ + ledger.skip_spend_check(); + }else if (read.spend_before > 0){ + ledger.expect_spend(read.spend_before); + } + ledger.record(read.balance, start + std::chrono::minutes(read.minute)); + } + const std::pair> checks[] = { + {"starting balance", {m_scenario.expected_start, ledger.starting_balance}}, + {"earned", {(int64_t)m_scenario.expected_earned, (int64_t)ledger.earned}}, + {"spent", {(int64_t)m_scenario.expected_spent, (int64_t)ledger.spent}}, + {"net", {m_scenario.expected_net, ledger.net()}}, + {"net per hour", {m_scenario.expected_per_hour, ledger.net_per_hour()}}, + {"checked reroll windows", {(int64_t)m_scenario.expected_checked, (int64_t)ledger.checked_windows}}, + {"mismatched reroll windows", {(int64_t)m_scenario.expected_mismatched, (int64_t)ledger.mismatched_windows}}, + //Reconciled means a balance was read and no reroll window mismatched. + {"reconciled", {m_scenario.expected_start >= 0 && m_scenario.expected_mismatched == 0, ledger.reconciled()}}, + }; + for (const auto& [field, values] : checks){ + if (values.first != values.second){ + return std::string("Expected ") + field + " " + std::to_string(values.first) + + ", got " + std::to_string(values.second); + } + } + return true; + } + +private: + const BBQPointsLedgerScenario m_scenario; +}; + +} + +// Reroll windows where the next read does not show what the rerolls should have cost. +static void add_tests_BBQPointsLedgerMismatches(UnitTestDatabase& database){ + const BBQPointsLedgerScenario mismatches[] = { + { + // The game didn't take the BP: the reroll didn't happen. + .name = "a reroll that cost nothing is a mismatch", + .reads = {{6750, 0}, {6750, 1, 10}}, + .expected_start = 6750, + .expected_checked = 1, + .expected_mismatched = 1, + }, + { + // 6740 misread as 6140. + .name = "a misread after a reroll is a mismatch", + .reads = {{6750, 0}, {6140, 1, 10}}, + .expected_start = 6750, + .expected_spent = 610, + .expected_net = -610, + .expected_per_hour = -36600, + .expected_checked = 1, + .expected_mismatched = 1, + }, + }; + for (const BBQPointsLedgerScenario& scenario : mismatches){ + database.add(scenario); + } +} + +// Reroll windows: what the rerolls should have cost against the next read. +static void add_tests_BBQPointsLedgerRerolls(UnitTestDatabase& database){ + const BBQPointsLedgerScenario scenarios[] = { + { + // A blue and a red reroll, each followed by a read, as the farmer does. + .name = "rerolls that match the reads reconcile", + .reads = {{6750, 0}, {6740, 1, 10}, {6800, 10}, {6750, 11, 50}}, + .expected_start = 6750, + .expected_earned = 60, + .expected_spent = 60, + .expected_per_hour = 0, + .expected_checked = 2, + }, + { + // The next read may include quest income, so the window isn't checked. + .name = "a failed read after a reroll skips the check", + .reads = {{6750, 0}, {-1, 1, 10}, {6790, 10}}, + .expected_start = 6750, + .expected_earned = 40, + .expected_net = 40, + .expected_per_hour = 240, + }, + { + .name = "a reroll of unknown cost skips the check", + .reads = {{6750, 0}, {6700, 1, -1}}, + .expected_start = 6750, + .expected_spent = 50, + .expected_net = -50, + .expected_per_hour = -3000, + }, + }; + for (const BBQPointsLedgerScenario& scenario : scenarios){ + database.add(scenario); + } +} + +static void add_tests_BBQPointsLedger(UnitTestDatabase& database){ + const BBQPointsLedgerScenario scenarios[] = { + { + .name = "no reads", + }, + { + .name = "one read sets the start", + .reads = {{6750, 0}}, + .expected_start = 6750, + }, + { + // A quest reward, then a reroll. + .name = "rises are earned and drops are spent", + .reads = {{6750, 0}, {6780, 10}, {6730, 20}}, + .expected_start = 6750, + .expected_earned = 30, + .expected_spent = 50, + .expected_net = -20, + .expected_per_hour = -60, + }, + { + .name = "an unchanged balance adds nothing", + .reads = {{6750, 0}, {6750, 30}}, + .expected_start = 6750, + }, + { + .name = "OCR failures are skipped", + .reads = {{6750, 0}, {-1, 5}, {6800, 30}}, + .expected_start = 6750, + .expected_earned = 50, + .expected_net = 50, + .expected_per_hour = 100, + }, + { + // The hour starts at the first successful read. + .name = "a failed first read does not set the start", + .reads = {{-1, 0}, {6750, 10}, {6760, 70}}, + .expected_start = 6750, + .expected_earned = 10, + .expected_net = 10, + .expected_per_hour = 10, + }, + }; + for (const BBQPointsLedgerScenario& scenario : scenarios){ + database.add(scenario); + } + add_tests_BBQPointsLedgerRerolls(database); + add_tests_BBQPointsLedgerMismatches(database); +} + + + void add_tests_BBQ(UnitTestDatabase& database){ database.add(); @@ -133,7 +1522,13 @@ void add_tests_BBQ(UnitTestDatabase& database){ database.add("PokemonSV/BlueberryPoints/6740.png", 6740, 1920, 1080); database.add("PokemonSV/BlueberryPoints/6740.png", 6740, 1280, 720); + add_tests_BBQReroll(database); + add_tests_BBQuestPlan(database); + add_tests_BBQFarmerRounds(database); + add_tests_BBQPointsLedger(database); add_tests_TeraEncounterAction(database); + add_tests_BBQDiagnosticLogs(database); + add_tests_BBQSnapshot(database); } diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp index 3a24e1d187..de89e53043 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp @@ -5,7 +5,6 @@ */ #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" -#include "CommonFramework/Tools/ErrorDumper.h" #include "CommonFramework/Exceptions/ProgramFinishedException.h" #include "CommonTools/Async/InferenceRoutines.h" #include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" @@ -26,6 +25,7 @@ #include "VideoGames/PokemonSV/Programs/PokemonSV_WorldNavigation.h" #include "VideoGames/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" #include "VideoGames/PokemonSV/Programs/PokemonSV_Terarium.h" +#include "PokemonSV_BBQSnapshot.h" #include "PokemonSV_BlueberryCatchPhoto.h" namespace PokemonAutomation{ @@ -916,7 +916,7 @@ void quest_catch( { battle_menu } ); if (ret2 != 0){ - console.log("Did not enter battle. Did target spawn?"); + record_bbq_battle_entry_timeout(console, current_quest); } }, { diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp index c90bae7a04..b099b38c71 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp @@ -4,6 +4,7 @@ * */ +#include #include #include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h" #include "CommonFramework/Tools/ErrorDumper.h" @@ -22,6 +23,7 @@ #include "VideoGames/PokemonSV/PokemonSV_Settings.h" #include "VideoGames/PokemonSV/Programs/PokemonSV_GameEntry.h" #include "VideoGames/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "VideoGames/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" #include "VideoGames/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" #include "VideoGames/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" #include "VideoGames/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" @@ -42,6 +44,8 @@ #include "VideoGames/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" #include "VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h" #include "VideoGames/PokemonSV/Programs/PokemonSV_Terarium.h" +#include "PokemonSV_BBQLogger.h" +#include "PokemonSV_BBQSnapshot.h" #include "PokemonSV_BlueberryQuests.h" @@ -76,30 +80,41 @@ int read_BP(const ProgramInfo& info, VideoStream& stream, ProControllerContext& return read_BP_from_image(stream.logger(), screen); } -std::vector read_quests( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -){ - std::vector quest_list; +namespace{ - //Open quest list. Wait for it to open. - WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); +//Open the quest panel from the overworld. Returns false if it did not open. +bool open_quest_panel(VideoStream& stream, ProControllerContext& context){ + WhiteButtonWatcher panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); int result = run_until( stream, context, [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++){ //try 6 times + for (int i = 0; i < 6; i++){ pbf_press_dpad(context, DPAD_RIGHT, 400ms, 160ms); pbf_wait(context, 1600ms); context.wait_for_all_requests(); } }, - {{ right_panel }} + {{ panel }} ); if (result == 0){ stream.log("Found quest panel."); } context.wait_for_all_requests(); + return result == 0; +} + +} + +// Detector index 0 confirms the quest panel; a negative run_until result means no detection. +std::vector read_quests( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + int* BP +){ + std::vector quest_list; + + const bool panel_detected = open_quest_panel(stream, context); //Read in the initial 4 quests. stream.log("Reading quests."); @@ -118,6 +133,12 @@ std::vector read_quests( quest_list.push_back(BBQuests_string_to_enum(fourth_quest)); } + //The balance is on the same panel, so reading it costs no extra button presses. + if (BP != nullptr){ + *BP = read_BP_from_image(stream.logger(), screen); + } + BBQLogger(stream.logger()).board(/*panel_detected=*/panel_detected, quest_list); + //Close quest list pbf_mash_button(context, BUTTON_B, 800ms); context.wait_for_all_requests(); @@ -125,177 +146,393 @@ std::vector read_quests( return quest_list; } -std::vector process_quest_list( +namespace{ + +//Out of eggs, the egg quest cannot be done. OUT_OF_EGGS decides what happens to it. +void plan_out_of_eggs(Logger& logger, const BBQOption& BBQ_OPTIONS, size_t slot, BBQuestPlan& plan){ + switch (BBQ_OPTIONS.OUT_OF_EGGS){ + case BBQOption::OOEggs::Reroll: + logger.log("Reroll selected. Rerolling Egg quest. New quest will be run in the next batch of quests."); + //logger.log("Warning: This does not handle/check being out of BP!", COLOR_RED); + plan.reroll_slots.push_back(slot); + break; + case BBQOption::OOEggs::KeepGoing: + logger.log("Keep Going selected. Ignoring quest."); + break; + default: + //This case is handled in BBQSoloFarmer. + throw InternalProgramError(&logger, PA_CURRENT_FUNCTION, "OOEggs is Stop in process_quest_list()."); + } +} + +//Apply each exclusions table row for the quest, in table order. Returns false if no row is for it. +//A quest the program cannot do is never run, but can still be rerolled or skipped. +bool plan_from_exclusions( + Logger& logger, + const std::vector>& exclusions_table, + BBQuests quest, size_t slot, bool possible, + BBQuestPlan& plan +){ + bool quest_in_table = false; + for (const std::unique_ptr& row : exclusions_table){ + if (quest != row->quest){ + continue; + } + logger.log("Quest found in inclusions/exclusions table."); + quest_in_table = true; + switch (row->action){ + case BBQAction::run: + if (!possible){ + logger.log("Run selected, but this quest is not possible. Skipping quest."); + break; + } + logger.log("Run selected. Adding quest to list."); + plan.to_do.push_back(quest); + break; + case BBQAction::reroll: + logger.log("Reroll selected. Rerolling quest. New quest will be run in the next batch of quests."); + plan.reroll_slots.push_back(slot); + break; + case BBQAction::skip: + logger.log("Skip selected. Skipping quest."); + break; + } + } + return quest_in_table; +} + +class ConsoleBBQRerollActions : public BBQRerollActions{ +public: + ConsoleBBQRerollActions( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQPointsLedger* ledger, int reroll_cost + ) + : m_info(info), m_stream(stream), m_context(context), m_options(BBQ_OPTIONS) + , m_ledger(ledger), m_reroll_cost(reroll_cost) + {} + + virtual bool open_panel() override{ + return open_quest_panel(m_stream, m_context); + } + virtual std::optional open_reroll_menu() override{ + //The menu opens next to the quest, with an arrow on its top choice. Slots are 0.177 + //apart; the boxes for the top 3 slots were checked on a Switch, the 4th is spaced + //the same way. + GradientArrowWatcher slot0(COLOR_RED, GradientArrowType::RIGHT, {0.475, 0.218, 0.070, 0.095}); + GradientArrowWatcher slot1(COLOR_RED, GradientArrowType::RIGHT, {0.475, 0.395, 0.070, 0.095}); + GradientArrowWatcher slot2(COLOR_RED, GradientArrowType::RIGHT, {0.475, 0.572, 0.070, 0.095}); + GradientArrowWatcher slot3(COLOR_RED, GradientArrowType::RIGHT, {0.475, 0.749, 0.070, 0.095}); + pbf_press_button(m_context, BUTTON_A, 160ms, 400ms); + m_context.wait_for_all_requests(); + int ret = wait_until( + m_stream, m_context, std::chrono::seconds(3), + {slot0, slot1, slot2, slot3} + ); + if (ret < 0){ + return std::nullopt; + } + return (size_t)ret; + } + virtual void close_reroll_menu() override{ + pbf_press_button(m_context, BUTTON_B, 160ms, 400ms); + m_context.wait_for_all_requests(); + } + virtual void move_cursor(int slots) override{ + for (int i = 0; i < std::abs(slots); i++){ + pbf_press_dpad(m_context, slots > 0 ? DPAD_DOWN : DPAD_UP, 160ms, 160ms); + pbf_wait(m_context, 800ms); + } + m_context.wait_for_all_requests(); + } + virtual void confirm_reroll() override{ + pbf_press_button(m_context, BUTTON_A, 160ms, 400ms); + pbf_wait(m_context, 800ms); + m_context.wait_for_all_requests(); + if (m_ledger != nullptr){ + m_ledger->expect_spend(m_reroll_cost); + } + } + virtual void close_panel() override{ + press_Bs_to_back_to_overworld(m_info, m_stream, m_context); + } + virtual std::vector read_quests() override{ + m_stream.log("Reading quest panel to verify reroll."); + int BP = -1; + std::vector quests = PokemonSV::read_quests(m_info, m_stream, m_context, m_options, &BP); + if (m_ledger != nullptr){ + m_ledger->record(BP, current_time()); + } + return quests; + } + +private: + const ProgramInfo& m_info; + VideoStream& m_stream; + ProControllerContext& m_context; + const BBQOption& m_options; + BBQPointsLedger* m_ledger; + int m_reroll_cost; +}; + +//This does not handle out of BP. +void reroll_all_slots( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const std::vector& quests, + BBQPointsLedger* ledger +){ + open_quest_panel(stream, context); + + for (BBQuests quest : quests){ + if (ledger != nullptr){ + //An unreadable slot may be empty or a quest of unknown cost. + if (quest == BBQuests::UnableToDetect){ + ledger->skip_spend_check(); + }else{ + ledger->expect_spend(reroll_cost(quest)); + } + } + pbf_press_button(context, BUTTON_A, 160ms, 400ms); + pbf_press_button(context, BUTTON_A, 160ms, 400ms); //Yes. + pbf_wait(context, 800ms); + context.wait_for_all_requests(); + pbf_press_dpad(context, DPAD_DOWN, 160ms, 160ms); + pbf_wait(context, 800ms); + context.wait_for_all_requests(); + } + //Close quest panel - mash b + press_Bs_to_back_to_overworld(info, stream, context); +} + +} + +BBQRerollResult reroll_quest( + Logger& logger, + BBQRerollActions& actions, + std::vector& quests, + size_t slot, + std::optional>& observed_panel +){ + observed_panel.reset(); + // An unavailable slot is logged as unknown without indexing outside the board. + const BBQuests quest = slot < quests.size() ? quests[slot] : BBQuests::UnableToDetect; + BBQLogger(logger).reroll_attempt(/*slot=*/slot, /*quest=*/quest); + if (!actions.open_panel()){ + return BBQRerollResult::PanelNotOpened; + } + + //The cursor is not always on the top quest when the panel opens; it can be left where it + //was. So open the menu wherever the cursor is, see which quest it opened next to, and move + //from there. Moving can drop a press, so this is tried a few times. + bool menu_on_slot = false; + for (int attempt = 0; attempt < 3 && !menu_on_slot; attempt++){ + std::optional menu_slot = actions.open_reroll_menu(); + if (!menu_slot){ + //Without a menu, B would close the panel instead, so stop here. + break; + } + if (*menu_slot == slot){ + menu_on_slot = true; + break; + } + logger.log("Reroll menu opened on quest " + std::to_string(*menu_slot + 1) + ". Moving to quest " + std::to_string(slot + 1) + "."); + actions.close_reroll_menu(); + actions.move_cursor((int)slot - (int)*menu_slot); + } + if (!menu_on_slot){ + actions.close_panel(); + return BBQRerollResult::MenuNotFound; + } + actions.confirm_reroll(); + actions.close_panel(); + + //A read can miss the quest in the slot, so read up to 3 times before deciding it is + //still the old quest. + for (int read = 0; read < 3; read++){ + std::vector after = actions.read_quests(); + if (slot < after.size() && after[slot] != quests[slot] && after[slot] != BBQuests::UnableToDetect){ + logger.log("Quest " + std::to_string(slot + 1) + " rerolled."); + quests[slot] = after[slot]; + //Reuse only a read whose slots are all known and, apart from the + //rerolled one, agree with the panel used for this reroll. Three + //slots can mean a missed fourth quest, so a 3-slot read is only + //reused when that panel had 3 slots too. Both reads could have + //missed the same fourth quest, as a fresh read also could. That + //quest is then left out of one plan, which costs no BP, and a + //3-slot read never proves a failed quest left the panel. + if (after.size() >= 3 && after == quests + && std::find(after.begin(), after.end(), BBQuests::UnableToDetect) == after.end()){ + observed_panel = std::move(after); + } + return BBQRerollResult::Rerolled; + } + } + return BBQRerollResult::NotReplaced; +} + +std::optional> reroll_quest_slot( const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, const BBQOption& BBQ_OPTIONS, std::vector& quest_list, - uint8_t& eggs_hatched + size_t slot, + BBQPointsLedger* ledger ){ - std::vector quests_to_do; - bool rerolled = false; + ConsoleBBQRerollActions actions(info, stream, context, BBQ_OPTIONS, ledger, reroll_cost(quest_list[slot])); + std::optional> observed_panel; + switch (reroll_quest(stream.logger(), actions, quest_list, slot, observed_panel)){ + case BBQRerollResult::Rerolled: + return observed_panel; + case BBQRerollResult::PanelNotOpened: + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "Unable to open the quest panel to reroll a quest.", + stream + ); + case BBQRerollResult::MenuNotFound: + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::SEND_ERROR_REPORT, + "Unable to open the reroll menu for quest " + std::to_string(slot + 1) + ". No BP was spent.", + stream + ); + case BBQRerollResult::NotReplaced: + //Most likely out of BP, which is not a program error. + OperationFailedExceptionWithScreenshot::fire( + ErrorReportMode::NO_ERROR_REPORT, + "Quest " + std::to_string(slot + 1) + " was not replaced after rerolling it. Check that there is enough BP.", + stream + ); + } + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Invalid enum."); +} + +int reroll_cost(BBQuests quest){ + return red_quests.contains(quest) ? 50 : 10; +} + +BBQuestPlan plan_quests( + Logger& logger, + const BBQOption& BBQ_OPTIONS, + const std::vector& quest_list, + uint8_t eggs_hatched, + std::optional bp +){ + BBQuestPlan plan; std::vector> exclusions_table = BBQ_OPTIONS.QUEST_EXCLUSIONS.copy_snapshot(); - int questpos = 0; - stream.log("Processing quests."); - //Put all do-able quests into a different list - for (auto n : quest_list){ - if (not_possible_quests.contains(n)){ - stream.log("Quest not possible"); - }else{ - //Check eggs remaining. - if (n == BBQuests::hatch_egg && eggs_hatched >= BBQ_OPTIONS.NUM_EGGS){ - stream.log("Out of eggs! Quest not possible."); - - switch (BBQ_OPTIONS.OUT_OF_EGGS){ - case BBQOption::OOEggs::Reroll: - { - stream.log("Reroll selected. Rerolling Egg quest. New quest will be run in the next batch of quests."); - //stream.log("Warning: This does not handle/check being out of BP!", COLOR_RED); - - WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 400ms, 160ms); - pbf_wait(context, 1600ms); - context.wait_for_all_requests(); - } - }, - {{ right_panel }} - ); - if (result == 0){ - stream.log("Found quest panel."); - } - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_A, 160ms, 400ms); - pbf_press_button(context, BUTTON_A, 160ms, 400ms); - pbf_wait(context, 800ms); - context.wait_for_all_requests(); + //Quests not possible and not in the table, in panel order. Rerolled below if BP allows. + std::vector not_possible_slots; - rerolled = true; - press_Bs_to_back_to_overworld(info, stream, context); + logger.log("Processing quests."); + for (size_t slot = 0; slot < quest_list.size(); slot++){ + const BBQuests n = quest_list[slot]; + if (n == BBQuests::UnableToDetect){ + logger.log("Quest not detected."); + continue; + } + //Check eggs remaining. + if (n == BBQuests::hatch_egg && eggs_hatched >= BBQ_OPTIONS.NUM_EGGS){ + logger.log("Out of eggs! Quest not possible."); + plan_out_of_eggs(logger, BBQ_OPTIONS, slot, plan); + continue; + } + const bool possible = !not_possible_quests.contains(n); + if (plan_from_exclusions(logger, exclusions_table, n, slot, possible, plan)){ + continue; + } + if (!possible){ + logger.log("Quest not possible."); + not_possible_slots.push_back(slot); + continue; + } + logger.log("Quest not in inclusion/exclusions table. Adding to list."); + plan.to_do.push_back(n); + } - break; - } - case BBQOption::OOEggs::KeepGoing: - stream.log("Keep Going selected. Ignoring quest."); - break; - default: - //This case is handled in BBQSoloFarmer. - stream.log("OOEggs is Stop in process_quest_list()."); - OperationFailedExceptionWithScreenshot::fire( - ErrorReportMode::SEND_ERROR_REPORT, - "OOEggs is Stop in process_quest_list().", - stream - ); - break; - } - }else{ - bool quest_in_table = false; - for (const std::unique_ptr& row : exclusions_table){ - if(n == row->quest){ - stream.log("Quest found in inclusions/exclusions table."); - quest_in_table = true; - - WhiteButtonWatcher rp2(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result2; - switch (row->action){ - case BBQAction::run: - stream.log("Run selected. Adding quest to list."); - quests_to_do.push_back(n); - break; - case BBQAction::reroll: - stream.log("Reroll selected. Rerolling quest. New quest will be run in the next batch of quests."); - result2 = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 400ms, 160ms); - pbf_wait(context, 1600ms); - context.wait_for_all_requests(); - } - }, - {{ rp2 }} - ); - if (result2 == 0){ - stream.log("Found quest panel."); - } - context.wait_for_all_requests(); - - //Move cursor down to quest - for (int i = 0; i < questpos; i++){ - pbf_press_dpad(context, DPAD_DOWN, 160ms, 160ms); - pbf_wait(context, 800ms); - context.wait_for_all_requests(); - } - - //Reroll - pbf_press_button(context, BUTTON_A, 160ms, 400ms); - pbf_press_button(context, BUTTON_A, 160ms, 400ms); - pbf_wait(context, 800ms); - context.wait_for_all_requests(); - - //Prevent error/rerolling again at the end (allows program to read the rerolled quests) - rerolled = true; - - press_Bs_to_back_to_overworld(info, stream, context); - break; - case BBQAction::skip: - stream.log("Skip selected. Skipping quest."); - break; - } - } - } - if(!quest_in_table){ - stream.log("Quest not in inclusion/exclusions table. Adding to list."); - quests_to_do.push_back(n); - } + if (plan.to_do.empty()){ + //Nothing else to do: a quest not possible only changes by rerolling it. + for (size_t slot : not_possible_slots){ + logger.log("No possible quests! Rerolling quest " + std::to_string(slot + 1) + ", which is not possible."); + plan.reroll_slots.push_back(slot); + } + }else{ + //Left on the panel, a quest not possible holds a slot until something else is rerolled. + //A red quest costs 50 BP to reroll instead of 10, but pays 100-150 BP and keeps the + //next red quest from appearing, so it is rerolled too. Without the BP for it, it is + //skipped and the doable quests run, rather than stopping the program on a reroll + //that does not happen. + int budget = bp.value_or(0); + for (size_t slot : plan.reroll_slots){ + budget -= reroll_cost(quest_list[slot]); + } + for (size_t slot : not_possible_slots){ + const int cost = reroll_cost(quest_list[slot]); + if (!bp || budget < cost){ + logger.log( + "Quest " + std::to_string(slot + 1) + " not possible, but BP (" + + (bp ? std::to_string(*bp) : "unknown") + ") does not cover its " + + std::to_string(cost) + " BP reroll. Skipping it." + ); + continue; } + logger.log("Quest " + std::to_string(slot + 1) + " not possible. Rerolling quest. New quest will be run in the next batch of quests."); + budget -= cost; + plan.reroll_slots.push_back(slot); } - questpos++; } - + std::sort(plan.reroll_slots.begin(), plan.reroll_slots.end()); + //Check that quests_to_do is not empty (after completing all quests on the list, be sure to erase it. //Lag might be a problem in multi - look into making slots like menu-left navigation - if (!rerolled && quests_to_do.size() == 0){ - stream.log("No possible quests! Rerolling all quests."); + if (plan.reroll_slots.empty() && plan.to_do.empty()){ + plan.reroll_all = true; + } + return plan; +} - //Open quest panel and reroll all quests. - //This does not handle out of BP. - WhiteButtonWatcher panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 400ms, 160ms); - pbf_wait(context, 1600ms); - context.wait_for_all_requests(); - } - }, - {{ panel }} - ); - if (result == 0){ - stream.log("Found quest panel."); +BBQuestBatch process_quest_list( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + const std::vector& quest_list, + uint8_t eggs_hatched, + BBQPointsLedger* ledger +){ + //Read BP only when a quest not possible may be rerolled while others are doable. + std::optional bp; + if (std::any_of(quest_list.begin(), quest_list.end(), [](BBQuests quest){ + return quest != BBQuests::UnableToDetect && not_possible_quests.contains(quest); + })){ + const int read = read_BP(info, stream, context); + if (ledger != nullptr){ + ledger->record(read, current_time()); } - context.wait_for_all_requests(); - - for (string::size_type i = 0; i < quest_list.size(); i++){ - pbf_press_button(context, BUTTON_A, 160ms, 400ms); - pbf_press_button(context, BUTTON_A, 160ms, 400ms); //Yes. - pbf_wait(context, 800ms); - context.wait_for_all_requests(); - pbf_press_dpad(context, DPAD_DOWN, 160ms, 160ms); - pbf_wait(context, 800ms); - context.wait_for_all_requests(); + if (read >= 0){ + bp = read; } - //Close quest panel - mash b - press_Bs_to_back_to_overworld(info, stream, context); + stream.log("BP: " + (bp ? std::to_string(*bp) : "unable to read")); } + BBQuestPlan plan = plan_quests(stream.logger(), BBQ_OPTIONS, quest_list, eggs_hatched, bp); + + //Each reroll updates the panel the next one checks against. + std::vector panel = quest_list; + std::optional> observed_panel; + for (size_t slot : plan.reroll_slots){ + observed_panel = reroll_quest_slot(info, stream, context, BBQ_OPTIONS, panel, slot, ledger); + } + if (plan.reroll_all){ + stream.log("No possible quests! Rerolling all quests."); + reroll_all_slots(info, stream, context, quest_list, ledger); + } + + //Disabled since 2025-05, when the exclusions table gained its reroll action. Before that, + //nothing doable stopped the program here, because it usually meant the game language + //option did not match the game and no quest could be read. Now all quests are rerolled + //above instead, which also covers a panel of only excluded quests. /* - if (!rerolled && quests_to_do.size() == 0){ + if (plan.reroll_all){ OperationFailedExceptionWithScreenshot::fire( ErrorReportMode::SEND_ERROR_REPORT, "No possible quests! Check language selection.", @@ -303,7 +540,12 @@ std::vector process_quest_list( ); } */ - return quests_to_do; + //A mutation invalidates queued work, even when other quests remain runnable. + //A complete replacement observation can seed the next selection instead. + if (!plan.reroll_slots.empty() || plan.reroll_all){ + return {{}, std::move(observed_panel)}; + } + return {std::move(plan.to_do), std::nullopt}; } bool process_and_do_quest( @@ -311,12 +553,17 @@ bool process_and_do_quest( ConsoleHandle& console, ProControllerContext& context, BBQOption& BBQ_OPTIONS, BBQuests current_quest, - uint8_t& eggs_hatched + uint8_t& eggs_hatched, + std::vector* panel_after ){ bool quest_completed = false; int quest_attempts = 0; while (!quest_completed){ + BBQAttemptLog attempt_log( + console.logger(), /*quest=*/current_quest, + /*attempt=*/quest_attempts + 1, /*limit=*/static_cast(BBQ_OPTIONS.NUM_RETRIES) + 1 + ); switch (current_quest){ case BBQuests::make_tm: quest_make_tm(env.program_info(), console, context); @@ -415,13 +662,16 @@ bool process_and_do_quest( break; } + attempt_log.route_return(); //Validate quest was completed by checking list + console.log("Reading quest panel after attempt."); std::vector quest_list = read_quests(env.program_info(), console, context, BBQ_OPTIONS); + if (panel_after){ + *panel_after = quest_list; + } if (std::find(quest_list.begin(), quest_list.end(), current_quest) != quest_list.end()){ - console.log("Current quest exists on list. Quest did not complete."); quest_attempts++; }else{ - console.log("Current quest was not found. Quest completed!"); if (current_quest == BBQuests::hatch_egg){ eggs_hatched++; console.log("Eggs hatched: " + std::to_string(eggs_hatched)); @@ -430,8 +680,12 @@ bool process_and_do_quest( quest_completed = true; } + record_bbq_attempt_result( + console, attempt_log, current_quest, + quest_completed ? BBQAttemptOutcome::Completed : BBQAttemptOutcome::StillOnBoard + ); if (quest_attempts > BBQ_OPTIONS.NUM_RETRIES){ - console.log("Failed to complete a quest multiple times. Skipping it for now.", COLOR_RED); + BBQLogger(console.logger()).retry_exhausted(current_quest); break; } } @@ -981,6 +1235,43 @@ void quest_wash_pokemon(const ProgramInfo& info, VideoStream& stream, ProControl context.wait_for_all_requests(); } +namespace{ + +//Look through the current box for an egg, from the box system. Leaves the cursor on the egg and +//returns its slot, or returns false if the box has none. +bool find_egg_in_box( + const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, + uint8_t& row, uint8_t& col +){ + BoxCurrentEggDetector egg_detector; + SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); + for (row = 0; row < 5; row++){ + for (uint8_t j_col = 0; j_col < 6; j_col++){ + col = (row % 2 == 0 ? j_col : 5 - j_col); + move_box_cursor(info, console, context, BoxCursorLocation::SLOTS, row, col); + context.wait_for_all_requests(); + auto snapshot = console.video().snapshot(); + if (sth_in_box_detector.detect(snapshot) && egg_detector.detect(snapshot)){ + console.log("Found egg."); + return true; + } + } + } + return false; +} + +} + +bool box_has_egg(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context){ + enter_box_system_from_overworld(info, console, context); + context.wait_for(std::chrono::milliseconds(400)); + uint8_t row = 0; + uint8_t col = 0; + const bool found = find_egg_in_box(info, console, context, row, col); + leave_box_system_to_overworld(info, console, context); + return found; +} + void quest_hatch_egg( ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, @@ -1013,30 +1304,15 @@ void quest_hatch_egg( context.wait_for(std::chrono::milliseconds(400)); //move_to_left_box(context); - BoxCurrentEggDetector egg_detector; - SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); - bool egg_found = false; uint8_t row = 0; uint8_t col = 0; - for ( ; row < 5; row++){ - for (uint8_t j_col = 0; j_col < 6; j_col++){ - col = (row % 2 == 0 ? j_col : 5 - j_col); - move_box_cursor(env.program_info(), console, context, BoxCursorLocation::SLOTS, row, col); - context.wait_for_all_requests(); - auto snapshot = console.video().snapshot(); - if (sth_in_box_detector.detect(snapshot) && egg_detector.detect(snapshot)){ - console.log("Found egg."); - egg_found = true; - break; - } - } - if (egg_found){ - break; - } - } - - if (!egg_found){ + if (!find_egg_in_box(env.program_info(), console, context, row, col)){ + //Leave the box and go back, so the quest fails instead of leaving the game in the box. console.log("No egg found during egg hatching quest!", COLOR_RED); + leave_box_system_to_overworld(env.program_info(), console, context); + pbf_press_button(context, BUTTON_PLUS, 160ms, 400ms); + return_to_plaza(env.program_info(), console, context); + context.wait_for_all_requests(); }else{ swap_two_box_slots(env.program_info(), console, context, BoxCursorLocation::SLOTS, row, col, diff --git a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h index 21ad16aa71..e5f964f79c 100644 --- a/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h +++ b/SerialPrograms/Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h @@ -7,11 +7,13 @@ #ifndef PokemonAutomation_PokemonSV_BlueberryQuests_H #define PokemonAutomation_PokemonSV_BlueberryQuests_H +#include #include #include "NintendoSwitch/Controllers/Procon/NintendoSwitch_ProController.h" #include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" #include "VideoGames/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" #include "VideoGames/PokemonSV/Options/PokemonSV_BBQOption.h" +#include "PokemonSV_BBQPointsLedger.h" namespace PokemonAutomation{ struct ProgramInfo; @@ -51,29 +53,128 @@ int read_BP(const ProgramInfo& info, VideoStream& stream, ProControllerContext& //Open the quest panel and read in the current quests. //Currently only supports singleplayer. //For multiplayer, we will want keep track of which quest are gold/red and scroll cursor down until all of the current player's blue quests are in. +//If BP is not null, also read the BP balance from the same screenshot (-1 on OCR failure). std::vector read_quests( const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS + const BBQOption& BBQ_OPTIONS, + int* BP = nullptr +); + +//What to do with the quests read from the panel. Slot 0 is the top quest on the panel. +struct BBQuestPlan{ + std::vector to_do; //Quests to attempt, in panel order. + std::vector reroll_slots; //Slots to reroll, in panel order. + bool reroll_all = false; //Nothing to do and nothing rerolled: reroll every slot. +}; +//BP it costs to reroll one quest: 50 for a red quest, 10 for a blue one. +int reroll_cost(BBQuests quest); +//Decide what to do with each quest from the options alone, without touching the game, so +//the decision can be tested. Quests not possible are never run. Those not in the exclusions +//table are rerolled, red or blue, so they do not hold a slot, as long as BP (the balance +//read from the panel, if any) still covers their cost after the other planned rerolls; the +//rest are skipped, and the doable quests run. A table row for one decides instead. +//Out-of-egg hatch quests and quests set to reroll in the exclusions table are rerolled. A +//quest with several table rows gets the action of each row, in table order. With nothing to +//do, every quest not possible and not in the table is rerolled whatever the BP, or else +//every quest. +BBQuestPlan plan_quests( + Logger& logger, + const BBQOption& BBQ_OPTIONS, + const std::vector& quest_list, + uint8_t eggs_hatched, + std::optional bp +); + +//Work selected from a panel, or a complete observed panel to replan after a reroll. +//The observation is consumed once, before any further game actions. +struct BBQuestBatch{ + std::vector to_do; + std::optional> observed_panel; +}; + +//The steps of rerolling one quest on the quest panel. They are injected so that the reroll +//(which quest it pays for, when it gives up) runs in tests without a Switch. +class BBQRerollActions{ +public: + virtual ~BBQRerollActions() = default; + + //Open the quest panel from the overworld. Returns false if it did not open. + virtual bool open_panel() = 0; + + //Press A on the quest under the cursor, which opens its reroll menu. Returns the slot of + //the quest the menu opened next to, or nothing if no menu was seen. + virtual std::optional open_reroll_menu() = 0; + + //Close the reroll menu without rerolling. + virtual void close_reroll_menu() = 0; + + //Move the cursor down this many slots, or up if negative. + virtual void move_cursor(int slots) = 0; + + //Choose to reroll in the open menu. This spends BP. + virtual void confirm_reroll() = 0; + + //Close the quest panel and return to the overworld. + virtual void close_panel() = 0; + + //Open the quest panel and read the quests on it, as read_quests() does. + virtual std::vector read_quests() = 0; +}; + +enum class BBQRerollResult{ + Rerolled, //The quest in the slot was replaced. + PanelNotOpened, //Nothing was spent. + MenuNotFound, //Nothing was spent. + NotReplaced, //The reroll was confirmed, but the slot still shows the same quest. +}; + +//Reroll the quest in `slot` of `quests`, the quests last read from the panel. Only pays once +//the reroll menu is open next to that slot, then reads the panel again to check the quest was +//replaced. On Rerolled, `quests[slot]` is updated. observed_panel is populated +//only when every slot is known and no other slot changed, so scheduling can +//reuse it. A 3-slot read is only reused when `quests` had 3 slots. +BBQRerollResult reroll_quest( + Logger& logger, + BBQRerollActions& actions, + std::vector& quests, + size_t slot, + std::optional>& observed_panel +); + +//Reroll the quest in `slot` of `quests` on the console, with reroll_quest(). Stops the program +//if the reroll fails. Returns the observed panel when reusable. If ledger is not null, it records +//the BP of each panel read and what the reroll should cost. +std::optional> reroll_quest_slot( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + std::vector& quests, + size_t slot, + BBQPointsLedger* ledger = nullptr ); //Determine which quests are possible and which quests are not. (ex. no eggs, reroll egg hatcher.) //Quests not possible are removed from the list. If the list is empty, then reroll all items. -std::vector process_quest_list( +//If ledger is not null, it records every BP read here and what each reroll should cost. +BBQuestBatch process_quest_list( const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, const BBQOption& BBQ_OPTIONS, - std::vector& quest_list, - uint8_t& eggs_hatched + const std::vector& quest_list, + uint8_t eggs_hatched, + BBQPointsLedger* ledger = nullptr ); //Take the current quest and calls the function to do it, then checks the quest was successful. Returns true if so. +//If panel_after is given, it receives the quest panel read that checked the last attempt. bool process_and_do_quest( ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, BBQOption& BBQ_OPTIONS, BBQuests current_quest, - uint8_t& eggs_hatched + uint8_t& eggs_hatched, + std::vector* panel_after = nullptr ); //Iterate through TMs until a craftable one is found. Make the TM and return to position. @@ -129,6 +230,9 @@ void quest_wash_pokemon( VideoStream& stream, ProControllerContext& context ); +//Open the box system from the overworld and check that the current box has an egg. +bool box_has_egg(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context); + //Withdraw and hatch an egg void quest_hatch_egg( ProgramEnvironment& env, diff --git a/SerialPrograms/cmake/SourceFiles.cmake b/SerialPrograms/cmake/SourceFiles.cmake index 1603b71bc5..768bf71874 100644 --- a/SerialPrograms/cmake/SourceFiles.cmake +++ b/SerialPrograms/cmake/SourceFiles.cmake @@ -2670,6 +2670,16 @@ file(GLOB LIBRARY_SOURCES Source/VideoGames/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.cpp Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.cpp + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger.h + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.cpp + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQLogger_Tests.h + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.cpp + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQPointsLedger.h + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.cpp + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot.h + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.cpp + Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSnapshot_Tests.h Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h Source/VideoGames/PokemonSV/Programs/Farming/PokemonSV_BBQTests.cpp