Contract Name:
DungeonGame
Contract Source Code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./interfaces/IDungeonGame.sol";
import "./interfaces/IDungeonEntry.sol";
import "./interfaces/INFTStats.sol";
import "./interfaces/IPrizePool.sol";
import "./libraries/EncounterLibrary.sol";
/// @title DungeonGame
/// @notice Core game logic for dungeon runs and encounters
contract DungeonGame is IDungeonGame, Ownable(msg.sender), ReentrancyGuard {
// Events
event FeesWithdrawn(address indexed owner, uint256 amount);
event DungeonEntered(
address indexed collection,
uint256 indexed tokenId,
uint256 indexed entryIndex
);
event CharacterSurvived(
address indexed collection,
uint256 indexed tokenId,
uint256 newHp,
uint256 xpGained
);
// Allow contract to receive native currency (for Pyth refunds)
receive() external payable {}
// Constants
uint8 public constant ROOM_COUNT = 16;
uint256 private constant BASE_XP = 100;
uint256 private constant COMPLETION_BONUS = 500;
CharacterState private emptyRoom =
CharacterState({collection: address(0), tokenId: 0, currentHp: 0});
// Core contract references
address public dungeonEntry;
address public immutable nftStats;
address public immutable prizePool;
uint256 public currentIndex = 0;
uint8 public startRoom = 0;
CharacterState[ROOM_COUNT] public rooms;
mapping(uint64 => CharacterState) private pendingEntries;
mapping(address => mapping(uint256 => uint256)) private characterEntryIndex;
constructor(address _dungeonEntry, address _nftStats, address _prizePool) {
require(_dungeonEntry != address(0), "Invalid DungeonEntry address");
require(_nftStats != address(0), "Invalid NFTStats address");
require(_prizePool != address(0), "Invalid PrizePool address");
dungeonEntry = _dungeonEntry;
nftStats = _nftStats;
prizePool = _prizePool;
}
/// @notice Get the state of a specific room
function getRoomState(
uint256 roomNumber
) external view returns (CharacterState memory) {
require(
roomNumber >= 0 && roomNumber <= ROOM_COUNT - 1,
"Invalid room number"
);
return rooms[roomNumber];
}
function getCharacterRoomNumber(
address collection,
uint256 tokenId
) public view returns (uint8) {
uint256 entryIndex = characterEntryIndex[collection][tokenId];
uint8 roomNumber = uint8(
(currentIndex - entryIndex + startRoom) % ROOM_COUNT
);
return roomNumber;
}
function getCharacterState(
address collection,
uint256 tokenId
) external view returns (CharacterState memory) {
uint8 roomNumber = getCharacterRoomNumber(collection, tokenId);
return rooms[roomNumber];
}
/// @notice Add a new character to the dungeon queue
/// @dev Only DungeonEntry can add characters
function enterDungeon(address collection, uint256 tokenId) external {
require(
msg.sender == address(dungeonEntry),
"Only DungeonEntry can add characters"
);
bytes32 randomNumber = keccak256(
abi.encodePacked(block.timestamp, block.prevrandao)
);
_processEntry(collection, tokenId, randomNumber);
}
/// @notice Process encounter
function _processEntry(
address collection,
uint256 tokenId,
bytes32 randomNumber
) internal {
// Push all characters forward one room, starting from the last room
for (uint8 i = 0; i < ROOM_COUNT; i++) {
uint8 roomIndex = (ROOM_COUNT + startRoom - 1 - i) % ROOM_COUNT;
CharacterState storage character = rooms[roomIndex];
// Skip empty rooms
if (character.collection == address(0)) {
continue;
}
EncounterLibrary.Encounter memory encounter = EncounterLibrary
.generateEncounter(
roomIndex + 1, // Add 1 since EncounterLibrary expects 1-based room numbers
uint256(randomNumber)
);
INFTStats.NFTStatsData memory characterStats = INFTStats(nftStats)
.getStats(character.collection, character.tokenId);
EncounterResult memory result = EncounterLibrary.processEncounter(
encounter,
characterStats
);
int256 newHp = int256(character.currentHp) + result.hpChange;
bool survived = newHp > 0;
// Calculate XP (partial XP if failed)
uint256 xpGained = survived
? encounter.baseXp
: encounter.baseXp / 2;
// Update character stats
if (survived) {
emit CharacterSurvived(
character.collection,
character.tokenId,
uint256(newHp),
xpGained
);
character.currentHp = uint256(newHp);
INFTStats(nftStats).awardXP(
character.collection,
character.tokenId,
xpGained,
1
);
}
// Only move if they survived the encounter
if (survived) {
if (roomIndex == ROOM_COUNT - 1) {
// Character completed the dungeon
_handleDungeonCompletion(
character.collection,
character.tokenId
);
}
} else {
// End the run in DungeonEntry
IDungeonEntry(dungeonEntry).endDungeonRun(
character.collection,
character.tokenId,
false
);
// Remove dead character
rooms[roomIndex] = CharacterState({
collection: address(0),
tokenId: 0,
currentHp: 0
});
}
}
INFTStats.NFTStatsData memory stats = INFTStats(nftStats).getStats(
collection,
tokenId
);
// Store the entry index for this character
characterEntryIndex[collection][tokenId] = currentIndex;
// Place the new character in the start room
rooms[startRoom] = CharacterState({
collection: collection,
tokenId: tokenId,
currentHp: stats.hp
});
emit DungeonEntered(collection, tokenId, currentIndex);
// Increment indices for next entry
startRoom = (startRoom + 1) % ROOM_COUNT;
currentIndex++;
}
function _handleDungeonCompletion(
address collection,
uint256 tokenId
) internal {
// Award completion bonus XP
INFTStats(nftStats).awardXP(
collection,
tokenId,
COMPLETION_BONUS,
ROOM_COUNT
);
// Clear the last room
rooms[ROOM_COUNT - 1] = emptyRoom;
IPrizePool(prizePool).registerWinner(collection, tokenId);
emit DungeonCompleted(collection, tokenId);
}
/// @notice Withdraw accumulated fees from Pyth refunds
/// @dev Only callable by contract owner
function withdrawFees() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "No fees to withdraw");
(bool success, ) = msg.sender.call{value: balance}("");
require(success, "Withdrawal failed");
emit FeesWithdrawn(msg.sender, balance);
}
function getPendingEntry(
uint64 sequenceNumber
) external view returns (CharacterState memory) {
return pendingEntries[sequenceNumber];
}
function setDungeonEntry(address _dungeonEntry) external onlyOwner {
require(_dungeonEntry != address(0), "Invalid dungeon entry address");
dungeonEntry = _dungeonEntry;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title IDungeonGame
/// @notice Interface for core dungeon game mechanics and progression
interface IDungeonGame {
/// @notice Structure for dungeon room state
struct RoomState {
address collection;
uint256 tokenId;
uint256 entryIndex; // Used for ordering characters
uint256 currentHp;
uint256 currentAttack;
uint256 currentSpeed;
bool isOccupied;
}
/// @notice Structure for encounter results
struct EncounterResult {
int256 hpChange;
string encounterDescription;
}
/// @notice Structure for character state
struct CharacterState {
address collection;
uint256 tokenId;
uint256 currentHp;
}
/// @notice Event emitted when an encounter is completed
event EncounterCompleted(
address indexed collection,
uint256 indexed tokenId,
uint256 roomNumber,
uint256 xpGained,
bool survived,
string encounterDescription
);
/// @notice Event emitted when a dungeon run is completed
event DungeonCompleted(
address indexed collection,
uint256 indexed tokenId
);
/// @notice Add a new character to the dungeon queue
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
function enterDungeon(address collection, uint256 tokenId) external;
/// @notice Get the current room number for a character
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @return Current room number
function getCharacterRoomNumber(address collection, uint256 tokenId) external view returns (uint8);
/// @notice Get the current room state for a character
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @return Current room state
function getCharacterState(address collection, uint256 tokenId) external view returns (CharacterState memory);
/// @notice Get the state of a specific room
/// @param roomNumber Room number to get state for
/// @return CharacterState Memory of the room state
function getRoomState(uint256 roomNumber) external view returns (CharacterState memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title IDungeonEntry
/// @notice Interface for managing dungeon entry and run initialization
interface IDungeonEntry {
/// @notice Structure for active dungeon run state
struct DungeonRun {
uint256 currentHp;
uint256 currentRoom;
bool isActive;
}
/// @notice Event emitted when a dungeon run is started
event DungeonRunStarted(
address indexed collection,
uint256 indexed tokenId,
address indexed player,
uint256 entryFee
);
/// @notice Event emitted when a dungeon run is ended
event DungeonRunEnded(
address indexed collection,
uint256 indexed tokenId,
bool success
);
/// @notice Start a new dungeon run for an NFT
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
function startDungeonRun(address collection, uint256 tokenId) external payable;
/// @notice End an active dungeon run (called by DungeonGame)
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @param success Whether the run was successful
function endDungeonRun(address collection, uint256 tokenId, bool success) external;
/// @notice Check if an NFT has an active dungeon run
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @return bool True if NFT has an active run
function hasActiveRun(address collection, uint256 tokenId) external view returns (bool);
/// @notice Get the current entry fee for dungeon runs
/// @return uint256 Current entry fee in wei
function getEntryFee() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title INFTStats
/// @notice Interface for managing individual NFT stats and progression
interface INFTStats {
/// @notice Structure for NFT permanent stats
struct NFTStatsData {
uint256 hp;
uint256 attack;
uint256 speed;
uint256 level;
uint256 currentXP;
uint256 xpToNextLevel;
uint256 dungeonRuns;
uint256 successfulRuns;
uint256 roomsCleared;
bool initialized;
}
/// @notice Event emitted when an NFT's stats are initialized
event StatsInitialized(address indexed collection, uint256 indexed tokenId, uint256 hp, uint256 attack, uint256 speed);
/// @notice Event emitted when an NFT's stats are boosted
event StatsBoosted(address indexed collection, uint256 indexed tokenId, uint256 newHp, uint256 newAttack, uint256 newSpeed);
/// @notice Event emitted when XP is gained
event XPGained(address indexed collection, uint256 indexed tokenId, uint256 xpGained, uint256 newTotalXP);
/// @notice Event emitted when a level up occurs
event LevelUp(address indexed collection, uint256 indexed tokenId, uint256 newLevel);
/// @notice Event emitted when a run is recorded
event RunRecorded(address indexed collection, uint256 indexed tokenId, bool success, uint256 roomsCleared, uint256 xpGained);
/// @notice Initialize stats for an NFT based on its collection's base stats
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
function initializeStats(address collection, uint256 tokenId) external;
/// @notice Award XP for dungeon progress
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @param xpAmount Amount of XP to award
/// @param roomsCleared Number of rooms cleared in this run
function awardXP(
address collection,
uint256 tokenId,
uint256 xpAmount,
uint256 roomsCleared
) external;
/// @notice Calculate XP required for next level
/// @param currentLevel Current level of the NFT
/// @return uint256 XP required for next level
function getXPForNextLevel(uint256 currentLevel) external pure returns (uint256);
/// @notice Get the stat increases for a level up
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @return hpIncrease Amount HP increases
/// @return attackIncrease Amount Attack increases
/// @return speedIncrease Amount Speed increases
function getLevelUpStats(
address collection,
uint256 tokenId
) external view returns (
uint256 hpIncrease,
uint256 attackIncrease,
uint256 speedIncrease
);
/// @notice Record a dungeon run attempt
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @param success Whether the run was successful
function recordRun(address collection, uint256 tokenId, bool success) external;
/// @notice Get current stats for an NFT
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @return NFTStatsData struct containing current stats
function getStats(address collection, uint256 tokenId) external view returns (NFTStatsData memory);
/// @notice Check if an NFT has been initialized
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
/// @return bool True if NFT has been initialized
function isInitialized(address collection, uint256 tokenId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title IPrizePool
/// @notice Interface for managing dungeon rewards and prize distribution
interface IPrizePool {
/// @notice Event emitted when entry fee is deposited
event EntryFeeDeposited(address indexed collection, uint256 indexed tokenId, uint256 amount);
/// @notice Event emitted when reward is claimed
event RewardClaimed(address indexed collection, uint256 indexed tokenId, address indexed recipient, uint256 amount);
/// @notice Event emitted when prize pool parameters are updated
event PrizePoolParametersUpdated(uint256 entryFee, uint256 winnerShare);
/// @notice Deposit entry fee for a dungeon run
function depositEntryFee() external payable;
/// @notice Register a winner and immediately transfer their prize
/// @param collection Address of the NFT collection
/// @param tokenId Token ID of the NFT
function registerWinner(address collection, uint256 tokenId) external;
/// @notice Get current prize pool amount
/// @return uint256 Current prize pool amount
function getCurrentPrizePool() external view returns (uint256);
/// @notice Gets the current entry fee
/// @return uint256 Current entry fee
function getEntryFee() external view returns (uint256);
/// @notice Gets total entry fees collected
/// @return uint256 Total entry fees
function getTotalEntryFees() external view returns (uint256);
/// @notice Gets total prizes paid out
/// @return uint256 Total prizes paid
function getTotalPrizesPaid() external view returns (uint256);
/// @notice Gets current treasury balance
/// @return uint256 Current treasury balance
function getTreasuryBalance() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../interfaces/IDungeonGame.sol";
import "../interfaces/INFTStats.sol";
/// @title EncounterLibrary
/// @notice Library for generating and processing dungeon encounters
library EncounterLibrary {
// Encounter types
enum EncounterType {
Combat, // Standard combat encounter
Trap, // Environmental hazard
Blessing, // Positive encounter
Elite, // Stronger combat encounter
Boss // Room 16 boss encounter
}
// Encounter definition
struct Encounter {
EncounterType encounterType;
uint256 difficulty; // 1-100 scale
int256 baseHpChange; // Base HP modification
int256 baseAttackMod; // Temporary attack modification
int256 baseSpeedMod; // Temporary speed modification
uint256 baseXp; // Base XP reward
string description; // Encounter description
}
// Constants for encounter generation
uint256 private constant BASE_DIFFICULTY_PER_ROOM = 6; // ~100 difficulty by room 16
uint256 private constant ELITE_CHANCE = 15; // 15% chance for elite encounter
uint256 private constant BLESSING_CHANCE = 10; // 10% chance for blessing
uint256 private constant TRAP_CHANCE = 20; // 20% chance for trap
// Constants for encounter effects
uint256 private constant BASE_DAMAGE = 20;
uint256 private constant ELITE_DAMAGE_MULTIPLIER = 2;
uint256 private constant BOSS_DAMAGE_MULTIPLIER = 3;
int256 private constant MAX_STAT_MODIFICATION = 50; // Maximum temporary stat change
/// @notice Generate an encounter for a specific room
/// @param roomNumber Current room number (1-16)
/// @param randomness Random number for encounter generation
/// @return Encounter struct with encounter details
function generateEncounter(
uint256 roomNumber,
uint256 randomness
) internal pure returns (Encounter memory) {
require(roomNumber > 0 && roomNumber <= 16, "Invalid room number");
// Room 16 is always a boss encounter
if (roomNumber == 16) {
return _generateBossEncounter();
}
// Use randomness to determine encounter type
uint256 encounterRoll = randomness % 100;
// Scale difficulty with room number
uint256 difficulty = BASE_DIFFICULTY_PER_ROOM * roomNumber;
// Select encounter type based on roll
if (encounterRoll < BLESSING_CHANCE) {
return _generateBlessing(roomNumber, difficulty);
} else if (encounterRoll < BLESSING_CHANCE + TRAP_CHANCE) {
return _generateTrap(roomNumber, difficulty);
} else if (encounterRoll < BLESSING_CHANCE + TRAP_CHANCE + ELITE_CHANCE) {
return _generateEliteEncounter(roomNumber, difficulty);
} else {
return _generateCombatEncounter(roomNumber, difficulty);
}
}
/// @notice Process an encounter for a character
/// @param encounter The encounter to process
/// @param characterStats Current character stats
/// @return IDungeonGame.EncounterResult Result of the encounter
function processEncounter(
Encounter memory encounter,
INFTStats.NFTStatsData memory characterStats
) internal pure returns (IDungeonGame.EncounterResult memory) {
// Calculate final HP change based on character stats
int256 hpChange = _calculateHpChange(encounter, characterStats);
return IDungeonGame.EncounterResult({
hpChange: hpChange,
encounterDescription: encounter.description
});
}
// Internal encounter generation functions
function _generateCombatEncounter(
uint256 roomNumber,
uint256 difficulty
) private pure returns (Encounter memory) {
int256 damage = -int256(BASE_DAMAGE + (difficulty / 2));
return Encounter({
encounterType: EncounterType.Combat,
difficulty: difficulty,
baseHpChange: damage,
baseAttackMod: 0,
baseSpeedMod: 0,
baseXp: 100 + (roomNumber * 10),
description: "A hostile enemy appears!"
});
}
function _generateEliteEncounter(
uint256 roomNumber,
uint256 difficulty
) private pure returns (Encounter memory) {
int256 damage = -int256((BASE_DAMAGE + (difficulty / 2)) * ELITE_DAMAGE_MULTIPLIER);
return Encounter({
encounterType: EncounterType.Elite,
difficulty: difficulty,
baseHpChange: damage,
baseAttackMod: int256(MAX_STAT_MODIFICATION / 2),
baseSpeedMod: -int256(MAX_STAT_MODIFICATION / 4),
baseXp: (150 + (roomNumber * 15)),
description: "An elite enemy blocks your path!"
});
}
function _generateBossEncounter() private pure returns (Encounter memory) {
return Encounter({
encounterType: EncounterType.Boss,
difficulty: 100,
baseHpChange: -int256(BASE_DAMAGE * BOSS_DAMAGE_MULTIPLIER),
baseAttackMod: -int256(MAX_STAT_MODIFICATION),
baseSpeedMod: -int256(MAX_STAT_MODIFICATION / 2),
baseXp: 1000,
description: "The dungeon boss emerges!"
});
}
function _generateBlessing(
uint256 roomNumber,
uint256 difficulty
) private pure returns (Encounter memory) {
return Encounter({
encounterType: EncounterType.Blessing,
difficulty: difficulty,
baseHpChange: int256(BASE_DAMAGE),
baseAttackMod: int256(MAX_STAT_MODIFICATION / 2),
baseSpeedMod: int256(MAX_STAT_MODIFICATION / 2),
baseXp: 50 + (roomNumber * 5),
description: "You discover a magical blessing!"
});
}
function _generateTrap(
uint256 roomNumber,
uint256 difficulty
) private pure returns (Encounter memory) {
return Encounter({
encounterType: EncounterType.Trap,
difficulty: difficulty,
baseHpChange: -int256(BASE_DAMAGE / 2),
baseAttackMod: -int256(MAX_STAT_MODIFICATION / 4),
baseSpeedMod: -int256(MAX_STAT_MODIFICATION / 4),
baseXp: 75 + (roomNumber * 7),
description: "You triggered a trap!"
});
}
// Internal helper functions
function _calculateHpChange(
Encounter memory encounter,
INFTStats.NFTStatsData memory characterStats
) private pure returns (int256) {
// Base damage
int256 hpChange = encounter.baseHpChange;
// Modify based on character stats
if (encounter.encounterType == EncounterType.Combat ||
encounter.encounterType == EncounterType.Elite ||
encounter.encounterType == EncounterType.Boss) {
// Higher attack reduces damage taken
uint256 attackMitigation = characterStats.attack / 10;
// Higher speed increases chance to dodge
uint256 speedMitigation = characterStats.speed / 20;
hpChange += int256(attackMitigation + speedMitigation);
}
return hpChange;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}