mirror of
https://github.com/portapack-mayhem/mayhem-firmware.git
synced 2026-09-14 02:29:29 +00:00
Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0eb03373b1 | |||
| d5ea0f0369 | |||
| 22cc311447 | |||
| 4fbba205ad | |||
| 7b91103118 |
@@ -57,6 +57,95 @@ std::string pad_string_with_spaces(int snakes) {
|
||||
return paddedStr;
|
||||
}
|
||||
|
||||
struct GainEntry {
|
||||
uint8_t lna;
|
||||
uint8_t vga;
|
||||
uint8_t gain;
|
||||
};
|
||||
|
||||
// Only LNA with VGA 0-4 is tested to be accurate. Max zeroized gain tested to be 16dBm.
|
||||
// Beyond that it is hard to tell distance to transmitting device.
|
||||
// Test was conducted within a few inches of the device.
|
||||
// Device was transmitting at 0dBm.
|
||||
constexpr GainEntry gain_table[] =
|
||||
{
|
||||
{40, 0, 19},
|
||||
{32, 0, 18},
|
||||
{24, 0, 15},
|
||||
{16, 0, 8},
|
||||
{8, 0, 2},
|
||||
{0, 0, 0},
|
||||
{40, 2, 20},
|
||||
{32, 2, 22},
|
||||
{24, 2, 14},
|
||||
{16, 2, 8},
|
||||
{8, 2, 2},
|
||||
{0, 2, 0},
|
||||
{40, 4, 21},
|
||||
{32, 4, 22},
|
||||
{24, 4, 15},
|
||||
{16, 4, 10},
|
||||
{8, 4, 3},
|
||||
{0, 4, 0},
|
||||
{40, 6, 26},
|
||||
{32, 6, 22},
|
||||
{24, 6, 15},
|
||||
{16, 6, 10},
|
||||
{8, 6, 4},
|
||||
{0, 6, 0},
|
||||
{40, 8, 26},
|
||||
{32, 8, 26},
|
||||
{24, 8, 18},
|
||||
{16, 8, 12},
|
||||
{8, 8, 6},
|
||||
{0, 8, 1},
|
||||
{40, 10, 26},
|
||||
{32, 10, 26},
|
||||
{24, 10, 20},
|
||||
{16, 10, 15},
|
||||
{8, 10, 8},
|
||||
{0, 10, 3},
|
||||
{40, 12, 26},
|
||||
{32, 12, 26},
|
||||
{24, 12, 23},
|
||||
{16, 12, 17},
|
||||
{8, 12, 10},
|
||||
{0, 12, 4},
|
||||
{40, 14, 26},
|
||||
{32, 14, 26},
|
||||
{24, 14, 25},
|
||||
{16, 14, 19},
|
||||
{8, 14, 12},
|
||||
{0, 14, 6},
|
||||
{40, 16, 26},
|
||||
{32, 16, 26},
|
||||
{24, 16, 26},
|
||||
{16, 16, 20},
|
||||
{8, 16, 13},
|
||||
{0, 16, 7},
|
||||
{40, 18, 26},
|
||||
{32, 18, 26},
|
||||
{24, 18, 26},
|
||||
{16, 18, 21},
|
||||
{8, 18, 14},
|
||||
{0, 18, 8},
|
||||
{40, 20, 26},
|
||||
{32, 20, 26},
|
||||
{24, 20, 26},
|
||||
{16, 20, 23},
|
||||
{8, 20, 16},
|
||||
{0, 20, 10},
|
||||
};
|
||||
|
||||
uint8_t get_total_gain(uint8_t lna, uint8_t vga) {
|
||||
for (const auto& entry : gain_table) {
|
||||
if (entry.lna == lna && entry.vga == vga)
|
||||
return entry.gain;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint64_t copy_mac_address_to_uint64(const uint8_t* macAddress) {
|
||||
uint64_t result = 0;
|
||||
|
||||
@@ -68,22 +157,6 @@ uint64_t copy_mac_address_to_uint64(const uint8_t* macAddress) {
|
||||
return result;
|
||||
}
|
||||
|
||||
void reverse_byte_array(uint8_t* arr, int length) {
|
||||
int start = 0;
|
||||
int end = length - 1;
|
||||
|
||||
while (start < end) {
|
||||
// Swap elements at start and end
|
||||
uint8_t temp = arr[start];
|
||||
arr[start] = arr[end];
|
||||
arr[end] = temp;
|
||||
|
||||
// Move the indices towards the center
|
||||
start++;
|
||||
end--;
|
||||
}
|
||||
}
|
||||
|
||||
MAC_VENDOR_STATUS lookup_mac_vendor_status(const uint8_t* mac_address, std::string& vendor_name) {
|
||||
static bool db_checked = false;
|
||||
static bool db_exists = false;
|
||||
@@ -128,6 +201,22 @@ std::string lookup_mac_vendor(const uint8_t* mac_address) {
|
||||
return vendor_name;
|
||||
}
|
||||
|
||||
void reverse_byte_array(uint8_t* arr, int length) {
|
||||
int start = 0;
|
||||
int end = length - 1;
|
||||
|
||||
while (start < end) {
|
||||
// Swap elements at start and end
|
||||
uint8_t temp = arr[start];
|
||||
arr[start] = arr[end];
|
||||
arr[end] = temp;
|
||||
|
||||
// Move the indices towards the center
|
||||
start++;
|
||||
end--;
|
||||
}
|
||||
}
|
||||
|
||||
namespace ui {
|
||||
|
||||
std::string pdu_type_to_string(ADV_PDU_TYPE type) {
|
||||
@@ -186,19 +275,26 @@ void RecentEntriesTable<BleRecentEntries>::draw(
|
||||
if (!entry.nameString.empty() && entry.include_name) {
|
||||
line = entry.nameString;
|
||||
|
||||
if (line.length() < 17) {
|
||||
line += pad_string_with_spaces(17 - line.length());
|
||||
if (line.length() < 10) {
|
||||
line += pad_string_with_spaces(10 - line.length());
|
||||
} else {
|
||||
line = truncate(line, 17);
|
||||
line = truncate(line, 10);
|
||||
}
|
||||
} else {
|
||||
line = to_string_mac_address(entry.packetData.macAddress, 6, false);
|
||||
}
|
||||
|
||||
std::string hitsStr;
|
||||
|
||||
if (!entry.informationString.empty()) {
|
||||
hitsStr = entry.informationString;
|
||||
} else {
|
||||
hitsStr = "Hits: " + to_string_dec_int(entry.numHits);
|
||||
}
|
||||
|
||||
// Pushing single digit values down right justified.
|
||||
std::string hitsStr = to_string_dec_int(entry.numHits);
|
||||
int hitsDigits = hitsStr.length();
|
||||
uint8_t hits_spacing = 8 - hitsDigits;
|
||||
uint8_t hits_spacing = 14 - hitsDigits;
|
||||
|
||||
// Pushing single digit values down right justified.
|
||||
std::string dbStr = to_string_dec_int(entry.dbValue);
|
||||
@@ -539,7 +635,6 @@ BLERxView::BLERxView(NavigationView& nav)
|
||||
logger = std::make_unique<BLELogger>();
|
||||
|
||||
check_log.on_select = [this](Checkbox&, bool v) {
|
||||
str_log = "";
|
||||
logging = v;
|
||||
|
||||
if (logger && logging)
|
||||
@@ -561,6 +656,7 @@ BLERxView::BLERxView(NavigationView& nav)
|
||||
|
||||
button_clear_list.on_select = [this](Button&) {
|
||||
recent.clear();
|
||||
recent_entries_view.set_dirty();
|
||||
};
|
||||
|
||||
button_switch.on_select = [&nav](Button&) {
|
||||
@@ -602,7 +698,10 @@ BLERxView::BLERxView(NavigationView& nav)
|
||||
|
||||
options_filter.on_change = [this](size_t index, int32_t v) {
|
||||
filter_index = (uint8_t)index;
|
||||
recent.clear();
|
||||
handle_filter_options(v);
|
||||
uniqueParsing = filter_index == 2 ? true : false;
|
||||
recent_entries_view.set_dirty();
|
||||
};
|
||||
|
||||
options_channel.set_selected_index(channel_index, true);
|
||||
@@ -775,10 +874,49 @@ bool BLERxView::saveFile(const std::filesystem::path& path) {
|
||||
}
|
||||
|
||||
void BLERxView::on_data(BlePacketData* packet) {
|
||||
if (!logging) {
|
||||
str_log = "";
|
||||
uint64_t macAddressEncoded = copy_mac_address_to_uint64(packet->macAddress);
|
||||
|
||||
// Start of Packet stuffing.
|
||||
// Masking off the top 2 bytes to avoid invalid keys.
|
||||
|
||||
BleRecentEntry tempEntry;
|
||||
|
||||
if (updateEntry(packet, tempEntry, (ADV_PDU_TYPE)packet->type)) {
|
||||
auto& entry = ::on_packet(recent, macAddressEncoded & 0xFFFFFFFFFFFF);
|
||||
|
||||
// Preserve exisisting data from entry.
|
||||
tempEntry.macAddress = macAddressEncoded;
|
||||
tempEntry.numHits = ++entry.numHits;
|
||||
|
||||
entry = tempEntry;
|
||||
|
||||
handle_filter_options(options_filter.selected_index());
|
||||
handle_entries_sort(options_sort.selected_index());
|
||||
|
||||
if (!searchList.empty()) {
|
||||
auto it = searchList.begin();
|
||||
|
||||
while (it != searchList.end()) {
|
||||
std::string searchStr = (std::string)*it;
|
||||
|
||||
if (entry.dataString.find(searchStr) != std::string::npos) {
|
||||
searchList.erase(it);
|
||||
found_count++;
|
||||
break;
|
||||
}
|
||||
|
||||
it++;
|
||||
}
|
||||
|
||||
text_found_count.set(to_string_dec_uint(found_count) + "/" + to_string_dec_uint(total_count));
|
||||
}
|
||||
}
|
||||
|
||||
log_ble_packet(packet);
|
||||
}
|
||||
|
||||
void BLERxView::log_ble_packet(BlePacketData* packet) {
|
||||
str_console = "";
|
||||
str_console += pdu_type_to_string((ADV_PDU_TYPE)packet->type);
|
||||
str_console += " Len:";
|
||||
str_console += to_string_dec_uint(packet->size);
|
||||
@@ -792,49 +930,14 @@ void BLERxView::on_data(BlePacketData* packet) {
|
||||
str_console += to_string_hex(packet->data[i], 2);
|
||||
}
|
||||
|
||||
uint64_t macAddressEncoded = copy_mac_address_to_uint64(packet->macAddress);
|
||||
|
||||
// Start of Packet stuffing.
|
||||
// Masking off the top 2 bytes to avoid invalid keys.
|
||||
auto& entry = ::on_packet(recent, macAddressEncoded & 0xFFFFFFFFFFFF);
|
||||
updateEntry(packet, entry, (ADV_PDU_TYPE)packet->type);
|
||||
|
||||
// Add entries if they meet the criteria.
|
||||
// auto value = filter;
|
||||
// resetFilteredEntries(recent, [&value](const BleRecentEntry& entry) {
|
||||
// return (entry.dataString.find(value) == std::string::npos) && (entry.nameString.find(value) == std::string::npos);
|
||||
// });
|
||||
handle_filter_options(options_filter.selected_index());
|
||||
|
||||
handle_entries_sort(options_sort.selected_index());
|
||||
|
||||
// Log at End of Packet.
|
||||
if (logger && logging) {
|
||||
logger->log_raw_data(str_console + "\r\n");
|
||||
logger->log_raw_data(str_console);
|
||||
}
|
||||
|
||||
if (serial_logging) {
|
||||
UsbSerialAsyncmsg::asyncmsg(str_console); // new line handled there, no need here.
|
||||
}
|
||||
str_console = "";
|
||||
|
||||
if (!searchList.empty()) {
|
||||
auto it = searchList.begin();
|
||||
|
||||
while (it != searchList.end()) {
|
||||
std::string searchStr = (std::string)*it;
|
||||
|
||||
if (entry.dataString.find(searchStr) != std::string::npos) {
|
||||
searchList.erase(it);
|
||||
found_count++;
|
||||
break;
|
||||
}
|
||||
|
||||
it++;
|
||||
}
|
||||
|
||||
text_found_count.set(to_string_dec_uint(found_count) + "/" + to_string_dec_uint(total_count));
|
||||
}
|
||||
}
|
||||
|
||||
void BLERxView::on_filter_change(std::string value) {
|
||||
@@ -979,16 +1082,18 @@ BLERxView::~BLERxView() {
|
||||
baseband::shutdown();
|
||||
}
|
||||
|
||||
void BLERxView::updateEntry(const BlePacketData* packet, BleRecentEntry& entry, ADV_PDU_TYPE pdu_type) {
|
||||
bool BLERxView::updateEntry(const BlePacketData* packet, BleRecentEntry& entry, ADV_PDU_TYPE pdu_type) {
|
||||
std::string data_string;
|
||||
|
||||
bool success = false;
|
||||
|
||||
int i;
|
||||
|
||||
for (i = 0; i < packet->dataLen; i++) {
|
||||
data_string += to_string_hex(packet->data[i], 2);
|
||||
}
|
||||
|
||||
entry.dbValue = packet->max_dB;
|
||||
entry.dbValue = 2 * (packet->max_dB - get_total_gain(receiver_model.lna(), receiver_model.vga()));
|
||||
entry.timestamp = to_string_timestamp(rtc_time::now());
|
||||
entry.dataString = data_string;
|
||||
|
||||
@@ -1004,7 +1109,6 @@ void BLERxView::updateEntry(const BlePacketData* packet, BleRecentEntry& entry,
|
||||
entry.packetData.macAddress[4] = packet->macAddress[4];
|
||||
entry.packetData.macAddress[5] = packet->macAddress[5];
|
||||
|
||||
entry.numHits++;
|
||||
entry.pduType = pdu_type;
|
||||
entry.channelNumber = channel_number;
|
||||
|
||||
@@ -1021,35 +1125,48 @@ void BLERxView::updateEntry(const BlePacketData* packet, BleRecentEntry& entry,
|
||||
entry.include_name = check_name.value();
|
||||
|
||||
// Only parse name for advertisment packets and empty name entries
|
||||
if ((pdu_type == ADV_IND || pdu_type == ADV_NONCONN_IND || pdu_type == SCAN_RSP || pdu_type == ADV_SCAN_IND) && entry.nameString.empty()) {
|
||||
ADV_PDU_PAYLOAD_TYPE_0_2_4_6* advertiseData = (ADV_PDU_PAYLOAD_TYPE_0_2_4_6*)entry.packetData.data;
|
||||
|
||||
uint8_t currentByte = 0;
|
||||
uint8_t length = 0;
|
||||
uint8_t type = 0;
|
||||
|
||||
std::string decoded_data;
|
||||
for (currentByte = 0; (currentByte < entry.packetData.dataLen);) {
|
||||
length = advertiseData->Data[currentByte++];
|
||||
type = advertiseData->Data[currentByte++];
|
||||
|
||||
// Subtract 1 because type is part of the length.
|
||||
for (int i = 0; i < length - 1; i++) {
|
||||
// parse the name of bluetooth device: 0x08->Shortened Local Name; 0x09->Complete Local Name
|
||||
if (type == 0x08 || type == 0x09) {
|
||||
decoded_data += (char)advertiseData->Data[currentByte];
|
||||
}
|
||||
currentByte++;
|
||||
}
|
||||
if (!decoded_data.empty()) {
|
||||
entry.nameString = std::move(decoded_data);
|
||||
break;
|
||||
}
|
||||
if (pdu_type == ADV_IND || pdu_type == ADV_NONCONN_IND) // || pdu_type == SCAN_RSP || pdu_type == ADV_SCAN_IND)
|
||||
{
|
||||
if (uniqueParsing) {
|
||||
// Add your unique beacon parsing function here.
|
||||
}
|
||||
|
||||
if (!success && !uniqueParsing) {
|
||||
success = parse_beacon_data(packet->data, packet->dataLen, entry.nameString, entry.informationString);
|
||||
}
|
||||
|
||||
} else if (pdu_type == ADV_DIRECT_IND || pdu_type == SCAN_REQ) {
|
||||
ADV_PDU_PAYLOAD_TYPE_1_3* directed_mac_data = (ADV_PDU_PAYLOAD_TYPE_1_3*)entry.packetData.data;
|
||||
reverse_byte_array(directed_mac_data->A1, 6);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
bool BLERxView::parse_beacon_data(const uint8_t* data, uint8_t length, std::string& nameString, std::string& informationString) {
|
||||
uint8_t currentByte, currentLength, currentType = 0;
|
||||
|
||||
for (currentByte = 0; currentByte < length;) {
|
||||
currentLength = data[currentByte++];
|
||||
currentType = data[currentByte++];
|
||||
|
||||
// Subtract 1 because type is part of the length.
|
||||
for (int i = 0; ((i < currentLength - 1) && (currentByte < length)); i++) {
|
||||
// parse the name of bluetooth device: 0x08->Shortened Local Name; 0x09->Complete Local Name
|
||||
if (currentType == 0x08 || currentType == 0x09) {
|
||||
nameString += (char)data[currentByte];
|
||||
}
|
||||
currentByte++;
|
||||
}
|
||||
}
|
||||
|
||||
if (nameString.empty()) {
|
||||
nameString = "None";
|
||||
}
|
||||
|
||||
informationString = "";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace ui */
|
||||
|
||||
@@ -84,7 +84,7 @@ typedef enum {
|
||||
struct BleRecentEntry {
|
||||
using Key = uint64_t;
|
||||
|
||||
static constexpr Key invalid_key = 0xffffffff;
|
||||
static constexpr Key invalid_key = 0xFFFFFFFFFFFF;
|
||||
|
||||
uint64_t macAddress;
|
||||
int dbValue;
|
||||
@@ -92,6 +92,7 @@ struct BleRecentEntry {
|
||||
std::string timestamp;
|
||||
std::string dataString;
|
||||
std::string nameString;
|
||||
std::string informationString;
|
||||
bool include_name;
|
||||
uint16_t numHits;
|
||||
ADV_PDU_TYPE pduType;
|
||||
@@ -111,6 +112,7 @@ struct BleRecentEntry {
|
||||
timestamp{},
|
||||
dataString{},
|
||||
nameString{},
|
||||
informationString{},
|
||||
include_name{},
|
||||
numHits{},
|
||||
pduType{},
|
||||
@@ -216,15 +218,18 @@ class BLERxView : public View {
|
||||
bool saveFile(const std::filesystem::path& path);
|
||||
std::unique_ptr<UsbSerialThread> usb_serial_thread{};
|
||||
void on_data(BlePacketData* packetData);
|
||||
void log_ble_packet(BlePacketData* packet);
|
||||
void on_filter_change(std::string value);
|
||||
void on_file_changed(const std::filesystem::path& new_file_path);
|
||||
void file_error();
|
||||
void on_timer();
|
||||
void handle_entries_sort(uint8_t index);
|
||||
void handle_filter_options(uint8_t index);
|
||||
void updateEntry(const BlePacketData* packet, BleRecentEntry& entry, ADV_PDU_TYPE pdu_type);
|
||||
bool updateEntry(const BlePacketData* packet, BleRecentEntry& entry, ADV_PDU_TYPE pdu_type);
|
||||
bool parse_beacon_data(const uint8_t* data, uint8_t length, std::string& nameString, std::string& informationString);
|
||||
|
||||
NavigationView& nav_;
|
||||
|
||||
RxRadioState radio_state_{
|
||||
2402000000 /* frequency */,
|
||||
4000000 /* bandwidth */,
|
||||
@@ -234,6 +239,7 @@ class BLERxView : public View {
|
||||
uint8_t channel_index{0};
|
||||
uint8_t sort_index{0};
|
||||
uint8_t filter_index{0};
|
||||
bool uniqueParsing = false;
|
||||
std::string filter{};
|
||||
bool logging{false};
|
||||
bool serial_logging{false};
|
||||
@@ -325,9 +331,10 @@ class BLERxView : public View {
|
||||
|
||||
OptionsField options_filter{
|
||||
{18 * 8 + 2, 2 * 8},
|
||||
4,
|
||||
7,
|
||||
{{"Data", 0},
|
||||
{"MAC", 1}}};
|
||||
{"MAC", 1},
|
||||
{"Unique", 2}}};
|
||||
|
||||
Checkbox check_log{
|
||||
{10 * 8, 4 * 8 + 2},
|
||||
@@ -380,9 +387,9 @@ class BLERxView : public View {
|
||||
BleRecentEntries tempList{};
|
||||
|
||||
const RecentEntriesColumns columns{{
|
||||
{"Mac Address", 17},
|
||||
{"Hits", 7},
|
||||
{"dB", 4},
|
||||
{"Name", 10},
|
||||
{"Information", 13},
|
||||
{"dBm", 4},
|
||||
}};
|
||||
|
||||
BleRecentEntriesView recent_entries_view{columns, recent};
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Blackjack Game for Portapack Mayhem
|
||||
* Ported / Enhanced / Graphically made awesome by RocketGod (https://betaskynet.com)
|
||||
* Based on BlackJack 83 for TI Calculator by Harper Maddox (was written in Assembly)
|
||||
*/
|
||||
|
||||
#include "ui.hpp"
|
||||
#include "ui_blackjack.hpp"
|
||||
#include "ui_navigation.hpp"
|
||||
#include "external_app.hpp"
|
||||
|
||||
namespace ui::external_app::blackjack {
|
||||
void initialize_app(ui::NavigationView& nav) {
|
||||
nav.push<BlackjackView>();
|
||||
}
|
||||
} // namespace ui::external_app::blackjack
|
||||
|
||||
extern "C" {
|
||||
|
||||
__attribute__((section(".external_app.app_blackjack.application_information"), used)) application_information_t _application_information_blackjack = {
|
||||
(uint8_t*)0x00000000,
|
||||
ui::external_app::blackjack::initialize_app,
|
||||
CURRENT_HEADER_VERSION,
|
||||
VERSION_MD5,
|
||||
|
||||
"Blackjack",
|
||||
{
|
||||
// Diamond icon 16x16
|
||||
0x00, 0x00, // ................
|
||||
0x80, 0x01, // .......##.......
|
||||
0xC0, 0x03, // ......####......
|
||||
0xE0, 0x07, // .....######.....
|
||||
0xF0, 0x0F, // ....########....
|
||||
0xF8, 0x1F, // ...##########...
|
||||
0xFC, 0x3F, // ..############..
|
||||
0xFE, 0x7F, // .##############.
|
||||
0xFE, 0x7F, // .##############.
|
||||
0xFC, 0x3F, // ..############..
|
||||
0xF8, 0x1F, // ...##########...
|
||||
0xF0, 0x0F, // ....########....
|
||||
0xE0, 0x07, // .....######.....
|
||||
0xC0, 0x03, // ......####......
|
||||
0x80, 0x01, // .......##.......
|
||||
0x00, 0x00, // ................
|
||||
},
|
||||
ui::Color::red().v, // Red color for diamonds
|
||||
app_location_t::GAMES,
|
||||
-1,
|
||||
|
||||
{0, 0, 0, 0},
|
||||
0x00000000,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,727 @@
|
||||
/*
|
||||
* Blackjack Game for Portapack Mayhem
|
||||
* Ported / Enhanced / Graphically made awesome by RocketGod (https://betaskynet.com)
|
||||
* Based on BlackJack 83 for TI Calculator by Harper Maddox (was written in Assembly)
|
||||
*/
|
||||
|
||||
#include "ui_blackjack.hpp"
|
||||
|
||||
namespace ui::external_app::blackjack {
|
||||
|
||||
// Global variables
|
||||
static BlackjackView* current_instance = nullptr;
|
||||
static Callback game_update_callback = nullptr;
|
||||
static uint32_t game_update_timeout = 0;
|
||||
static uint32_t game_update_counter = 0;
|
||||
static Painter painter;
|
||||
|
||||
void check_game_timer() {
|
||||
if (game_update_callback) {
|
||||
if (++game_update_counter >= game_update_timeout) {
|
||||
game_update_counter = 0;
|
||||
game_update_callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Ticker::attach(Callback func, double delay_sec) {
|
||||
game_update_callback = func;
|
||||
game_update_timeout = delay_sec * 60;
|
||||
}
|
||||
|
||||
void Ticker::detach() {
|
||||
game_update_callback = nullptr;
|
||||
}
|
||||
|
||||
void game_timer_check() {
|
||||
if (current_instance) {
|
||||
current_instance->update_game();
|
||||
}
|
||||
}
|
||||
|
||||
BlackjackView::BlackjackView(NavigationView& nav)
|
||||
: nav_{nav}, game_timer{} {
|
||||
add_children({&dummy});
|
||||
current_instance = this;
|
||||
game_timer.attach(&game_timer_check, 1.0 / 60.0);
|
||||
}
|
||||
|
||||
BlackjackView::~BlackjackView() {
|
||||
current_instance = nullptr;
|
||||
}
|
||||
|
||||
void BlackjackView::on_show() {
|
||||
draw_menu_static();
|
||||
}
|
||||
|
||||
void BlackjackView::paint(Painter& painter) {
|
||||
(void)painter;
|
||||
|
||||
if (!initialized) {
|
||||
initialized = true;
|
||||
std::srand(LPC_RTC->CTIME0);
|
||||
init_deck();
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::frame_sync() {
|
||||
check_game_timer();
|
||||
set_dirty();
|
||||
}
|
||||
|
||||
void BlackjackView::clear_screen() {
|
||||
painter.fill_rectangle({0, 0, 240, 320}, Color::black());
|
||||
}
|
||||
|
||||
void BlackjackView::init_deck() {
|
||||
// Initialize deck with card values 0-51
|
||||
// 0-12 = Spades (A-K), 13-25 = Hearts, 26-38 = Diamonds, 39-51 = Clubs
|
||||
for (int i = 0; i < 52; i++) {
|
||||
deck[i] = i;
|
||||
}
|
||||
shuffle_deck();
|
||||
}
|
||||
|
||||
void BlackjackView::shuffle_deck() {
|
||||
// Simple shuffle using random swaps
|
||||
for (int i = 51; i > 0; i--) {
|
||||
int j = rand() % (i + 1);
|
||||
uint8_t temp = deck[i];
|
||||
deck[i] = deck[j];
|
||||
deck[j] = temp;
|
||||
}
|
||||
deck_position = 0;
|
||||
}
|
||||
|
||||
uint8_t BlackjackView::draw_card() {
|
||||
if (deck_position >= 52) {
|
||||
shuffle_deck();
|
||||
}
|
||||
return deck[deck_position++];
|
||||
}
|
||||
|
||||
int BlackjackView::get_card_value(uint8_t card) {
|
||||
int value = (card % 13) + 1; // 1-13
|
||||
if (value > 10) value = 10; // Face cards worth 10
|
||||
return value;
|
||||
}
|
||||
|
||||
uint8_t BlackjackView::get_card_suit(uint8_t card) {
|
||||
return card / 13; // 0=Spades, 1=Hearts, 2=Diamonds, 3=Clubs
|
||||
}
|
||||
|
||||
std::string BlackjackView::get_card_string(uint8_t card) {
|
||||
int value = (card % 13) + 1;
|
||||
std::string result;
|
||||
|
||||
if (value == 1)
|
||||
result = "A";
|
||||
else if (value == 11)
|
||||
result = "J";
|
||||
else if (value == 12)
|
||||
result = "Q";
|
||||
else if (value == 13)
|
||||
result = "K";
|
||||
else if (value == 10)
|
||||
result = "10"; // Special case for 10
|
||||
else
|
||||
result = std::to_string(value);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int BlackjackView::calculate_hand_value(uint8_t* cards, uint8_t count) {
|
||||
int value = 0;
|
||||
int aces = 0;
|
||||
|
||||
for (uint8_t i = 0; i < count; i++) {
|
||||
int card_val = get_card_value(cards[i]);
|
||||
if (card_val == 1) {
|
||||
aces++;
|
||||
value += 1;
|
||||
} else {
|
||||
value += card_val;
|
||||
}
|
||||
}
|
||||
|
||||
// Convert aces from 1 to 11 if beneficial
|
||||
while (aces > 0 && value + 10 <= 21) {
|
||||
value += 10;
|
||||
aces--;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
void BlackjackView::deal_cards() {
|
||||
// Clear hands
|
||||
player_card_count = 0;
|
||||
dealer_card_count = 0;
|
||||
|
||||
// Deal initial cards
|
||||
player_cards[player_card_count++] = draw_card();
|
||||
dealer_cards[dealer_card_count++] = draw_card();
|
||||
player_cards[player_card_count++] = draw_card();
|
||||
dealer_cards[dealer_card_count++] = draw_card();
|
||||
|
||||
dealer_hidden = true;
|
||||
game_state = GameState::PLAYING;
|
||||
}
|
||||
|
||||
void BlackjackView::player_hit() {
|
||||
if (player_card_count < MAX_CARDS_IN_HAND) {
|
||||
player_cards[player_card_count++] = draw_card();
|
||||
|
||||
int value = calculate_hand_value(player_cards, player_card_count);
|
||||
if (value > 21) {
|
||||
// Bust!
|
||||
cash = (cash >= bet) ? cash - bet : 0;
|
||||
losses++;
|
||||
game_state = GameState::GAME_OVER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::player_stay() {
|
||||
dealer_hidden = false;
|
||||
game_state = GameState::DEALER_TURN;
|
||||
dealer_timer = 0;
|
||||
}
|
||||
|
||||
void BlackjackView::dealer_turn() {
|
||||
int dealer_value = calculate_hand_value(dealer_cards, dealer_card_count);
|
||||
|
||||
if (dealer_value < 17 && dealer_card_count < MAX_CARDS_IN_HAND) {
|
||||
dealer_cards[dealer_card_count++] = draw_card();
|
||||
} else {
|
||||
check_game_over();
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::check_game_over() {
|
||||
int player_value = calculate_hand_value(player_cards, player_card_count);
|
||||
int dealer_value = calculate_hand_value(dealer_cards, dealer_card_count);
|
||||
|
||||
if (player_value > 21) {
|
||||
// Player bust (already handled)
|
||||
} else if (dealer_value > 21) {
|
||||
// Dealer bust - player wins
|
||||
cash += bet;
|
||||
wins++;
|
||||
} else if (player_value > dealer_value) {
|
||||
// Player wins
|
||||
cash += bet;
|
||||
wins++;
|
||||
} else if (player_value < dealer_value) {
|
||||
// Dealer wins
|
||||
cash = (cash >= bet) ? cash - bet : 0;
|
||||
losses++;
|
||||
}
|
||||
// Else it's a tie - no money changes hands
|
||||
|
||||
if (cash > high_score) {
|
||||
high_score = cash;
|
||||
}
|
||||
|
||||
game_state = GameState::GAME_OVER;
|
||||
}
|
||||
|
||||
void BlackjackView::update_game() {
|
||||
switch (game_state) {
|
||||
case GameState::MENU:
|
||||
draw_menu();
|
||||
break;
|
||||
|
||||
case GameState::BETTING:
|
||||
draw_betting();
|
||||
break;
|
||||
|
||||
case GameState::PLAYING:
|
||||
draw_game();
|
||||
break;
|
||||
|
||||
case GameState::DEALER_TURN:
|
||||
if (++dealer_timer >= 60) { // 1 second delay
|
||||
dealer_timer = 0;
|
||||
dealer_turn();
|
||||
}
|
||||
draw_game();
|
||||
break;
|
||||
|
||||
case GameState::GAME_OVER:
|
||||
draw_game();
|
||||
break;
|
||||
|
||||
case GameState::STATS:
|
||||
draw_stats();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::draw_menu_static() {
|
||||
clear_screen();
|
||||
|
||||
auto style_title = *ui::Theme::getInstance()->fg_green;
|
||||
auto style_text = *ui::Theme::getInstance()->fg_light;
|
||||
auto style_rules = *ui::Theme::getInstance()->fg_cyan;
|
||||
|
||||
painter.draw_string({84, 20}, style_title, "BLACKJACK");
|
||||
|
||||
// Draw rules
|
||||
painter.draw_string({70, 55}, style_rules, "-- RULES --");
|
||||
painter.draw_string({61, 75}, style_text, "Get close to 21");
|
||||
painter.draw_string({61, 90}, style_text, "without going over");
|
||||
painter.draw_string({61, 110}, style_text, "Dealer hits on 16");
|
||||
painter.draw_string({61, 125}, style_text, "Dealer stays on 17");
|
||||
painter.draw_string({61, 145}, style_text, "Blackjack pays 1:1");
|
||||
|
||||
// Controls
|
||||
painter.draw_string({65, 175}, style_rules, "-- CONTROLS --");
|
||||
painter.draw_string({61, 195}, style_text, "SELECT: Start/Hit");
|
||||
painter.draw_string({61, 210}, style_text, "LEFT: Stats");
|
||||
painter.draw_string({61, 225}, style_text, "RIGHT: Exit/Stay");
|
||||
|
||||
// Draw high score
|
||||
painter.draw_string({61, 250}, style_text, "High Score: $" + std::to_string(high_score));
|
||||
}
|
||||
|
||||
void BlackjackView::draw_menu() {
|
||||
// Only handle the flashing text animation
|
||||
if (++blink_counter >= 30) {
|
||||
blink_counter = 0;
|
||||
blink_state = !blink_state;
|
||||
|
||||
if (blink_state) {
|
||||
auto style = *ui::Theme::getInstance()->fg_yellow;
|
||||
painter.draw_string({55, 280}, style, "* PRESS SELECT *");
|
||||
} else {
|
||||
// Clear just the text area
|
||||
painter.fill_rectangle({55, 278, 130, 20}, Color::black());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::draw_stats() {
|
||||
clear_screen();
|
||||
|
||||
auto style_title = *ui::Theme::getInstance()->fg_green;
|
||||
auto style_text = *ui::Theme::getInstance()->fg_light;
|
||||
auto style_value = *ui::Theme::getInstance()->fg_yellow;
|
||||
|
||||
painter.draw_string({75, 30}, style_title, "STATISTICS");
|
||||
|
||||
painter.draw_string({30, 80}, style_text, "Wins:");
|
||||
painter.draw_string({150, 80}, style_value, std::to_string(wins));
|
||||
|
||||
painter.draw_string({30, 100}, style_text, "Losses:");
|
||||
painter.draw_string({150, 100}, style_value, std::to_string(losses));
|
||||
|
||||
// Win percentage
|
||||
uint32_t total = wins + losses;
|
||||
if (total > 0) {
|
||||
uint32_t win_pct = (wins * 100) / total;
|
||||
painter.draw_string({30, 120}, style_text, "Win %:");
|
||||
painter.draw_string({150, 120}, style_value, std::to_string(win_pct) + "%");
|
||||
}
|
||||
|
||||
painter.draw_string({30, 160}, style_text, "High Score:");
|
||||
painter.draw_string({150, 160}, style_value, "$" + std::to_string(high_score));
|
||||
|
||||
painter.draw_string({30, 180}, style_text, "Cash:");
|
||||
painter.draw_string({150, 180}, style_value, "$" + std::to_string(cash));
|
||||
|
||||
painter.draw_string({40, 250}, style_text, "SELECT: Back");
|
||||
}
|
||||
|
||||
void BlackjackView::draw_betting() {
|
||||
static uint32_t last_bet = 0;
|
||||
static bool betting_drawn = false;
|
||||
|
||||
if (!betting_drawn) {
|
||||
clear_screen();
|
||||
|
||||
auto style_title = *ui::Theme::getInstance()->fg_green;
|
||||
auto style_text = *ui::Theme::getInstance()->fg_light;
|
||||
|
||||
painter.draw_string({70, 40}, style_title, "PLACE BET");
|
||||
painter.draw_string({30, 80}, style_text, "Cash: $" + std::to_string(cash));
|
||||
|
||||
painter.draw_string({30, 140}, style_text, "ENCODER: +/- $10");
|
||||
painter.draw_string({30, 160}, style_text, "SELECT: Deal");
|
||||
|
||||
betting_drawn = true;
|
||||
last_bet = 0;
|
||||
}
|
||||
|
||||
// Update bet display
|
||||
if (bet != last_bet) {
|
||||
painter.fill_rectangle({30, 110, 150, 20}, Color::black());
|
||||
painter.draw_string({30, 110}, *ui::Theme::getInstance()->fg_yellow, "Bet: $" + std::to_string(bet));
|
||||
last_bet = bet;
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::draw_game() {
|
||||
static int last_player_count = -1;
|
||||
static int last_dealer_count = -1;
|
||||
static GameState last_game_state = GameState::MENU;
|
||||
static uint32_t last_bet = 0;
|
||||
|
||||
// Clear and redraw if hands changed or game state changed
|
||||
if (player_card_count != last_player_count || dealer_card_count != last_dealer_count || game_state != last_game_state) {
|
||||
clear_screen();
|
||||
|
||||
auto style = *ui::Theme::getInstance()->fg_green;
|
||||
painter.draw_string({10, 10}, style, "Cash: $" + std::to_string(cash));
|
||||
painter.draw_string({140, 10}, style, "Bet: $" + std::to_string(bet));
|
||||
|
||||
// Draw dealer hand with value next to label
|
||||
auto style_value = *ui::Theme::getInstance()->fg_yellow;
|
||||
painter.draw_string({10, 45}, *ui::Theme::getInstance()->fg_light, "Dealer:");
|
||||
if (!dealer_hidden || game_state == GameState::GAME_OVER) {
|
||||
int dealer_value = calculate_hand_value(dealer_cards, dealer_card_count);
|
||||
painter.draw_string({70, 45}, style_value, "(" + std::to_string(dealer_value) + ")");
|
||||
}
|
||||
draw_hand(10, 65, dealer_cards, dealer_card_count, true);
|
||||
|
||||
// Draw player hand with value next to label
|
||||
painter.draw_string({10, 165}, *ui::Theme::getInstance()->fg_light, "You:");
|
||||
int player_value = calculate_hand_value(player_cards, player_card_count);
|
||||
painter.draw_string({50, 165}, style_value, "(" + std::to_string(player_value) + ")");
|
||||
draw_hand(10, 185, player_cards, player_card_count, false);
|
||||
|
||||
// Draw controls or result
|
||||
if (game_state == GameState::PLAYING) {
|
||||
auto style_text = *ui::Theme::getInstance()->fg_light;
|
||||
painter.draw_string({30, 290}, style_text, "SELECT: Hit");
|
||||
painter.draw_string({130, 290}, style_text, "RIGHT: Stay");
|
||||
} else if (game_state == GameState::GAME_OVER) {
|
||||
const Style* style_result = ui::Theme::getInstance()->fg_yellow;
|
||||
std::string result;
|
||||
|
||||
if (player_value > 21) {
|
||||
result = "BUST! You Lose";
|
||||
style_result = ui::Theme::getInstance()->fg_red;
|
||||
} else if (calculate_hand_value(dealer_cards, dealer_card_count) > 21) {
|
||||
result = "Dealer Bust! Win!";
|
||||
style_result = ui::Theme::getInstance()->fg_green;
|
||||
} else if (player_value > calculate_hand_value(dealer_cards, dealer_card_count)) {
|
||||
result = "You Win!";
|
||||
style_result = ui::Theme::getInstance()->fg_green;
|
||||
} else if (player_value < calculate_hand_value(dealer_cards, dealer_card_count)) {
|
||||
result = "You Lose";
|
||||
style_result = ui::Theme::getInstance()->fg_red;
|
||||
} else {
|
||||
result = "Push (Tie)";
|
||||
}
|
||||
|
||||
// Draw result
|
||||
painter.draw_string({60, 270}, *style_result, result);
|
||||
|
||||
// Draw compact bet selector in top right area
|
||||
auto style_bet = *ui::Theme::getInstance()->fg_cyan;
|
||||
painter.draw_string({140, 25}, style_bet, "Next: $" + std::to_string(bet));
|
||||
|
||||
// Show controls
|
||||
painter.draw_string({10, 290}, *ui::Theme::getInstance()->fg_light, "SELECT: Deal ENC: +/-");
|
||||
}
|
||||
|
||||
last_player_count = player_card_count;
|
||||
last_dealer_count = dealer_card_count;
|
||||
last_game_state = game_state;
|
||||
last_bet = bet;
|
||||
} else if (game_state == GameState::GAME_OVER && bet != last_bet) {
|
||||
// Only update the bet display when it changes
|
||||
painter.fill_rectangle({140, 25, 90, 16}, Color::black());
|
||||
painter.draw_string({140, 25}, *ui::Theme::getInstance()->fg_cyan, "Next: $" + std::to_string(bet));
|
||||
last_bet = bet;
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::draw_suit_symbol(int x, int y, uint8_t suit, Color color, bool large) {
|
||||
if (large) {
|
||||
// Large suit symbols for center of card
|
||||
switch (suit) {
|
||||
case 0: // Spades
|
||||
// Top curve
|
||||
painter.fill_rectangle({x + 9, y + 4, 2, 2}, color);
|
||||
painter.fill_rectangle({x + 8, y + 5, 4, 2}, color);
|
||||
painter.fill_rectangle({x + 7, y + 6, 6, 2}, color);
|
||||
painter.fill_rectangle({x + 6, y + 7, 8, 2}, color);
|
||||
painter.fill_rectangle({x + 5, y + 8, 10, 2}, color);
|
||||
painter.fill_rectangle({x + 4, y + 9, 12, 2}, color);
|
||||
painter.fill_rectangle({x + 3, y + 10, 14, 2}, color);
|
||||
painter.fill_rectangle({x + 2, y + 11, 16, 2}, color);
|
||||
painter.fill_rectangle({x + 1, y + 12, 18, 2}, color);
|
||||
painter.fill_rectangle({x + 0, y + 13, 20, 3}, color);
|
||||
painter.fill_rectangle({x + 1, y + 16, 18, 2}, color);
|
||||
painter.fill_rectangle({x + 2, y + 17, 16, 1}, color);
|
||||
painter.fill_rectangle({x + 3, y + 18, 14, 1}, color);
|
||||
// Stem
|
||||
painter.fill_rectangle({x + 9, y + 19, 2, 4}, color);
|
||||
painter.fill_rectangle({x + 8, y + 22, 4, 1}, color);
|
||||
painter.fill_rectangle({x + 7, y + 23, 6, 1}, color);
|
||||
painter.fill_rectangle({x + 6, y + 24, 8, 1}, color);
|
||||
break;
|
||||
|
||||
case 1: // Hearts
|
||||
// Left bump
|
||||
painter.fill_rectangle({x + 3, y + 5, 4, 2}, color);
|
||||
painter.fill_rectangle({x + 2, y + 6, 6, 2}, color);
|
||||
painter.fill_rectangle({x + 1, y + 7, 8, 3}, color);
|
||||
painter.fill_rectangle({x + 0, y + 9, 9, 3}, color);
|
||||
// Right bump
|
||||
painter.fill_rectangle({x + 13, y + 5, 4, 2}, color);
|
||||
painter.fill_rectangle({x + 12, y + 6, 6, 2}, color);
|
||||
painter.fill_rectangle({x + 11, y + 7, 8, 3}, color);
|
||||
painter.fill_rectangle({x + 11, y + 9, 9, 3}, color);
|
||||
// Body
|
||||
painter.fill_rectangle({x + 1, y + 11, 18, 3}, color);
|
||||
painter.fill_rectangle({x + 2, y + 14, 16, 2}, color);
|
||||
painter.fill_rectangle({x + 3, y + 16, 14, 2}, color);
|
||||
painter.fill_rectangle({x + 4, y + 18, 12, 1}, color);
|
||||
painter.fill_rectangle({x + 5, y + 19, 10, 1}, color);
|
||||
painter.fill_rectangle({x + 6, y + 20, 8, 1}, color);
|
||||
painter.fill_rectangle({x + 7, y + 21, 6, 1}, color);
|
||||
painter.fill_rectangle({x + 8, y + 22, 4, 1}, color);
|
||||
painter.fill_rectangle({x + 9, y + 23, 2, 1}, color);
|
||||
break;
|
||||
|
||||
case 2: // Diamonds
|
||||
painter.fill_rectangle({x + 10, y + 3, 1, 1}, color);
|
||||
painter.fill_rectangle({x + 9, y + 4, 3, 1}, color);
|
||||
painter.fill_rectangle({x + 8, y + 5, 5, 1}, color);
|
||||
painter.fill_rectangle({x + 7, y + 6, 7, 1}, color);
|
||||
painter.fill_rectangle({x + 6, y + 7, 9, 1}, color);
|
||||
painter.fill_rectangle({x + 5, y + 8, 11, 1}, color);
|
||||
painter.fill_rectangle({x + 4, y + 9, 13, 1}, color);
|
||||
painter.fill_rectangle({x + 3, y + 10, 15, 1}, color);
|
||||
painter.fill_rectangle({x + 2, y + 11, 17, 1}, color);
|
||||
painter.fill_rectangle({x + 1, y + 12, 19, 1}, color);
|
||||
painter.fill_rectangle({x + 0, y + 13, 21, 1}, color);
|
||||
painter.fill_rectangle({x + 1, y + 14, 19, 1}, color);
|
||||
painter.fill_rectangle({x + 2, y + 15, 17, 1}, color);
|
||||
painter.fill_rectangle({x + 3, y + 16, 15, 1}, color);
|
||||
painter.fill_rectangle({x + 4, y + 17, 13, 1}, color);
|
||||
painter.fill_rectangle({x + 5, y + 18, 11, 1}, color);
|
||||
painter.fill_rectangle({x + 6, y + 19, 9, 1}, color);
|
||||
painter.fill_rectangle({x + 7, y + 20, 7, 1}, color);
|
||||
painter.fill_rectangle({x + 8, y + 21, 5, 1}, color);
|
||||
painter.fill_rectangle({x + 9, y + 22, 3, 1}, color);
|
||||
painter.fill_rectangle({x + 10, y + 23, 1, 1}, color);
|
||||
break;
|
||||
|
||||
case 3: // Clubs
|
||||
// Center circle
|
||||
painter.fill_rectangle({x + 8, y + 8, 5, 1}, color);
|
||||
painter.fill_rectangle({x + 7, y + 9, 7, 3}, color);
|
||||
painter.fill_rectangle({x + 8, y + 12, 5, 1}, color);
|
||||
// Left circle
|
||||
painter.fill_rectangle({x + 3, y + 11, 4, 1}, color);
|
||||
painter.fill_rectangle({x + 2, y + 12, 6, 3}, color);
|
||||
painter.fill_rectangle({x + 3, y + 15, 4, 1}, color);
|
||||
// Right circle
|
||||
painter.fill_rectangle({x + 14, y + 11, 4, 1}, color);
|
||||
painter.fill_rectangle({x + 13, y + 12, 6, 3}, color);
|
||||
painter.fill_rectangle({x + 14, y + 15, 4, 1}, color);
|
||||
// Connect circles
|
||||
painter.fill_rectangle({x + 6, y + 13, 9, 2}, color);
|
||||
// Stem
|
||||
painter.fill_rectangle({x + 9, y + 16, 3, 4}, color);
|
||||
painter.fill_rectangle({x + 8, y + 19, 5, 1}, color);
|
||||
painter.fill_rectangle({x + 7, y + 20, 7, 1}, color);
|
||||
painter.fill_rectangle({x + 6, y + 21, 9, 1}, color);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// Small suit symbols
|
||||
switch (suit) {
|
||||
case 0: // Spades - small
|
||||
painter.fill_rectangle({x + 2, y + 1, 3, 3}, color);
|
||||
painter.fill_rectangle({x + 1, y + 3, 5, 2}, color);
|
||||
painter.fill_rectangle({x + 3, y + 5, 1, 2}, color);
|
||||
break;
|
||||
|
||||
case 1: // Hearts - small
|
||||
painter.fill_rectangle({x + 1, y + 1, 2, 2}, color);
|
||||
painter.fill_rectangle({x + 4, y + 1, 2, 2}, color);
|
||||
painter.fill_rectangle({x + 1, y + 2, 5, 2}, color);
|
||||
painter.fill_rectangle({x + 2, y + 4, 3, 1}, color);
|
||||
painter.fill_rectangle({x + 3, y + 5, 1, 1}, color);
|
||||
break;
|
||||
|
||||
case 2: // Diamonds - small
|
||||
painter.fill_rectangle({x + 3, y + 1, 1, 1}, color);
|
||||
painter.fill_rectangle({x + 2, y + 2, 3, 1}, color);
|
||||
painter.fill_rectangle({x + 1, y + 3, 5, 1}, color);
|
||||
painter.fill_rectangle({x + 2, y + 4, 3, 1}, color);
|
||||
painter.fill_rectangle({x + 3, y + 5, 1, 1}, color);
|
||||
break;
|
||||
|
||||
case 3: // Clubs - small
|
||||
painter.fill_rectangle({x + 3, y + 1, 2, 2}, color);
|
||||
painter.fill_rectangle({x + 1, y + 3, 2, 2}, color);
|
||||
painter.fill_rectangle({x + 4, y + 3, 2, 2}, color);
|
||||
painter.fill_rectangle({x + 3, y + 5, 2, 2}, color);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::draw_card(int x, int y, uint8_t card, bool hidden) {
|
||||
const int width = 60;
|
||||
const int height = 80;
|
||||
|
||||
// Draw card background
|
||||
painter.fill_rectangle({x, y, width, height}, Color::white());
|
||||
painter.draw_rectangle({x, y, width, height}, Color::black());
|
||||
painter.draw_rectangle({x + 1, y + 1, width - 2, height - 2}, Color::grey()); // Inner border
|
||||
|
||||
if (hidden) {
|
||||
// Draw card back pattern - diagonal lines
|
||||
for (int i = 4; i < width - 4; i += 6) {
|
||||
for (int j = 4; j < height - 4; j += 6) {
|
||||
painter.fill_rectangle({x + i, y + j, 3, 3}, Color::blue());
|
||||
painter.fill_rectangle({x + i + 3, y + j + 3, 3, 3}, Color::red());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Draw card value
|
||||
uint8_t suit = get_card_suit(card);
|
||||
Color suit_color = (suit == 1 || suit == 2) ? Color::red() : Color::black();
|
||||
|
||||
const auto* base_style = ui::Theme::getInstance()->fg_light;
|
||||
Style card_style{
|
||||
.font = base_style->font,
|
||||
.background = Color::white(),
|
||||
.foreground = suit_color};
|
||||
|
||||
std::string value_str = get_card_string(card);
|
||||
|
||||
// Draw value in top-left corner
|
||||
painter.draw_string({x + 4, y + 4}, card_style, value_str);
|
||||
|
||||
// Draw small suit symbol next to value
|
||||
int suit_x = (value_str == "10") ? x + 20 : x + 12;
|
||||
draw_suit_symbol(suit_x, y + 4, suit, suit_color, false);
|
||||
|
||||
// Draw value in bottom-right corner
|
||||
int bottom_x = (value_str == "10") ? x + width - 24 : x + width - 16;
|
||||
painter.draw_string({bottom_x, y + height - 18}, card_style, value_str);
|
||||
|
||||
// Draw small suit symbol in bottom-right
|
||||
draw_suit_symbol(x + width - 10, y + height - 16, suit, suit_color, false);
|
||||
|
||||
// Draw large suit symbol in center
|
||||
draw_suit_symbol(x + 20, y + 28, suit, suit_color, true);
|
||||
}
|
||||
}
|
||||
|
||||
void BlackjackView::draw_hand(int x, int y, uint8_t* cards, uint8_t count, bool is_dealer) {
|
||||
// Calculate total width needed
|
||||
const int card_width = 60;
|
||||
const int overlap = 40; // Amount of overlap when cards need to fit
|
||||
const int max_width = 230 - x; // Available width on screen
|
||||
|
||||
int spacing;
|
||||
if (count == 1) {
|
||||
spacing = 0;
|
||||
} else if (count == 2) {
|
||||
spacing = card_width + 5; // Small gap for 2 cards
|
||||
} else {
|
||||
// Calculate spacing to fit all cards
|
||||
int total_overlap_width = card_width + (count - 1) * overlap;
|
||||
if (total_overlap_width <= max_width) {
|
||||
spacing = overlap;
|
||||
} else {
|
||||
// Need more overlap to fit
|
||||
spacing = (max_width - card_width) / (count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
for (uint8_t i = 0; i < count; i++) {
|
||||
bool hide = is_dealer && dealer_hidden && i == 1;
|
||||
int card_x = x + (i * spacing);
|
||||
draw_card(card_x, y, cards[i], hide);
|
||||
}
|
||||
}
|
||||
|
||||
bool BlackjackView::on_key(const KeyEvent key) {
|
||||
if (key == KeyEvent::Select) {
|
||||
switch (game_state) {
|
||||
case GameState::MENU:
|
||||
if (cash < 10) {
|
||||
cash = 100; // Reset if broke - maybe should provide https://gamblersanonymous.org/ link if they also lost their wife and house
|
||||
wins = 0;
|
||||
losses = 0;
|
||||
}
|
||||
game_state = GameState::BETTING;
|
||||
break;
|
||||
|
||||
case GameState::BETTING:
|
||||
deal_cards();
|
||||
break;
|
||||
|
||||
case GameState::PLAYING:
|
||||
player_hit();
|
||||
break;
|
||||
|
||||
case GameState::GAME_OVER:
|
||||
// Deal new hand with current bet
|
||||
if (cash >= bet) {
|
||||
deal_cards();
|
||||
} else if (cash >= 10) {
|
||||
// Not enough for current bet, reduce to what they can afford
|
||||
bet = 10;
|
||||
deal_cards();
|
||||
} else {
|
||||
// Broke, reset game
|
||||
cash = 100;
|
||||
wins = 0;
|
||||
losses = 0;
|
||||
game_state = GameState::MENU;
|
||||
draw_menu_static();
|
||||
}
|
||||
break;
|
||||
|
||||
case GameState::STATS:
|
||||
game_state = GameState::MENU;
|
||||
draw_menu_static();
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return true;
|
||||
} else if (key == KeyEvent::Left) {
|
||||
if (game_state == GameState::MENU) {
|
||||
game_state = GameState::STATS;
|
||||
}
|
||||
return true;
|
||||
} else if (key == KeyEvent::Right) {
|
||||
if (game_state == GameState::MENU) {
|
||||
nav_.pop();
|
||||
return true;
|
||||
} else if (game_state == GameState::PLAYING) {
|
||||
player_stay();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool BlackjackView::on_encoder(const EncoderEvent delta) {
|
||||
if (game_state == GameState::BETTING || game_state == GameState::GAME_OVER) {
|
||||
if (delta > 0 && bet + 10 <= cash) {
|
||||
bet += 10;
|
||||
} else if (delta < 0 && bet >= 20) {
|
||||
bet -= 10;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace ui::external_app::blackjack
|
||||
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* Blackjack Game for Portapack Mayhem
|
||||
* Ported / Enhanced / Graphically made awesome by RocketGod (https://betaskynet.com)
|
||||
* Based on BlackJack 83 for TI Calculator by Harper Maddox (was written in Assembly)
|
||||
*/
|
||||
|
||||
#ifndef __UI_BLACKJACK_H__
|
||||
#define __UI_BLACKJACK_H__
|
||||
|
||||
#include "ui.hpp"
|
||||
#include "ui_navigation.hpp"
|
||||
#include "event_m0.hpp"
|
||||
#include "message.hpp"
|
||||
#include "irq_controls.hpp"
|
||||
#include "random.hpp"
|
||||
#include "lpc43xx_cpp.hpp"
|
||||
#include "ui_widget.hpp"
|
||||
#include "app_settings.hpp"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ui::external_app::blackjack {
|
||||
|
||||
// Game states
|
||||
enum class GameState {
|
||||
MENU,
|
||||
BETTING,
|
||||
PLAYING,
|
||||
DEALER_TURN,
|
||||
GAME_OVER,
|
||||
STATS
|
||||
};
|
||||
|
||||
// Card structure
|
||||
struct Card {
|
||||
uint8_t value; // 1-13 (Ace=1, Jack=11, Queen=12, King=13)
|
||||
uint8_t suit; // 0=Spades, 1=Hearts, 2=Diamonds, 3=Clubs
|
||||
|
||||
Card()
|
||||
: value(0), suit(0) {}
|
||||
Card(uint8_t v, uint8_t s)
|
||||
: value(v), suit(s) {}
|
||||
};
|
||||
|
||||
// Timer class
|
||||
using Callback = void (*)(void);
|
||||
|
||||
class Ticker {
|
||||
public:
|
||||
Ticker() = default;
|
||||
void attach(Callback func, double delay_sec);
|
||||
void detach();
|
||||
};
|
||||
|
||||
// Function declarations
|
||||
void check_game_timer();
|
||||
void game_timer_check();
|
||||
|
||||
class BlackjackView : public View {
|
||||
public:
|
||||
BlackjackView(NavigationView& nav);
|
||||
~BlackjackView();
|
||||
|
||||
void on_show() override;
|
||||
std::string title() const override { return "Blackjack"; }
|
||||
void focus() override { dummy.focus(); }
|
||||
void paint(Painter& painter) override;
|
||||
void frame_sync();
|
||||
bool on_encoder(const EncoderEvent event) override;
|
||||
bool on_key(KeyEvent key) override;
|
||||
|
||||
// Public for timer callback
|
||||
GameState game_state = GameState::MENU;
|
||||
void update_game();
|
||||
|
||||
private:
|
||||
NavigationView& nav_;
|
||||
bool initialized = false;
|
||||
|
||||
// Game variables
|
||||
static constexpr uint8_t MAX_CARDS_IN_HAND = 11; // Maximum possible cards before bust
|
||||
uint8_t deck[52];
|
||||
uint8_t deck_position = 0;
|
||||
|
||||
uint8_t player_cards[MAX_CARDS_IN_HAND];
|
||||
uint8_t player_card_count = 0;
|
||||
|
||||
uint8_t dealer_cards[MAX_CARDS_IN_HAND];
|
||||
uint8_t dealer_card_count = 0;
|
||||
|
||||
// Game state variables
|
||||
uint32_t cash = 100;
|
||||
uint32_t bet = 10;
|
||||
uint32_t wins = 0;
|
||||
uint32_t losses = 0;
|
||||
uint32_t high_score = 100;
|
||||
bool dealer_hidden = true;
|
||||
|
||||
// UI state
|
||||
uint8_t menu_selection = 0;
|
||||
bool blink_state = true;
|
||||
uint32_t blink_counter = 0;
|
||||
uint32_t dealer_timer = 0;
|
||||
|
||||
// Timer
|
||||
Ticker game_timer;
|
||||
|
||||
// Methods
|
||||
void init_deck();
|
||||
void shuffle_deck();
|
||||
uint8_t draw_card();
|
||||
void deal_cards();
|
||||
int calculate_hand_value(uint8_t* cards, uint8_t count);
|
||||
int get_card_value(uint8_t card);
|
||||
uint8_t get_card_suit(uint8_t card);
|
||||
std::string get_card_string(uint8_t card);
|
||||
void player_hit();
|
||||
void player_stay();
|
||||
void dealer_turn();
|
||||
void check_game_over();
|
||||
void reset_game();
|
||||
|
||||
// Drawing methods
|
||||
void draw_menu();
|
||||
void draw_menu_static();
|
||||
void draw_stats();
|
||||
void draw_game();
|
||||
void draw_betting();
|
||||
void draw_card(int x, int y, uint8_t card, bool hidden = false);
|
||||
void draw_hand(int x, int y, uint8_t* cards, uint8_t count, bool is_dealer = false);
|
||||
void draw_suit_symbol(int x, int y, uint8_t suit, Color color, bool large);
|
||||
void clear_screen();
|
||||
|
||||
// Settings
|
||||
app_settings::SettingsManager settings_{
|
||||
"blackjack",
|
||||
app_settings::Mode::NO_RF,
|
||||
{{"cash"sv, &cash},
|
||||
{"wins"sv, &wins},
|
||||
{"losses"sv, &losses},
|
||||
{"highscore"sv, &high_score}}};
|
||||
|
||||
Button dummy{
|
||||
{240, 0, 0, 0},
|
||||
""};
|
||||
|
||||
MessageHandlerRegistration message_handler_frame_sync{
|
||||
Message::ID::DisplayFrameSync,
|
||||
[this](const Message* const) {
|
||||
this->frame_sync();
|
||||
}};
|
||||
};
|
||||
|
||||
} // namespace ui::external_app::blackjack
|
||||
|
||||
#endif /* __UI_BLACKJACK_H__ */
|
||||
+19
-36
@@ -4,9 +4,7 @@
|
||||
* | Find me at https://betaskynet.com |
|
||||
* | Argh matey! |
|
||||
* ------------------------------------------------------------
|
||||
*/
|
||||
|
||||
/*
|
||||
*
|
||||
* Chrome Dino Game for Portapack Mayhem
|
||||
* Based on the original DinoGame by various contributors
|
||||
*/
|
||||
@@ -32,38 +30,23 @@ __attribute__((section(".external_app.app_dinogame.application_information"), us
|
||||
|
||||
"Dino Game",
|
||||
{
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0xF0,
|
||||
0xF8,
|
||||
0xFC,
|
||||
0xFE,
|
||||
0xFF,
|
||||
0xFF,
|
||||
0x7F,
|
||||
0x7F,
|
||||
0x3F,
|
||||
0x3F,
|
||||
0x3E,
|
||||
0x3C,
|
||||
0x38,
|
||||
0x30,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
// Cactus icon 16x16
|
||||
0x00, 0x00, // ................
|
||||
0x80, 0x01, // .......##.......
|
||||
0x80, 0x01, // .......##.......
|
||||
0x80, 0x01, // .......##.......
|
||||
0x98, 0x19, // ...##..##..##...
|
||||
0x98, 0x19, // ...##..##..##...
|
||||
0x98, 0x19, // ...##..##..##...
|
||||
0x98, 0x19, // ...##..##..##...
|
||||
0xF8, 0x1F, // ...##########...
|
||||
0xF0, 0x0F, // ....########....
|
||||
0x80, 0x01, // .......##.......
|
||||
0x80, 0x01, // .......##.......
|
||||
0x80, 0x01, // .......##.......
|
||||
0x80, 0x01, // .......##.......
|
||||
0x80, 0x01, // .......##.......
|
||||
0x00, 0x00, // ................
|
||||
},
|
||||
ui::Color::green().v,
|
||||
app_location_t::GAMES,
|
||||
@@ -72,4 +55,4 @@ __attribute__((section(".external_app.app_dinogame.application_information"), us
|
||||
{0, 0, 0, 0},
|
||||
0x00000000,
|
||||
};
|
||||
}
|
||||
}
|
||||
+10
@@ -220,6 +220,14 @@ set(EXTCPPSRC
|
||||
#detector_rx
|
||||
external/detector_rx/main.cpp
|
||||
external/detector_rx/ui_detector_rx.cpp
|
||||
|
||||
#space_invaders
|
||||
external/spaceinv/main.cpp
|
||||
external/spaceinv/ui_spaceinv.cpp
|
||||
|
||||
#blackjack
|
||||
external/blackjack/main.cpp
|
||||
external/blackjack/ui_blackjack.cpp
|
||||
)
|
||||
|
||||
set(EXTAPPLIST
|
||||
@@ -276,4 +284,6 @@ set(EXTAPPLIST
|
||||
level
|
||||
gfxeq
|
||||
detector_rx
|
||||
spaceinv
|
||||
blackjack
|
||||
)
|
||||
|
||||
+14
@@ -76,6 +76,8 @@ MEMORY
|
||||
ram_external_app_noaaapt_rx (rwx) : org = 0xADE30000, len = 32k
|
||||
ram_external_app_detector_rx (rwx) : org = 0xADE40000, len = 32k
|
||||
ram_external_app_dinogame (rwx) : org = 0xADE50000, len = 32k
|
||||
ram_external_app_spaceinv (rwx) : org = 0xADE60000, len = 32k
|
||||
ram_external_app_blackjack (rwx) : org = 0xADE70000, len = 32k
|
||||
}
|
||||
|
||||
SECTIONS
|
||||
@@ -398,5 +400,17 @@ SECTIONS
|
||||
*(*ui*external_app*dinogame*);
|
||||
} > ram_external_app_dinogame
|
||||
|
||||
.external_app_spaceinv : ALIGN(4) SUBALIGN(4)
|
||||
{
|
||||
KEEP(*(.external_app.app_spaceinv.application_information));
|
||||
*(*ui*external_app*spaceinv*);
|
||||
} > ram_external_app_spaceinv
|
||||
|
||||
.external_app_blackjack : ALIGN(4) SUBALIGN(4)
|
||||
{
|
||||
KEEP(*(.external_app.app_blackjack.application_information));
|
||||
*(*ui*external_app*blackjack*);
|
||||
} > ram_external_app_blackjack
|
||||
|
||||
}
|
||||
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* ------------------------------------------------------------
|
||||
* | Made by RocketGod |
|
||||
* | Find me at https://betaskynet.com |
|
||||
* | Argh matey! |
|
||||
* ------------------------------------------------------------
|
||||
*/
|
||||
|
||||
#include "ui.hpp"
|
||||
#include "ui_spaceinv.hpp"
|
||||
#include "ui_navigation.hpp"
|
||||
#include "external_app.hpp"
|
||||
|
||||
namespace ui::external_app::spaceinv {
|
||||
void initialize_app(ui::NavigationView& nav) {
|
||||
nav.push<SpaceInvadersView>();
|
||||
}
|
||||
} // namespace ui::external_app::spaceinv
|
||||
|
||||
extern "C" {
|
||||
|
||||
__attribute__((section(".external_app.app_spaceinv.application_information"), used)) application_information_t _application_information_spaceinv = {
|
||||
(uint8_t*)0x00000000,
|
||||
ui::external_app::spaceinv::initialize_app,
|
||||
CURRENT_HEADER_VERSION,
|
||||
VERSION_MD5,
|
||||
|
||||
"Space Invaders",
|
||||
{
|
||||
// Space Invader alien icon 16x16
|
||||
0x00, 0x18, // .......##.......
|
||||
0x00, 0x3C, // ......####......
|
||||
0x00, 0x7E, // .....######.....
|
||||
0x00, 0xDB, // ....##.##.##....
|
||||
0x00, 0xFF, // ....########....
|
||||
0x00, 0xFF, // ....########....
|
||||
0x00, 0x24, // ......#..#......
|
||||
0x00, 0x66, // .....##..##.....
|
||||
0x00, 0x42, // .....#....#.....
|
||||
0x00, 0x00, // ................
|
||||
0x00, 0x24, // ......#..#......
|
||||
0x00, 0x18, // .......##.......
|
||||
0x00, 0x24, // ......#..#......
|
||||
0x00, 0x42, // .....#....#.....
|
||||
0x00, 0x81, // ....#......#....
|
||||
0x00, 0x00, // ................
|
||||
},
|
||||
ui::Color::magenta().v,
|
||||
app_location_t::GAMES,
|
||||
-1,
|
||||
|
||||
{0, 0, 0, 0},
|
||||
0x00000000,
|
||||
};
|
||||
} // namespace ui::external_app::spaceinv
|
||||
@@ -0,0 +1,879 @@
|
||||
/*
|
||||
* ------------------------------------------------------------
|
||||
* | Made by RocketGod |
|
||||
* | Find me at https://betaskynet.com |
|
||||
* | Argh matey! |
|
||||
* ------------------------------------------------------------
|
||||
*/
|
||||
|
||||
#include "ui_spaceinv.hpp"
|
||||
|
||||
namespace ui::external_app::spaceinv {
|
||||
|
||||
// Game constants
|
||||
#define PLAYER_WIDTH 26
|
||||
#define PLAYER_HEIGHT 16
|
||||
#define PLAYER_Y 280
|
||||
#define BULLET_WIDTH 3
|
||||
#define BULLET_HEIGHT 10
|
||||
#define BULLET_SPEED 8
|
||||
#define MAX_BULLETS 3
|
||||
#define INVADER_WIDTH 20
|
||||
#define INVADER_HEIGHT 16
|
||||
#define INVADER_ROWS 5 // Classic 5 rows
|
||||
#define INVADER_COLS 6 // Reduced for more movement space on narrow PP screen
|
||||
#define INVADER_GAP_X 10
|
||||
#define INVADER_GAP_Y 8 // Gap between invaders
|
||||
#define MAX_ENEMY_BULLETS 3
|
||||
#define ENEMY_BULLET_SPEED 3
|
||||
|
||||
// Game state
|
||||
static int game_state = 0; // 0=menu, 1=playing, 2=game over, 3=wave_complete
|
||||
static bool initialized = false;
|
||||
static int player_x = 120;
|
||||
static uint32_t score = 0;
|
||||
static int lives = 3;
|
||||
static uint32_t wave = 1;
|
||||
static uint32_t speed_bonus = 0;
|
||||
static uint32_t wave_complete_timer = 0;
|
||||
|
||||
// Cannon Bullets
|
||||
static int bullet_x[MAX_BULLETS] = {0, 0, 0};
|
||||
static int bullet_y[MAX_BULLETS] = {0, 0, 0};
|
||||
static bool bullet_active[MAX_BULLETS] = {false, false, false};
|
||||
|
||||
// Enemy bullets
|
||||
static int enemy_bullet_x[MAX_ENEMY_BULLETS] = {0, 0, 0};
|
||||
static int enemy_bullet_y[MAX_ENEMY_BULLETS] = {0, 0, 0};
|
||||
static bool enemy_bullet_active[MAX_ENEMY_BULLETS] = {false, false, false};
|
||||
static uint32_t enemy_fire_counter = 0;
|
||||
|
||||
// Invaders
|
||||
static bool invaders[INVADER_ROWS][INVADER_COLS];
|
||||
static int invaders_x = 40;
|
||||
static int invaders_y = 60;
|
||||
static int invader_direction = 1;
|
||||
static uint32_t invader_move_counter = 0;
|
||||
static uint32_t invader_move_delay = 30;
|
||||
static bool invader_animation_frame = false;
|
||||
|
||||
// Menu state
|
||||
static bool menu_initialized = false;
|
||||
static bool game_over_initialized = false;
|
||||
static bool blink_state = true;
|
||||
static uint32_t blink_counter = 0;
|
||||
static int16_t prompt_x = 0;
|
||||
|
||||
// Timer
|
||||
static Ticker game_timer;
|
||||
static Callback game_update_callback = nullptr;
|
||||
static uint32_t game_update_timeout = 0;
|
||||
static uint32_t game_update_counter = 0;
|
||||
|
||||
// Painter
|
||||
static Painter painter;
|
||||
|
||||
// For high score access
|
||||
static SpaceInvadersView* current_instance = nullptr;
|
||||
|
||||
void check_game_timer() {
|
||||
if (game_update_callback) {
|
||||
if (++game_update_counter >= game_update_timeout) {
|
||||
game_update_counter = 0;
|
||||
game_update_callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Ticker::attach(Callback func, double delay_sec) {
|
||||
game_update_callback = func;
|
||||
game_update_timeout = delay_sec * 60;
|
||||
}
|
||||
|
||||
void Ticker::detach() {
|
||||
game_update_callback = nullptr;
|
||||
}
|
||||
|
||||
static void init_invaders() {
|
||||
// Initialize invader array
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
invaders[row][col] = true;
|
||||
}
|
||||
}
|
||||
invaders_x = 40;
|
||||
invaders_y = 60;
|
||||
invader_direction = 1;
|
||||
invader_move_counter = 0;
|
||||
|
||||
// Clear any active enemy bullets
|
||||
for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
|
||||
enemy_bullet_active[i] = false;
|
||||
}
|
||||
|
||||
// Clear any active player bullets
|
||||
for (int i = 0; i < MAX_BULLETS; i++) {
|
||||
bullet_active[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
static void save_high_score() {
|
||||
if (current_instance && score > current_instance->highScore) {
|
||||
current_instance->highScore = score;
|
||||
// Settings are automatically saved when the view is destroyed
|
||||
}
|
||||
}
|
||||
|
||||
static void init_menu() {
|
||||
painter.fill_rectangle({0, 0, 240, 320}, Color::black());
|
||||
|
||||
auto style_green = *ui::Theme::getInstance()->fg_green;
|
||||
auto style_yellow = *ui::Theme::getInstance()->fg_yellow;
|
||||
auto style_cyan = *ui::Theme::getInstance()->fg_cyan;
|
||||
|
||||
int16_t screen_width = 240;
|
||||
int16_t title_x = (screen_width - 15 * 8) / 2;
|
||||
int16_t divider_width = 24 * 8;
|
||||
int16_t divider_x = (screen_width - divider_width) / 2;
|
||||
int16_t instruction_width = 22 * 8;
|
||||
int16_t instruction_x = (screen_width - instruction_width) / 2;
|
||||
int16_t prompt_width = 12 * 8;
|
||||
prompt_x = (screen_width - prompt_width) / 2;
|
||||
|
||||
painter.fill_rectangle({0, 30, screen_width, 30}, Color::black());
|
||||
painter.draw_string({title_x, 42}, style_green, "SPACE INVADERS");
|
||||
|
||||
painter.draw_string({divider_x, 70}, style_yellow, "========================");
|
||||
|
||||
painter.fill_rectangle({instruction_x - 5, 100, instruction_width + 10, 80}, Color::black());
|
||||
painter.draw_rectangle({instruction_x - 5, 100, instruction_width + 10, 80}, Color::white());
|
||||
|
||||
painter.draw_string({instruction_x, 110}, style_cyan, " ROTARY: MOVE SHIP");
|
||||
painter.draw_string({instruction_x, 130}, style_cyan, " SELECT: FIRE");
|
||||
painter.draw_string({instruction_x, 150}, style_cyan, " DEFEND EARTH!");
|
||||
|
||||
// Draw point values
|
||||
auto style_purple = *ui::Theme::getInstance()->fg_magenta;
|
||||
painter.draw_string({50, 190}, style_purple, "TOP ROW = 30 PTS");
|
||||
painter.draw_string({50, 205}, style_yellow, "MID ROW = 20 PTS");
|
||||
painter.draw_string({50, 220}, style_green, "BOT ROW = 10 PTS");
|
||||
|
||||
// Draw high score
|
||||
if (current_instance) {
|
||||
auto style_white = *ui::Theme::getInstance()->fg_light;
|
||||
std::string high_score_text = "HIGH SCORE: " + std::to_string(current_instance->highScore);
|
||||
int16_t high_score_x = (screen_width - high_score_text.length() * 8) / 2;
|
||||
painter.draw_string({high_score_x, 240}, style_white, high_score_text);
|
||||
}
|
||||
|
||||
menu_initialized = true;
|
||||
}
|
||||
|
||||
static void init_game_over() {
|
||||
painter.fill_rectangle({0, 0, 240, 320}, Color::black());
|
||||
|
||||
auto style_red = *ui::Theme::getInstance()->fg_red;
|
||||
auto style_yellow = *ui::Theme::getInstance()->fg_yellow;
|
||||
auto style_cyan = *ui::Theme::getInstance()->fg_cyan;
|
||||
auto style_white = *ui::Theme::getInstance()->fg_light;
|
||||
|
||||
int16_t screen_width = 240;
|
||||
|
||||
// Game Over title
|
||||
int16_t title_x = (screen_width - 9 * 8) / 2;
|
||||
painter.draw_string({title_x, 42}, style_red, "GAME OVER");
|
||||
|
||||
// Divider
|
||||
int16_t divider_width = 24 * 8;
|
||||
int16_t divider_x = (screen_width - divider_width) / 2;
|
||||
painter.draw_string({divider_x, 70}, style_yellow, "========================");
|
||||
|
||||
// Score box
|
||||
int16_t box_width = 22 * 8;
|
||||
int16_t box_x = (screen_width - box_width) / 2;
|
||||
painter.fill_rectangle({box_x - 5, 100, box_width + 10, 80}, Color::black());
|
||||
painter.draw_rectangle({box_x - 5, 100, box_width + 10, 80}, Color::white());
|
||||
|
||||
// Display scores
|
||||
std::string score_text = "SCORE: " + std::to_string(score);
|
||||
int16_t score_x = (screen_width - score_text.length() * 8) / 2;
|
||||
painter.draw_string({score_x, 120}, style_cyan, score_text);
|
||||
|
||||
std::string wave_text = "WAVE: " + std::to_string(wave);
|
||||
int16_t wave_x = (screen_width - wave_text.length() * 8) / 2;
|
||||
painter.draw_string({wave_x, 140}, style_cyan, wave_text);
|
||||
|
||||
// High score section
|
||||
if (current_instance) {
|
||||
if (score > current_instance->highScore) {
|
||||
// New high score!
|
||||
std::string new_high = "NEW HIGH SCORE!";
|
||||
int16_t new_high_x = (screen_width - new_high.length() * 8) / 2;
|
||||
painter.draw_string({new_high_x, 200}, style_yellow, new_high);
|
||||
|
||||
std::string high_score_text = std::to_string(score);
|
||||
int16_t high_score_x = (screen_width - high_score_text.length() * 8) / 2;
|
||||
painter.draw_string({high_score_x, 220}, style_yellow, high_score_text);
|
||||
} else {
|
||||
// Show existing high score
|
||||
std::string high_label = "HIGH SCORE:";
|
||||
int16_t label_x = (screen_width - high_label.length() * 8) / 2;
|
||||
painter.draw_string({label_x, 200}, style_white, high_label);
|
||||
|
||||
std::string high_score_text = std::to_string(current_instance->highScore);
|
||||
int16_t high_score_x = (screen_width - high_score_text.length() * 8) / 2;
|
||||
painter.draw_string({high_score_x, 220}, style_white, high_score_text);
|
||||
}
|
||||
}
|
||||
|
||||
game_over_initialized = true;
|
||||
}
|
||||
|
||||
static void draw_player() {
|
||||
// Clear the entire player area
|
||||
painter.fill_rectangle({0, PLAYER_Y - 4, 240, PLAYER_HEIGHT + 8}, Color::black());
|
||||
|
||||
// Draw the classic Space Invaders cannon
|
||||
Color green = Color::green();
|
||||
|
||||
// Top part - the cannon barrel
|
||||
painter.draw_hline({player_x + 12, PLAYER_Y}, 2, green);
|
||||
painter.draw_hline({player_x + 12, PLAYER_Y + 1}, 2, green);
|
||||
|
||||
// Upper body
|
||||
painter.draw_hline({player_x + 11, PLAYER_Y + 2}, 4, green);
|
||||
painter.draw_hline({player_x + 11, PLAYER_Y + 3}, 4, green);
|
||||
painter.draw_hline({player_x + 10, PLAYER_Y + 4}, 6, green);
|
||||
painter.draw_hline({player_x + 10, PLAYER_Y + 5}, 6, green);
|
||||
|
||||
// Main body
|
||||
painter.draw_hline({player_x + 2, PLAYER_Y + 6}, 22, green);
|
||||
painter.draw_hline({player_x + 2, PLAYER_Y + 7}, 22, green);
|
||||
painter.draw_hline({player_x + 1, PLAYER_Y + 8}, 24, green);
|
||||
painter.draw_hline({player_x + 1, PLAYER_Y + 9}, 24, green);
|
||||
painter.draw_hline({player_x, PLAYER_Y + 10}, 26, green);
|
||||
painter.draw_hline({player_x, PLAYER_Y + 11}, 26, green);
|
||||
painter.draw_hline({player_x, PLAYER_Y + 12}, 26, green);
|
||||
painter.draw_hline({player_x, PLAYER_Y + 13}, 26, green);
|
||||
painter.draw_hline({player_x, PLAYER_Y + 14}, 26, green);
|
||||
painter.draw_hline({player_x, PLAYER_Y + 15}, 26, green);
|
||||
}
|
||||
|
||||
static void draw_invader(int row, int col) {
|
||||
int x = invaders_x + col * (INVADER_WIDTH + INVADER_GAP_X);
|
||||
int y = invaders_y + row * (INVADER_HEIGHT + INVADER_GAP_Y);
|
||||
|
||||
// Clear the area first
|
||||
painter.fill_rectangle({x, y, INVADER_WIDTH, INVADER_HEIGHT}, Color::black());
|
||||
|
||||
// Different colors and shapes for different rows
|
||||
Color color;
|
||||
if (row == 0) {
|
||||
color = Color::red(); // Top row - 30 points
|
||||
} else if (row == 1 || row == 2) {
|
||||
color = Color::yellow(); // Middle rows - 20 points
|
||||
} else {
|
||||
color = Color::green(); // Bottom rows - 10 points
|
||||
}
|
||||
|
||||
// Draw different invader types based on row
|
||||
if (row == 0) {
|
||||
// Top row - squid-like invader (30 points)
|
||||
if (invader_animation_frame) {
|
||||
// Frame 1 - arms down
|
||||
painter.draw_hline({x + 8, y + 2}, 4, color);
|
||||
painter.draw_hline({x + 6, y + 3}, 8, color);
|
||||
painter.draw_hline({x + 4, y + 4}, 12, color);
|
||||
painter.draw_hline({x + 2, y + 5}, 16, color);
|
||||
painter.draw_hline({x + 2, y + 6}, 16, color);
|
||||
painter.draw_hline({x, y + 7}, 20, color);
|
||||
painter.draw_hline({x, y + 8}, 20, color);
|
||||
painter.draw_hline({x + 2, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 6, y + 9}, 8, color);
|
||||
painter.draw_hline({x + 16, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 4, y + 10}, 2, color);
|
||||
painter.draw_hline({x + 14, y + 10}, 2, color);
|
||||
} else {
|
||||
// Frame 2 - arms up
|
||||
painter.draw_hline({x + 8, y + 2}, 4, color);
|
||||
painter.draw_hline({x + 6, y + 3}, 8, color);
|
||||
painter.draw_hline({x + 4, y + 4}, 12, color);
|
||||
painter.draw_hline({x + 2, y + 5}, 16, color);
|
||||
painter.draw_hline({x + 2, y + 6}, 16, color);
|
||||
painter.draw_hline({x, y + 7}, 20, color);
|
||||
painter.draw_hline({x, y + 8}, 20, color);
|
||||
painter.draw_hline({x + 4, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 8, y + 9}, 4, color);
|
||||
painter.draw_hline({x + 14, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 2, y + 10}, 2, color);
|
||||
painter.draw_hline({x + 16, y + 10}, 2, color);
|
||||
}
|
||||
} else if (row == 1 || row == 2) {
|
||||
// Middle rows - crab-like invader (20 points)
|
||||
if (invader_animation_frame) {
|
||||
// Frame 1 - arms in
|
||||
painter.draw_hline({x + 4, y + 2}, 2, color);
|
||||
painter.draw_hline({x + 14, y + 2}, 2, color);
|
||||
painter.draw_hline({x + 2, y + 3}, 2, color);
|
||||
painter.draw_hline({x + 6, y + 3}, 8, color);
|
||||
painter.draw_hline({x + 16, y + 3}, 2, color);
|
||||
painter.draw_hline({x + 2, y + 4}, 16, color);
|
||||
painter.draw_hline({x, y + 5}, 6, color);
|
||||
painter.draw_hline({x + 8, y + 5}, 4, color);
|
||||
painter.draw_hline({x + 14, y + 5}, 6, color);
|
||||
painter.draw_hline({x, y + 6}, 20, color);
|
||||
painter.draw_hline({x + 2, y + 7}, 16, color);
|
||||
painter.draw_hline({x + 4, y + 8}, 2, color);
|
||||
painter.draw_hline({x + 14, y + 8}, 2, color);
|
||||
painter.draw_hline({x + 2, y + 9}, 4, color);
|
||||
painter.draw_hline({x + 14, y + 9}, 4, color);
|
||||
} else {
|
||||
// Frame 2 - arms out
|
||||
painter.draw_hline({x + 4, y + 2}, 2, color);
|
||||
painter.draw_hline({x + 14, y + 2}, 2, color);
|
||||
painter.draw_hline({x + 2, y + 3}, 2, color);
|
||||
painter.draw_hline({x + 6, y + 3}, 8, color);
|
||||
painter.draw_hline({x + 16, y + 3}, 2, color);
|
||||
painter.draw_hline({x + 2, y + 4}, 16, color);
|
||||
painter.draw_hline({x, y + 5}, 6, color);
|
||||
painter.draw_hline({x + 8, y + 5}, 4, color);
|
||||
painter.draw_hline({x + 14, y + 5}, 6, color);
|
||||
painter.draw_hline({x, y + 6}, 20, color);
|
||||
painter.draw_hline({x + 2, y + 7}, 16, color);
|
||||
painter.draw_hline({x + 4, y + 8}, 2, color);
|
||||
painter.draw_hline({x + 14, y + 8}, 2, color);
|
||||
painter.draw_hline({x, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 6, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 12, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 18, y + 9}, 2, color);
|
||||
}
|
||||
} else {
|
||||
// Bottom rows - octopus-like invader (10 points)
|
||||
if (invader_animation_frame) {
|
||||
// Frame 1
|
||||
painter.draw_hline({x + 6, y + 2}, 8, color);
|
||||
painter.draw_hline({x + 4, y + 3}, 12, color);
|
||||
painter.draw_hline({x + 2, y + 4}, 16, color);
|
||||
painter.draw_hline({x, y + 5}, 20, color);
|
||||
painter.draw_hline({x, y + 6}, 20, color);
|
||||
painter.draw_hline({x + 4, y + 7}, 4, color);
|
||||
painter.draw_hline({x + 12, y + 7}, 4, color);
|
||||
painter.draw_hline({x + 2, y + 8}, 4, color);
|
||||
painter.draw_hline({x + 8, y + 8}, 4, color);
|
||||
painter.draw_hline({x + 14, y + 8}, 4, color);
|
||||
painter.draw_hline({x + 4, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 14, y + 9}, 2, color);
|
||||
} else {
|
||||
// Frame 2
|
||||
painter.draw_hline({x + 6, y + 2}, 8, color);
|
||||
painter.draw_hline({x + 4, y + 3}, 12, color);
|
||||
painter.draw_hline({x + 2, y + 4}, 16, color);
|
||||
painter.draw_hline({x, y + 5}, 20, color);
|
||||
painter.draw_hline({x, y + 6}, 20, color);
|
||||
painter.draw_hline({x + 4, y + 7}, 4, color);
|
||||
painter.draw_hline({x + 12, y + 7}, 4, color);
|
||||
painter.draw_hline({x + 2, y + 8}, 4, color);
|
||||
painter.draw_hline({x + 8, y + 8}, 4, color);
|
||||
painter.draw_hline({x + 14, y + 8}, 4, color);
|
||||
painter.draw_hline({x + 2, y + 9}, 2, color);
|
||||
painter.draw_hline({x + 16, y + 9}, 2, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void draw_all_invaders() {
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
if (invaders[row][col]) {
|
||||
draw_invader(row, col);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void clear_all_invaders() {
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
if (invaders[row][col]) {
|
||||
int x = invaders_x + col * (INVADER_WIDTH + INVADER_GAP_X);
|
||||
int y = invaders_y + row * (INVADER_HEIGHT + INVADER_GAP_Y);
|
||||
painter.fill_rectangle({x, y, INVADER_WIDTH, INVADER_HEIGHT}, Color::black());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void clear_all_enemy_bullets() {
|
||||
// Clear any visible enemy bullets
|
||||
for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
|
||||
if (enemy_bullet_active[i]) {
|
||||
painter.fill_rectangle({enemy_bullet_x[i], enemy_bullet_y[i], BULLET_WIDTH, BULLET_HEIGHT}, Color::black());
|
||||
enemy_bullet_active[i] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void fire_enemy_bullet() {
|
||||
// Find a random invader to fire from
|
||||
int active_count = 0;
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
if (invaders[row][col]) active_count++;
|
||||
}
|
||||
}
|
||||
|
||||
if (active_count == 0) return;
|
||||
|
||||
int shooter = rand() % active_count;
|
||||
int count = 0;
|
||||
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
if (invaders[row][col]) {
|
||||
if (count == shooter) {
|
||||
// Fire from this invader
|
||||
for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
|
||||
if (!enemy_bullet_active[i]) {
|
||||
int x = invaders_x + col * (INVADER_WIDTH + INVADER_GAP_X);
|
||||
int y = invaders_y + row * (INVADER_HEIGHT + INVADER_GAP_Y);
|
||||
enemy_bullet_x[i] = x + INVADER_WIDTH / 2;
|
||||
enemy_bullet_y[i] = y + INVADER_HEIGHT;
|
||||
enemy_bullet_active[i] = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void update_enemy_bullets() {
|
||||
for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
|
||||
if (enemy_bullet_active[i]) {
|
||||
// Clear old position - but protect the border line
|
||||
if (enemy_bullet_y[i] != 49) { // Don't clear if we're exactly on the border line
|
||||
painter.fill_rectangle({enemy_bullet_x[i], enemy_bullet_y[i], BULLET_WIDTH, BULLET_HEIGHT}, Color::black());
|
||||
}
|
||||
|
||||
enemy_bullet_y[i] += ENEMY_BULLET_SPEED;
|
||||
|
||||
if (enemy_bullet_y[i] > 320) {
|
||||
enemy_bullet_active[i] = false;
|
||||
} else {
|
||||
// Draw at new position
|
||||
painter.fill_rectangle({enemy_bullet_x[i], enemy_bullet_y[i], BULLET_WIDTH, BULLET_HEIGHT}, Color::red());
|
||||
|
||||
// Check collision with player
|
||||
if (enemy_bullet_x[i] >= player_x &&
|
||||
enemy_bullet_x[i] <= player_x + PLAYER_WIDTH &&
|
||||
enemy_bullet_y[i] >= PLAYER_Y &&
|
||||
enemy_bullet_y[i] <= PLAYER_Y + PLAYER_HEIGHT) {
|
||||
// Player hit!
|
||||
enemy_bullet_active[i] = false;
|
||||
lives--;
|
||||
|
||||
// Update lives display
|
||||
auto style = *ui::Theme::getInstance()->fg_green;
|
||||
painter.fill_rectangle({5, 30, 100, 20}, Color::black());
|
||||
painter.draw_string({5, 30}, style, "Lives: " + std::to_string(lives));
|
||||
|
||||
if (lives <= 0) {
|
||||
game_state = 2; // Game over
|
||||
save_high_score();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void update_invaders() {
|
||||
uint32_t adjusted_delay = (speed_bonus >= invader_move_delay) ? 1 : invader_move_delay - speed_bonus;
|
||||
|
||||
if (++invader_move_counter >= adjusted_delay) {
|
||||
invader_move_counter = 0;
|
||||
|
||||
// Clear old positions
|
||||
clear_all_invaders();
|
||||
|
||||
// Check bounds - find the actual leftmost and rightmost invaders
|
||||
int leftmost = INVADER_COLS;
|
||||
int rightmost = -1;
|
||||
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
if (invaders[row][col]) {
|
||||
if (col < leftmost) leftmost = col;
|
||||
if (col > rightmost) rightmost = col;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool hit_edge = false;
|
||||
if (invader_direction > 0) {
|
||||
// Moving right - check rightmost invader
|
||||
int right_edge = invaders_x + rightmost * (INVADER_WIDTH + INVADER_GAP_X) + INVADER_WIDTH;
|
||||
if (right_edge >= 240) {
|
||||
hit_edge = true;
|
||||
}
|
||||
} else {
|
||||
// Moving left - check leftmost invader
|
||||
int left_edge = invaders_x + leftmost * (INVADER_WIDTH + INVADER_GAP_X);
|
||||
if (left_edge <= 0) {
|
||||
hit_edge = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Move invaders
|
||||
if (hit_edge) {
|
||||
invaders_y += 15; // Move down
|
||||
invader_direction = -invader_direction;
|
||||
} else {
|
||||
invaders_x += invader_direction * 8; // Horizontal movement
|
||||
}
|
||||
|
||||
// Toggle animation frame
|
||||
invader_animation_frame = !invader_animation_frame;
|
||||
|
||||
// Draw new positions
|
||||
draw_all_invaders();
|
||||
}
|
||||
|
||||
// Enemy firing logic - only in hard mode or always with lower frequency
|
||||
if (!current_instance || !current_instance->easy_mode) {
|
||||
if (++enemy_fire_counter >= 120) { // Fire every 2 seconds at 60fps
|
||||
enemy_fire_counter = 0;
|
||||
fire_enemy_bullet();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void fire_bullet() {
|
||||
for (int i = 0; i < MAX_BULLETS; i++) {
|
||||
if (!bullet_active[i]) {
|
||||
bullet_active[i] = true;
|
||||
bullet_x[i] = player_x + PLAYER_WIDTH / 2 - BULLET_WIDTH / 2;
|
||||
bullet_y[i] = PLAYER_Y - BULLET_HEIGHT;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void update_bullets() {
|
||||
for (int i = 0; i < MAX_BULLETS; i++) {
|
||||
if (bullet_active[i]) {
|
||||
painter.fill_rectangle({bullet_x[i], bullet_y[i], BULLET_WIDTH, BULLET_HEIGHT}, Color::black());
|
||||
|
||||
bullet_y[i] -= BULLET_SPEED;
|
||||
|
||||
if (bullet_y[i] < 50) {
|
||||
bullet_active[i] = false;
|
||||
} else {
|
||||
painter.fill_rectangle({bullet_x[i], bullet_y[i], BULLET_WIDTH, BULLET_HEIGHT}, Color::white());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void check_collisions() {
|
||||
for (int i = 0; i < MAX_BULLETS; i++) {
|
||||
if (!bullet_active[i]) continue;
|
||||
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
if (!invaders[row][col]) continue;
|
||||
|
||||
int inv_x = invaders_x + col * (INVADER_WIDTH + INVADER_GAP_X);
|
||||
int inv_y = invaders_y + row * (INVADER_HEIGHT + INVADER_GAP_Y);
|
||||
|
||||
// Simple collision check
|
||||
if (bullet_x[i] < inv_x + INVADER_WIDTH &&
|
||||
bullet_x[i] + BULLET_WIDTH > inv_x &&
|
||||
bullet_y[i] < inv_y + INVADER_HEIGHT &&
|
||||
bullet_y[i] + BULLET_HEIGHT > inv_y) {
|
||||
// Hit!
|
||||
bullet_active[i] = false;
|
||||
painter.fill_rectangle({bullet_x[i], bullet_y[i], BULLET_WIDTH, BULLET_HEIGHT}, Color::black());
|
||||
|
||||
invaders[row][col] = false;
|
||||
painter.fill_rectangle({inv_x, inv_y, INVADER_WIDTH, INVADER_HEIGHT}, Color::black());
|
||||
|
||||
// Score based on row: top=30, middle=20, bottom=10
|
||||
if (row == 0) {
|
||||
score += 30;
|
||||
} else if (row == 1 || row == 2) {
|
||||
score += 20;
|
||||
} else {
|
||||
score += 10;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void check_wave_complete() {
|
||||
// Check if all invaders are destroyed
|
||||
bool all_destroyed = true;
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
if (invaders[row][col]) {
|
||||
all_destroyed = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!all_destroyed) break;
|
||||
}
|
||||
|
||||
if (all_destroyed) {
|
||||
// Next wave!
|
||||
wave++;
|
||||
speed_bonus = (wave - 1) * 3; // Each wave is slightly faster
|
||||
if (speed_bonus > 15) speed_bonus = 15; // Cap the speed increase
|
||||
|
||||
// Clear any enemy bullets before transitioning
|
||||
clear_all_enemy_bullets();
|
||||
|
||||
// Set state to wave complete and start timer
|
||||
game_state = 3;
|
||||
wave_complete_timer = 60; // 1 second at 60fps
|
||||
|
||||
// Clear screen and show wave message - but preserve the border line
|
||||
painter.fill_rectangle({0, 51, 240, 269}, Color::black()); // Start at 51 to preserve line at 49
|
||||
|
||||
// Redraw the border line to ensure it's intact - stupid bullet clearing wants to damage it
|
||||
painter.draw_hline({0, 49}, 240, Color::white());
|
||||
|
||||
auto style = *ui::Theme::getInstance()->fg_green;
|
||||
std::string wave_text = "WAVE " + std::to_string(wave);
|
||||
int wave_x = (240 - wave_text.length() * 8) / 2;
|
||||
painter.draw_string({wave_x, 150}, style, wave_text);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if invaders reached player
|
||||
for (int row = 0; row < INVADER_ROWS; row++) {
|
||||
for (int col = 0; col < INVADER_COLS; col++) {
|
||||
if (invaders[row][col]) {
|
||||
int y = invaders_y + row * (INVADER_HEIGHT + INVADER_GAP_Y);
|
||||
if (y + INVADER_HEIGHT >= PLAYER_Y) { // Actual collision with player
|
||||
game_state = 2; // Game over
|
||||
save_high_score();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void game_timer_check() {
|
||||
if (game_state == 0) {
|
||||
// Menu state
|
||||
if (!menu_initialized) {
|
||||
init_menu();
|
||||
}
|
||||
|
||||
if (++blink_counter >= 30) {
|
||||
blink_counter = 0;
|
||||
blink_state = !blink_state;
|
||||
|
||||
auto style = *ui::Theme::getInstance()->fg_red;
|
||||
if (blink_state) {
|
||||
painter.draw_string({prompt_x, 260}, style, "PRESS SELECT");
|
||||
} else {
|
||||
painter.fill_rectangle({prompt_x, 260, 16 * 8, 20}, Color::black());
|
||||
}
|
||||
}
|
||||
} else if (game_state == 1) {
|
||||
// Playing state
|
||||
update_bullets();
|
||||
update_enemy_bullets();
|
||||
update_invaders();
|
||||
check_collisions();
|
||||
check_wave_complete();
|
||||
|
||||
// Update score display
|
||||
static uint32_t last_score = 999999;
|
||||
if (score != last_score) {
|
||||
last_score = score;
|
||||
auto style = *ui::Theme::getInstance()->fg_green;
|
||||
painter.fill_rectangle({5, 10, 100, 20}, Color::black());
|
||||
painter.draw_string({5, 10}, style, "Score: " + std::to_string(score));
|
||||
|
||||
// Redraw border line after score update (in case it was damaged) - stupid bullet clearing wants to damage it
|
||||
painter.draw_hline({0, 49}, 240, Color::white());
|
||||
}
|
||||
|
||||
// Periodically redraw the border line to fix any damage because it's a pain in the ass
|
||||
static uint32_t border_redraw_counter = 0;
|
||||
if (++border_redraw_counter >= 60) { // Once per second - might make less if causing flickering
|
||||
border_redraw_counter = 0;
|
||||
painter.draw_hline({0, 49}, 240, Color::white());
|
||||
}
|
||||
} else if (game_state == 2) {
|
||||
// Game over state
|
||||
if (!game_over_initialized) {
|
||||
init_game_over();
|
||||
}
|
||||
|
||||
if (++blink_counter >= 30) {
|
||||
blink_counter = 0;
|
||||
blink_state = !blink_state;
|
||||
|
||||
auto style = *ui::Theme::getInstance()->fg_red;
|
||||
if (blink_state) {
|
||||
painter.draw_string({prompt_x, 260}, style, "PRESS SELECT");
|
||||
} else {
|
||||
painter.fill_rectangle({prompt_x, 260, 16 * 8, 20}, Color::black());
|
||||
}
|
||||
}
|
||||
} else if (game_state == 3) {
|
||||
// Wave complete state - wait for timer
|
||||
if (--wave_complete_timer <= 0) {
|
||||
// Timer expired, start next wave
|
||||
game_state = 1;
|
||||
|
||||
// Clear and redraw game area - preserve border line
|
||||
painter.fill_rectangle({0, 51, 240, 269}, Color::black()); // Start at 51 to preserve line
|
||||
|
||||
// Restore UI
|
||||
auto style = *ui::Theme::getInstance()->fg_green;
|
||||
painter.draw_string({5, 10}, style, "Score: " + std::to_string(score));
|
||||
painter.draw_string({5, 30}, style, "Lives: " + std::to_string(lives));
|
||||
|
||||
// Redraw the border line in case it was damaged again
|
||||
painter.draw_hline({0, 49}, 240, Color::white());
|
||||
|
||||
// Initialize new wave of invaders
|
||||
init_invaders();
|
||||
draw_all_invaders();
|
||||
draw_player();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SpaceInvadersView::SpaceInvadersView(NavigationView& nav)
|
||||
: nav_{nav} {
|
||||
add_children({&dummy, &button_difficulty});
|
||||
current_instance = this;
|
||||
game_timer.attach(&game_timer_check, 1.0 / 60.0);
|
||||
|
||||
// Update button text based on loaded setting
|
||||
button_difficulty.set_text(easy_mode ? "Mode: EASY" : "Mode: HARD");
|
||||
|
||||
button_difficulty.on_select = [this](Button&) {
|
||||
easy_mode = !easy_mode;
|
||||
button_difficulty.set_text(easy_mode ? "Mode: EASY" : "Mode: HARD");
|
||||
// Settings will be saved when the view is destroyed
|
||||
};
|
||||
}
|
||||
|
||||
SpaceInvadersView::~SpaceInvadersView() {
|
||||
// Settings are automatically saved when destroyed
|
||||
current_instance = nullptr;
|
||||
}
|
||||
|
||||
void SpaceInvadersView::on_show() {
|
||||
}
|
||||
|
||||
void SpaceInvadersView::paint(Painter& painter) {
|
||||
(void)painter;
|
||||
|
||||
if (!initialized) {
|
||||
initialized = true;
|
||||
game_state = 0;
|
||||
menu_initialized = false;
|
||||
game_over_initialized = false;
|
||||
blink_state = true;
|
||||
blink_counter = 0;
|
||||
player_x = 107;
|
||||
score = 0;
|
||||
lives = 3;
|
||||
wave = 1;
|
||||
speed_bonus = 0;
|
||||
|
||||
// Initialize arrays
|
||||
for (int i = 0; i < MAX_BULLETS; i++) {
|
||||
bullet_active[i] = false;
|
||||
bullet_x[i] = 0;
|
||||
bullet_y[i] = 0;
|
||||
}
|
||||
|
||||
for (int i = 0; i < MAX_ENEMY_BULLETS; i++) {
|
||||
enemy_bullet_active[i] = false;
|
||||
enemy_bullet_x[i] = 0;
|
||||
enemy_bullet_y[i] = 0;
|
||||
}
|
||||
|
||||
init_invaders();
|
||||
}
|
||||
}
|
||||
|
||||
void SpaceInvadersView::frame_sync() {
|
||||
check_game_timer();
|
||||
set_dirty();
|
||||
}
|
||||
|
||||
bool SpaceInvadersView::on_encoder(const EncoderEvent delta) {
|
||||
if (game_state == 1) {
|
||||
if (delta > 0) {
|
||||
player_x += 5;
|
||||
if (player_x > 214) player_x = 214;
|
||||
draw_player();
|
||||
} else if (delta < 0) {
|
||||
player_x -= 5;
|
||||
if (player_x < 0) player_x = 0;
|
||||
draw_player();
|
||||
}
|
||||
|
||||
set_dirty();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SpaceInvadersView::on_key(const KeyEvent key) {
|
||||
if (key == KeyEvent::Select) {
|
||||
if (game_state == 0) {
|
||||
// Start game
|
||||
game_state = 1;
|
||||
button_difficulty.hidden(true);
|
||||
score = 0;
|
||||
lives = 3;
|
||||
wave = 1;
|
||||
speed_bonus = 0;
|
||||
invader_move_delay = 30;
|
||||
enemy_fire_counter = 0;
|
||||
init_invaders();
|
||||
|
||||
painter.fill_rectangle({0, 0, 240, 320}, Color::black());
|
||||
painter.draw_hline({0, 49}, 240, Color::white());
|
||||
|
||||
auto style = *ui::Theme::getInstance()->fg_green;
|
||||
painter.draw_string({5, 10}, style, "Score: 0");
|
||||
painter.draw_string({5, 30}, style, "Lives: 3");
|
||||
|
||||
draw_all_invaders();
|
||||
draw_player();
|
||||
|
||||
set_dirty();
|
||||
} else if (game_state == 1) {
|
||||
fire_bullet();
|
||||
} else if (game_state == 2) {
|
||||
// Return to menu
|
||||
game_state = 0;
|
||||
menu_initialized = false;
|
||||
game_over_initialized = false;
|
||||
button_difficulty.hidden(false);
|
||||
set_dirty();
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ui::external_app::spaceinv
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* ------------------------------------------------------------
|
||||
* | Made by RocketGod |
|
||||
* | Find me at https://betaskynet.com |
|
||||
* | Argh matey! |
|
||||
* ------------------------------------------------------------
|
||||
*/
|
||||
|
||||
#ifndef __UI_SPACEINV_H__
|
||||
#define __UI_SPACEINV_H__
|
||||
|
||||
#include "ui.hpp"
|
||||
#include "ui_navigation.hpp"
|
||||
#include "event_m0.hpp"
|
||||
#include "message.hpp"
|
||||
#include "irq_controls.hpp"
|
||||
#include "random.hpp"
|
||||
#include "lpc43xx_cpp.hpp"
|
||||
#include "ui_widget.hpp"
|
||||
#include "app_settings.hpp"
|
||||
|
||||
namespace ui::external_app::spaceinv {
|
||||
|
||||
using Callback = void (*)(void);
|
||||
|
||||
class Ticker {
|
||||
public:
|
||||
Ticker() = default;
|
||||
void attach(Callback func, double delay_sec);
|
||||
void detach();
|
||||
};
|
||||
|
||||
void check_game_timer();
|
||||
void game_timer_check();
|
||||
|
||||
class SpaceInvadersView : public View {
|
||||
public:
|
||||
SpaceInvadersView(NavigationView& nav);
|
||||
~SpaceInvadersView(); // Destructor will trigger settings save
|
||||
void on_show() override;
|
||||
|
||||
std::string title() const override { return "Space Invaders"; }
|
||||
|
||||
void focus() override { dummy.focus(); }
|
||||
void paint(Painter& painter) override;
|
||||
void frame_sync();
|
||||
bool on_encoder(const EncoderEvent event) override;
|
||||
bool on_key(KeyEvent key) override;
|
||||
|
||||
uint32_t highScore = 0;
|
||||
bool easy_mode = false;
|
||||
|
||||
private:
|
||||
NavigationView& nav_;
|
||||
|
||||
Button button_difficulty{
|
||||
{70, 285, 100, 20},
|
||||
"Mode: HARD"};
|
||||
|
||||
app_settings::SettingsManager settings_{
|
||||
"spaceinv",
|
||||
app_settings::Mode::NO_RF,
|
||||
{{"highscore"sv, &highScore},
|
||||
{"easy_mode"sv, &easy_mode}}};
|
||||
|
||||
Button dummy{
|
||||
{240, 0, 0, 0},
|
||||
""};
|
||||
|
||||
MessageHandlerRegistration message_handler_frame_sync{
|
||||
Message::ID::DisplayFrameSync,
|
||||
[this](const Message* const) {
|
||||
this->frame_sync();
|
||||
}};
|
||||
};
|
||||
|
||||
} // namespace ui::external_app::spaceinv
|
||||
|
||||
#endif /* __UI_SPACEINV_H__ */
|
||||
@@ -28,10 +28,10 @@ Optional<File::Error> LogFile::write_entry(const std::string& entry) {
|
||||
|
||||
Optional<File::Error> LogFile::write_entry(const rtc::RTC& datetime, const std::string& entry) {
|
||||
std::string timestamp = to_string_timestamp(datetime);
|
||||
return write_line(timestamp + " " + entry);
|
||||
return write_raw(timestamp + " " + entry);
|
||||
}
|
||||
|
||||
Optional<File::Error> LogFile::write_line(const std::string& message) {
|
||||
Optional<File::Error> LogFile::write_raw(const std::string& message) {
|
||||
auto error = file.write_line(message);
|
||||
if (!error) {
|
||||
file.sync();
|
||||
|
||||
@@ -39,11 +39,10 @@ class LogFile {
|
||||
|
||||
Optional<File::Error> write_entry(const std::string& entry);
|
||||
Optional<File::Error> write_entry(const rtc::RTC& datetime, const std::string& entry);
|
||||
Optional<File::Error> write_raw(const std::string& message);
|
||||
|
||||
private:
|
||||
File file{};
|
||||
|
||||
Optional<File::Error> write_line(const std::string& message);
|
||||
};
|
||||
|
||||
#endif /*__LOG_FILE_H__*/
|
||||
|
||||
+121
-127
@@ -27,6 +27,15 @@
|
||||
|
||||
#include "event_m4.hpp"
|
||||
|
||||
float BTLERxProcessor::get_phase_diff(const complex16_t& sample0, const complex16_t& sample1) {
|
||||
// Calculate the phase difference between two samples.
|
||||
float dI = sample1.real() * sample0.real() + sample1.imag() * sample0.imag();
|
||||
float dQ = sample1.imag() * sample0.real() - sample1.real() * sample0.imag();
|
||||
float phase_diff = atan2f(dQ, dI);
|
||||
|
||||
return phase_diff;
|
||||
}
|
||||
|
||||
uint32_t BTLERxProcessor::crc_init_reorder(uint32_t crc_init) {
|
||||
int i;
|
||||
uint32_t crc_init_tmp, crc_init_input, crc_init_input_tmp;
|
||||
@@ -122,120 +131,111 @@ int BTLERxProcessor::verify_payload_byte(int num_payload_byte, ADV_PDU_TYPE pdu_
|
||||
return 0;
|
||||
}
|
||||
|
||||
void BTLERxProcessor::resetOffsetTracking() {
|
||||
frequency_offset = 0.0f;
|
||||
frequency_offset_estimate = 0.0f;
|
||||
phase_buffer_index = 0;
|
||||
memset(phase_buffer, 0, sizeof(phase_buffer));
|
||||
}
|
||||
|
||||
void BTLERxProcessor::resetBitPacketIndex() {
|
||||
memset(rb_buf, 0, sizeof(rb_buf));
|
||||
packet_index = 0;
|
||||
bit_index = 0;
|
||||
}
|
||||
|
||||
void BTLERxProcessor::resetToDefaultState() {
|
||||
parseState = Parse_State_Begin;
|
||||
resetOffsetTracking();
|
||||
resetBitPacketIndex();
|
||||
}
|
||||
|
||||
void BTLERxProcessor::demodulateFSKBits(int num_demod_byte) {
|
||||
for (; packet_index < num_demod_byte; packet_index++) {
|
||||
for (; bit_index < 8; bit_index++) {
|
||||
if (samples_eaten >= (int)dst_buffer.count) {
|
||||
return;
|
||||
}
|
||||
|
||||
float phaseSum = 0.0f;
|
||||
for (int k = 0; k < SAMPLE_PER_SYMBOL; ++k) {
|
||||
float phase = get_phase_diff(
|
||||
dst_buffer.p[samples_eaten + k],
|
||||
dst_buffer.p[samples_eaten + k + 1]);
|
||||
phaseSum += phase;
|
||||
}
|
||||
|
||||
// phaseSum /= (SAMPLE_PER_SYMBOL);
|
||||
// phaseSum -= frequency_offset;
|
||||
|
||||
bool bitDecision = (phaseSum > 0.0f);
|
||||
rb_buf[packet_index] = rb_buf[packet_index] | (bitDecision << bit_index);
|
||||
|
||||
samples_eaten += SAMPLE_PER_SYMBOL;
|
||||
}
|
||||
|
||||
bit_index = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void BTLERxProcessor::handleBeginState() {
|
||||
int num_symbol_left = dst_buffer.count / SAMPLE_PER_SYMBOL; // One buffer sample consist of I and Q.
|
||||
|
||||
static uint8_t demod_buf_access[SAMPLE_PER_SYMBOL][LEN_DEMOD_BUF_ACCESS];
|
||||
|
||||
uint32_t uint32_tmp = DEFAULT_ACCESS_ADDR;
|
||||
uint8_t accessAddrBits[LEN_DEMOD_BUF_ACCESS];
|
||||
|
||||
uint32_t validAccessAddress = DEFAULT_ACCESS_ADDR;
|
||||
uint32_t accesssAddress = 0;
|
||||
|
||||
// Filling up addressBits with the access address we are looking to find.
|
||||
for (int i = 0; i < 32; i++) {
|
||||
accessAddrBits[i] = 0x01 & uint32_tmp;
|
||||
uint32_tmp = (uint32_tmp >> 1);
|
||||
}
|
||||
|
||||
const int demod_buf_len = LEN_DEMOD_BUF_ACCESS; // For AA
|
||||
int demod_buf_offset = 0;
|
||||
int hit_idx = (-1);
|
||||
bool unequal_flag = false;
|
||||
|
||||
memset(demod_buf_access, 0, SAMPLE_PER_SYMBOL * demod_buf_len);
|
||||
|
||||
for (int i = 0; i < num_symbol_left * SAMPLE_PER_SYMBOL; i += SAMPLE_PER_SYMBOL) {
|
||||
int sp = ((demod_buf_offset - demod_buf_len + 1) & (demod_buf_len - 1));
|
||||
for (int i = samples_eaten; i < (int)dst_buffer.count; i += SAMPLE_PER_SYMBOL) {
|
||||
float phaseDiff = 0;
|
||||
|
||||
for (int j = 0; j < SAMPLE_PER_SYMBOL; j++) {
|
||||
// Sample and compare with the adjacent next sample.
|
||||
int I0 = dst_buffer.p[i + j].real();
|
||||
int Q0 = dst_buffer.p[i + j].imag();
|
||||
int I1 = dst_buffer.p[i + j + 1].real();
|
||||
int Q1 = dst_buffer.p[i + j + 1].imag();
|
||||
|
||||
int phase_idx = j;
|
||||
|
||||
demod_buf_access[phase_idx][demod_buf_offset] = (I0 * Q1 - I1 * Q0) > 0 ? 1 : 0;
|
||||
|
||||
int k = sp;
|
||||
unequal_flag = false;
|
||||
|
||||
accesssAddress = 0;
|
||||
|
||||
for (int p = 0; p < demod_buf_len; p++) {
|
||||
if (demod_buf_access[phase_idx][k] != accessAddrBits[p]) {
|
||||
unequal_flag = true;
|
||||
hit_idx = (-1);
|
||||
break;
|
||||
}
|
||||
|
||||
accesssAddress = (accesssAddress & (~(1 << p))) | (demod_buf_access[phase_idx][k] << p);
|
||||
|
||||
k = ((k + 1) & (demod_buf_len - 1));
|
||||
}
|
||||
|
||||
if (unequal_flag == false) {
|
||||
hit_idx = (i + j - (demod_buf_len - 1) * SAMPLE_PER_SYMBOL);
|
||||
break;
|
||||
}
|
||||
phaseDiff += get_phase_diff(dst_buffer.p[i + j], dst_buffer.p[i + j + 1]);
|
||||
}
|
||||
|
||||
if (unequal_flag == false) {
|
||||
phase_buffer[phase_buffer_index] = phaseDiff / (SAMPLE_PER_SYMBOL);
|
||||
phase_buffer_index = (phase_buffer_index + 1) % ROLLING_WINDOW;
|
||||
|
||||
bool bitDecision = (phaseDiff > 0);
|
||||
|
||||
accesssAddress = (accesssAddress >> 1 | (bitDecision << 31));
|
||||
|
||||
int errors = __builtin_popcount(accesssAddress ^ validAccessAddress) & 0xFFFFFFFF;
|
||||
|
||||
if (errors <= 4) {
|
||||
hit_idx = i + SAMPLE_PER_SYMBOL;
|
||||
|
||||
for (int k = 0; k < ROLLING_WINDOW; k++) {
|
||||
frequency_offset_estimate += phase_buffer[k];
|
||||
}
|
||||
|
||||
frequency_offset = frequency_offset_estimate / ROLLING_WINDOW;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
demod_buf_offset = ((demod_buf_offset + 1) & (demod_buf_len - 1));
|
||||
}
|
||||
|
||||
if (hit_idx == -1) {
|
||||
// Process more samples.
|
||||
samples_eaten = dst_buffer.count + 1;
|
||||
return;
|
||||
}
|
||||
|
||||
symbols_eaten += hit_idx;
|
||||
|
||||
symbols_eaten += (8 * NUM_ACCESS_ADDR_BYTE * SAMPLE_PER_SYMBOL); // move to the beginning of PDU header
|
||||
|
||||
num_symbol_left = num_symbol_left - symbols_eaten;
|
||||
samples_eaten += hit_idx;
|
||||
|
||||
parseState = Parse_State_PDU_Header;
|
||||
}
|
||||
|
||||
void BTLERxProcessor::handlePDUHeaderState() {
|
||||
int num_demod_byte = 2; // PDU header has 2 octets
|
||||
|
||||
symbols_eaten += 8 * num_demod_byte * SAMPLE_PER_SYMBOL;
|
||||
|
||||
if (symbols_eaten > (int)dst_buffer.count) {
|
||||
if (samples_eaten > (int)dst_buffer.count) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Jump back down to the beginning of PDU header.
|
||||
sample_idx = symbols_eaten - (8 * num_demod_byte * SAMPLE_PER_SYMBOL);
|
||||
demodulateFSKBits(NUM_PDU_HEADER_BYTE);
|
||||
|
||||
packet_index = 0;
|
||||
|
||||
for (int i = 0; i < num_demod_byte; i++) {
|
||||
rb_buf[packet_index] = 0;
|
||||
|
||||
for (int j = 0; j < 8; j++) {
|
||||
int I0 = dst_buffer.p[sample_idx].real();
|
||||
int Q0 = dst_buffer.p[sample_idx].imag();
|
||||
int I1 = dst_buffer.p[sample_idx + 1].real();
|
||||
int Q1 = dst_buffer.p[sample_idx + 1].imag();
|
||||
|
||||
bit_decision = (I0 * Q1 - I1 * Q0) > 0 ? 1 : 0;
|
||||
rb_buf[packet_index] = rb_buf[packet_index] | (bit_decision << j);
|
||||
|
||||
sample_idx += SAMPLE_PER_SYMBOL;
|
||||
}
|
||||
|
||||
packet_index++;
|
||||
if (packet_index < NUM_PDU_HEADER_BYTE || bit_index != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
scramble_byte(rb_buf, num_demod_byte, scramble_table[channel_number], rb_buf);
|
||||
scramble_byte(rb_buf, 2, scramble_table[channel_number], rb_buf);
|
||||
|
||||
pdu_type = (ADV_PDU_TYPE)(rb_buf[0] & 0x0F);
|
||||
// uint8_t tx_add = ((rb_buf[0] & 0x40) != 0);
|
||||
@@ -252,30 +252,16 @@ void BTLERxProcessor::handlePDUHeaderState() {
|
||||
}
|
||||
|
||||
void BTLERxProcessor::handlePDUPayloadState() {
|
||||
int i;
|
||||
int num_demod_byte = (payload_len + 3);
|
||||
symbols_eaten += 8 * num_demod_byte * SAMPLE_PER_SYMBOL;
|
||||
const int num_demod_byte = (payload_len + 3);
|
||||
|
||||
if (symbols_eaten > (int)dst_buffer.count) {
|
||||
if (samples_eaten > (int)dst_buffer.count) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (i = 0; i < num_demod_byte; i++) {
|
||||
rb_buf[packet_index] = 0;
|
||||
demodulateFSKBits(num_demod_byte + NUM_PDU_HEADER_BYTE);
|
||||
|
||||
for (int j = 0; j < 8; j++) {
|
||||
int I0 = dst_buffer.p[sample_idx].real();
|
||||
int Q0 = dst_buffer.p[sample_idx].imag();
|
||||
int I1 = dst_buffer.p[sample_idx + 1].real();
|
||||
int Q1 = dst_buffer.p[sample_idx + 1].imag();
|
||||
|
||||
bit_decision = (I0 * Q1 - I1 * Q0) > 0 ? 1 : 0;
|
||||
rb_buf[packet_index] = rb_buf[packet_index] | (bit_decision << j);
|
||||
|
||||
sample_idx += SAMPLE_PER_SYMBOL;
|
||||
}
|
||||
|
||||
packet_index++;
|
||||
if (packet_index < (num_demod_byte + NUM_PDU_HEADER_BYTE) || bit_index != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
scramble_byte(rb_buf + 2, num_demod_byte, scramble_table[channel_number] + 2, rb_buf + 2);
|
||||
@@ -310,6 +296,8 @@ void BTLERxProcessor::handlePDUPayloadState() {
|
||||
// Skip Header Byte and MAC Address
|
||||
uint8_t startIndex = 8;
|
||||
|
||||
int i;
|
||||
|
||||
for (i = 0; i < payload_len - 6; i++) {
|
||||
blePacketData.data[i] = rb_buf[startIndex++];
|
||||
}
|
||||
@@ -322,46 +310,52 @@ void BTLERxProcessor::handlePDUPayloadState() {
|
||||
}
|
||||
}
|
||||
|
||||
parseState = Parse_State_Begin;
|
||||
resetToDefaultState();
|
||||
}
|
||||
|
||||
void BTLERxProcessor::execute(const buffer_c8_t& buffer) {
|
||||
if (!configured) return;
|
||||
|
||||
// Pulled this implementation from channel_stats_collector.c to time slice a specific packet's dB.
|
||||
uint32_t max_squared = 0;
|
||||
max_dB = -128;
|
||||
|
||||
void* src_p = buffer.p;
|
||||
real = -128;
|
||||
imag = -128;
|
||||
|
||||
while (src_p < &buffer.p[buffer.count]) {
|
||||
const uint32_t sample = *__SIMD32(src_p)++;
|
||||
const uint32_t mag_sq = __SMUAD(sample, sample);
|
||||
if (mag_sq > max_squared) {
|
||||
max_squared = mag_sq;
|
||||
auto* ptr = buffer.p;
|
||||
auto* end = &buffer.p[buffer.count];
|
||||
|
||||
while (ptr < end) {
|
||||
float dbm = mag2_to_dbm_8bit_normalized(ptr->real(), ptr->imag(), 1.0f, 50.0f);
|
||||
|
||||
if (dbm > max_dB) {
|
||||
max_dB = dbm;
|
||||
real = ptr->real();
|
||||
imag = ptr->imag();
|
||||
}
|
||||
}
|
||||
|
||||
const float max_squared_f = max_squared;
|
||||
max_dB = mag2_to_dbv_norm(max_squared_f * (1.0f / (32768.0f * 32768.0f)));
|
||||
ptr++;
|
||||
}
|
||||
|
||||
// 4Mhz 2048 samples
|
||||
// Decimated by 4 to achieve 2048/4 = 512 samples at 1 sample per symbol.
|
||||
decim_0.execute(buffer, dst_buffer);
|
||||
feed_channel_stats(dst_buffer);
|
||||
|
||||
symbols_eaten = 0;
|
||||
samples_eaten = 0;
|
||||
|
||||
// Handle parsing based on parseState
|
||||
if (parseState == Parse_State_Begin) {
|
||||
handleBeginState();
|
||||
}
|
||||
while (samples_eaten < (int)dst_buffer.count) {
|
||||
// Handle parsing based on parseState
|
||||
if (parseState == Parse_State_Begin) {
|
||||
handleBeginState();
|
||||
}
|
||||
|
||||
if (parseState == Parse_State_PDU_Header) {
|
||||
handlePDUHeaderState();
|
||||
}
|
||||
if (parseState == Parse_State_PDU_Header) {
|
||||
handlePDUHeaderState();
|
||||
}
|
||||
|
||||
if (parseState == Parse_State_PDU_Payload) {
|
||||
handlePDUPayloadState();
|
||||
if (parseState == Parse_State_PDU_Payload) {
|
||||
handlePDUPayloadState();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,7 +366,7 @@ void BTLERxProcessor::on_message(const Message* const message) {
|
||||
|
||||
void BTLERxProcessor::configure(const BTLERxConfigureMessage& message) {
|
||||
channel_number = message.channel_number;
|
||||
decim_0.configure(taps_BTLE_1M_PHY_decim_0.taps);
|
||||
decim_0.configure(taps_BTLE_2M_PHY_decim_0.taps);
|
||||
|
||||
configured = true;
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ class BTLERxProcessor : public BasebandProcessor {
|
||||
static constexpr int LEN_DEMOD_BUF_ACCESS{32};
|
||||
static constexpr uint32_t DEFAULT_ACCESS_ADDR{0x8E89BED6};
|
||||
static constexpr int NUM_ACCESS_ADDR_BYTE{4};
|
||||
static constexpr int NUM_PDU_HEADER_BYTE{2};
|
||||
static constexpr int ROLLING_WINDOW{32};
|
||||
|
||||
enum Parse_State {
|
||||
Parse_State_Begin = 0,
|
||||
@@ -81,8 +83,8 @@ class BTLERxProcessor : public BasebandProcessor {
|
||||
};
|
||||
|
||||
static constexpr size_t baseband_fs = 4000000;
|
||||
static constexpr size_t audio_fs = baseband_fs / 8 / 8 / 2;
|
||||
|
||||
float get_phase_diff(const complex16_t& sample0, const complex16_t& sample1);
|
||||
uint_fast32_t crc_update(uint_fast32_t crc, const void* data, size_t data_len);
|
||||
uint_fast32_t crc24_byte(uint8_t* byte_in, int num_byte, uint32_t init_hex);
|
||||
bool crc_check(uint8_t* tmp_byte, int body_len, uint32_t crc_init);
|
||||
@@ -95,6 +97,12 @@ class BTLERxProcessor : public BasebandProcessor {
|
||||
// void demod_byte(int num_byte, uint8_t *out_byte);
|
||||
int verify_payload_byte(int num_payload_byte, ADV_PDU_TYPE pdu_type);
|
||||
|
||||
void resetOffsetTracking();
|
||||
void resetBitPacketIndex();
|
||||
void resetToDefaultState();
|
||||
|
||||
void demodulateFSKBits(int num_demod_byte);
|
||||
|
||||
void handleBeginState();
|
||||
void handlePDUHeaderState();
|
||||
void handlePDUPayloadState();
|
||||
@@ -120,13 +128,20 @@ class BTLERxProcessor : public BasebandProcessor {
|
||||
BlePacketData blePacketData{};
|
||||
|
||||
Parse_State parseState{Parse_State_Begin};
|
||||
uint16_t packet_index{0};
|
||||
int sample_idx{0};
|
||||
int symbols_eaten{0};
|
||||
int samples_eaten{0};
|
||||
uint8_t bit_decision{0};
|
||||
uint8_t payload_len{0};
|
||||
uint8_t pdu_type{0};
|
||||
int32_t max_dB{0};
|
||||
int8_t real{0};
|
||||
int8_t imag{0};
|
||||
uint16_t packet_index{0};
|
||||
uint8_t bit_index{0};
|
||||
|
||||
float frequency_offset_estimate{0.0f};
|
||||
float frequency_offset{0.0f};
|
||||
float phase_buffer[ROLLING_WINDOW] = {0.0f};
|
||||
int phase_buffer_index = 0;
|
||||
|
||||
/* NB: Threads should be the last members in the class definition. */
|
||||
BasebandThread baseband_thread{baseband_fs, this, baseband::Direction::Receive};
|
||||
|
||||
@@ -91,6 +91,26 @@ float mag2_to_dbv_norm(const float mag2) {
|
||||
return (fast_log2(mag2) - mag2_log2_max) * mag2_to_db_factor;
|
||||
}
|
||||
|
||||
// Function to calculate dBm and normalize based on LNA and VGA settings
|
||||
float mag2_to_dbm_8bit_normalized(int8_t real, int8_t imag, float v_ref, float R) {
|
||||
// Step 1: Normalize IQ values (convert 8-bit signed to -1.0 to +1.0)
|
||||
float I = real / 127.0f; // Map the 8-bit real part to the [-1, 1] range
|
||||
float Q = imag / 127.0f; // Map the 8-bit imaginary part to the [-1, 1] range
|
||||
|
||||
// Step 2: Compute the magnitude squared (I^2 + Q^2)
|
||||
float mag2 = I * I + Q * Q;
|
||||
|
||||
// Step 3: Convert the magnitude squared to actual power (in watts)
|
||||
float voltage_squared = mag2 * v_ref * v_ref;
|
||||
float power_watts = voltage_squared / R;
|
||||
|
||||
// Step 4: Convert the power to dBm (multiply by 1000 to convert watts to milliwatts)
|
||||
float power_milliwatts = power_watts * 1000.0f;
|
||||
float dbm_measured = 10.0f * log10f(power_milliwatts);
|
||||
|
||||
return dbm_measured;
|
||||
}
|
||||
|
||||
// Integer in and out approximation
|
||||
// >40 times faster float sqrt(x*x+y*y) on Cortex M0
|
||||
// derived from https://dspguru.com/dsp/tricks/magnitude-estimator/
|
||||
|
||||
@@ -90,6 +90,7 @@ float fast_log2(const float val);
|
||||
float fast_pow2(const float val);
|
||||
|
||||
float mag2_to_dbv_norm(const float mag2);
|
||||
float mag2_to_dbm_8bit_normalized(int8_t real, int8_t imag, float v_ref, float R);
|
||||
|
||||
inline float magnitude_squared(const std::complex<float> c) {
|
||||
const auto r = c.real();
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
Upgraded standard case<br>https://www.printables.com/model/1337429-upgraded-hackrf-portapack-h4h4m-case
|
||||
|
||||
|
||||
Upgraded 18650 version case<br>https://www.printables.com/model/1337451-18650-power-hackrf-portapack-h4m-case
|
||||
|
||||
Official case, made for injection molding. Can be 3D printed, but has very tight tolerances.<br>https://www.printables.com/model/1019145-official-hackrf-portapack-h4h4m-case/comments
|
||||
Reference in New Issue
Block a user