PokeWars: A Journey into Web3 Gaming
💡 Inspiration
The concept of PokeWars emerged from the intersection of three passions: competitive gaming, blockchain technology, and the nostalgic appeal of Pokémon battles. I envisioned a future of true digital ownership in gaming, where players genuinely own their in-game assets as NFTs rather than merely licensing them from game companies.
The concept was inspired by several key trends:
- Web3 Gaming Evolution: Observing projects like Axie Infinity and The Sandbox demonstrate that blockchain gaming could transcend pure speculation and deliver real value
- Real-Time Multiplayer Challenges: The technical complexity of building real-time multiplayer games fascinated me and pushed my skills forward
- Cross-Chain Interoperability: XCM (Cross-Consensus Message Format) presented an opportunity to innovate within the Polkadot ecosystem
I wanted to create a game that wasn't "blockchain for blockchain's sake" but genuinely benefited from decentralization. The vision of players owning their Pokémon NFTs, trading them across chains, and participating in game governance through DAOs represents the future of gaming.
📚 What I Learned
Building PokeWars was an intensive learning journey across multiple domains:
Game Development
- Phaser.js Mastery: Developed expertise in Phaser 3's Scene system, Physics Engine, and real-time rendering capabilities
- Real-Time Synchronization: Mastered the complexities of state synchronization in multiplayer games using Socket.io
- Game Loop Architecture: Implemented efficient game loops with proper frame rate management and delta time calculations
- Collision Detection: Developed custom collision systems for shooting mechanics and player interactions
Blockchain & Web3
- Smart Contract Development: Deep dive into Solidity, including ERC-721 standards, escrow patterns, and gas optimization techniques
- Web3 Integration: Learned to connect wallets (MetaMask and Polkadot.js), handle message signing, and manage transactions
- Cross-Chain Technology: Gained detailed understanding of XCM message encoding, parachain communication, and cross-chain state queries
- IPFS Integration: Implemented decentralized storage patterns for NFT metadata
Full-Stack Architecture
- Microservices Design: Built a three-tier architecture (client, server, contracts) with clear separation of concerns
- Real-Time Communication: Developed WebSocket servers with Socket.io for low-latency game state updates
- Database Design: Created efficient MongoDB schemas for game state, user data, and match history
- API Design: Built RESTful APIs with proper authentication, rate limiting, and error handling
Mathematical Concepts
The project involved several mathematical challenges:
ELO Rating System: Implemented the ELO algorithm for competitive ranking:
$$ R' = R + K \times (S - E) $$
Where:
- $R'$ = New rating
- $R$ = Current rating
- $K$ = K-factor (typically 32)
- $S$ = Actual score (1 for win, 0 for loss)
- $E$ = Expected score: $E = \frac{1}{1 + 10^{(R_{opponent} - R)/400}}$
Damage Calculation: Created balanced damage formulas based on Pokémon stats:
$$ \text{Damage} = \text{BaseDamage} \times \left(1 + \frac{\text{Level}}{100}\right) \times \text{RangeMultiplier} \times \text{TypeEffectiveness} $$
Stat Scaling: Implemented level-based stat multipliers:
$$ \text{Stat}{\text{final}} = \text{Stat}{\text{base}} \times (1 + 0.01 \times \text{Level}) $$
Security & Best Practices
- Smart Contract Security: Learned about reentrancy attacks, overflow vulnerabilities, and access control patterns
- Authentication Patterns: Implemented Sign-In With Ethereum (SIWE) for Web3-native authentication
- Input Validation: Created comprehensive validation middleware to prevent injection attacks
- Rate Limiting: Applied protection against DDoS and brute-force attacks
🛠️ How I Built It
The project was developed in three distinct phases, each with unique challenges and milestones.
Phase 1: Core Game Engine
Frontend Foundation
- Set up React 19 using Vite for rapid development
- Integrated Phaser 3 game engine
- Implemented core game loop with player movement, shooting, and collision detection mechanics
- Created multiple map environments using Tiled map editor: Desert, Forest, Snow, and Volcano
Key Implementation Details:
// Example: Real-time player synchronization
socket.on('playerUpdate', (data) => {
players.forEach(player => {
if (player.id === data.id) {
player.setPosition(data.x, data.y);
player.setRotation(data.angle);
}
});
});
Phase 2: Backend & Multiplayer
Server Architecture
- Built REST API using Express.js with MongoDB for persistent data storage
- Implemented Socket.io server for real-time game state synchronization
- Designed game lobby system with custom room codes
- Developed matchmaking algorithm and ELO rating system
Game State Management
The server maintains authoritative game state, handling:
- Player positions and movements
- Shooting events and hit detection
- Damage calculation and health management
- Match timers and win conditions
Challenges Overcome:
- Latency Issues: Implemented client-side prediction with server reconciliation
- State Synchronization: Applied efficient delta compression for game state updates
- Concurrent Players: Handled multiple simultaneous matches through room-based architecture
Phase 3: Blockchain Integration
Smart Contracts
- PokemonNFT.sol: ERC-721 contract for Pokémon NFTs with leveling system
- MatchEscrow.sol: Escrow contract for staking with automatic winner payouts
- Marketplace.sol: Decentralized NFT trading with listing and bidding functionality
- Leaderboard.sol: On-chain ranking system for verifiable player statistics
- GovernanceToken.sol & PokeWarsDAO.sol: DAO governance for community-driven decisions
Cross-Chain Implementation
The most complex aspect was implementing XCM cross-chain functionality:
// Preparing an XCM message for cross-chain NFT transfers
async function prepareXCMTransfer(destChain, tokenId) {
const xcmMessage = {
V2: {
instructions: [
{
WithdrawAsset: {
id: { Concrete: { parents: 0, interior: 'Here' } },
fun: { Fungible: transferAmount }
}
},
// Additional XCM instructions
]
}
};
return encodeXCM(xcmMessage);
}
Web3 Integration
- Implemented dual wallet support: MetaMask for EVM chains, Polkadot.js for Substrate
- Applied SIWE (Sign-In With Ethereum) pattern for wallet authentication
- Created seamless NFT minting and trading flows
- Integrated IPFS for decentralized metadata storage
🏗️ Technical Architecture
The system consists of a three-tier architecture:
┌─────────────────┐
│ React Client │ ← Phaser.js Game Engine
│ (Frontend) │ ← Web3 Wallet Integration
└────────┬────────┘
│ HTTP/REST + WebSocket
↓
┌─────────────────┐
│ Express Server │ ← Socket.io (Real-time)
│ (Backend) │ ← MongoDB (Persistence)
└────────┬────────┘
│ JSON-RPC
↓
┌─────────────────┐
│ Smart Contracts │ ← Solidity on Moonbeam
│ (Blockchain) │ ← XCM for Cross-Chain
└─────────────────┘
🚧 Challenges Faced
1. Real-Time Multiplayer Synchronization
Problem: Maintaining consistent game state across multiple clients with varying network conditions.
Solution:
- Implemented authoritative server model where the server is the source of truth
- Employed client-side prediction for smooth gameplay
- Added lag compensation and interpolation techniques
- Implemented delta compression to reduce bandwidth usage
Learning: Network programming requires careful consideration of latency, packet loss, and state reconciliation.
2. Cross-Chain Complexity
Problem: XCM (Cross-Consensus Message Format) documentation was sparse, and the encoding format proved complex.
Solution:
- Deep dive into Polkadot's XCM documentation and examples
- Developed abstraction layer for XCM message construction
- Created comprehensive error handling for cross-chain failures
- Implemented retry mechanisms with exponential backoff
Learning: Cross-chain development requires understanding multiple blockchain architectures and consensus mechanisms.
3. Gas Optimization
Problem: Smart contract operations were expensive, particularly for frequent game actions.
Solution:
- Moved non-critical operations off-chain (game state stored in MongoDB)
- Used events for logging instead of storage
- Implemented batch operations where possible
- Optimized data structures to minimize storage costs
Gas Cost Reduction:
$$ \text{Gas}{\text{optimized}} = \text{Gas}{\text{original}} \times 0.35 $$
Achieved approximately 65% reduction in gas costs through optimization.
4. Phaser.js Integration with React
Problem: Phaser.js uses canvas rendering and doesn't integrate naturally with React's virtual DOM.
Solution:
- Created wrapper components that mount Phaser instances
- Used React refs to manage Phaser game lifecycle
- Implemented proper cleanup to prevent memory leaks
- Built communication bridge between React state and Phaser scenes
5. Wallet Connection Reliability
Problem: Different wallets have varying APIs and connection patterns.
Solution:
- Created abstraction layer (Web3Context) to manage multiple wallet types
- Implemented fallback mechanisms
- Added comprehensive error handling and user feedback
- Provided unified interface for wallet operations
6. ELO Rating System Balance
Problem: Initial ELO implementation caused wild rating fluctuations.
Solution:
- Adjusted K-factor based on player experience level
- Implemented rating floors to prevent extreme drops
- Added provisional rating period for new players
- Created tier system (Bronze, Silver, Gold, Platinum, Diamond, Master) for better matchmaking
Formula Refinement:
$$ K = \begin{cases} 32 & \text{if } R < 2100 \ 24 & \text{if } 2100 \leq R < 2400 \ 16 & \text{if } R \geq 2400 \end{cases} $$
7. Database Performance
Problem: MongoDB queries were slow with large player bases and extensive match histories.
Solution:
- Created appropriate indexes on frequently queried fields
- Implemented pagination for match history
- Used aggregation pipelines for complex queries
- Added caching layer for leaderboard data
Performance Improvement:
- Query time reduced from ~500ms to ~50ms
- Implemented connection pooling
- Added database query optimization scripts
8. Security Vulnerabilities
Problem: Initial implementation contained various security issues, including injection risks and unvalidated inputs.
Solution:
- Implemented comprehensive input validation middleware
- Added rate limiting to prevent abuse
- Used parameterized queries (handled by Mongoose)
- Implemented proper authentication and authorization
- Added security headers: CSP, HSTS, X-Frame-Options
🏆 Key Achievements
- Full-Stack Web3 Game: Successfully integrated blockchain technology with real-time multiplayer gameplay
- Cross-Chain Functionality: Implemented working XCM cross-chain transfers and data aggregation
- Scalable Architecture: Designed system to support multiple simultaneous matches
- Comprehensive Security: Implemented multiple layers of security best practices
- Exceptional User Experience: Achieved seamless wallet integration and intuitive gameplay
Built with passion, curiosity, and plenty of coffee ☕
Built With
- axios
- bcrypt
- dotenv
- eslint
- ethers.js
- express.js
- git
- hardhat
- ipfs
- javascript
- jest
- json
- json-rpc
- jwt
- mongodb
- mongoose
- moonbeam
- node.js
- nodemon
- openzeppelin
- phaser.js
- polkadot
- rest
- socket.io
- solidity
- tailwind
- typescript
- vite
- web3.js
- websocket
Log in or sign up for Devpost to join the conversation.