DevRocket Logo
Code Examples Background

Code Your Own Games

Learn from practical examples inspired by Slot Astronaut.

Get Started

Code + Concept Blocks

Dive into practical code snippets paired with detailed explanations to understand key game development concepts. These examples, inspired by Slot Astronaut, cover essential techniques like rendering, animations, and input handling. Use the tabs to switch between code and concepts, and apply these lessons to your own projects. Perfect for beginners and intermediate developers looking to build mobile-friendly games.

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function drawReel() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#1a1a1a';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(reelImage, 100, 100, 200, 200);
}

window.addEventListener('resize', () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  drawReel();
});

drawReel();

Canvas Rendering

This code sets up an HTML5 Canvas for rendering game graphics, a core component of Slot Astronaut. It initializes the canvas to match the window size, ensuring responsiveness. The drawReel function clears the canvas and draws a reel image, optimized for mobile screens. Resizing is handled dynamically to maintain visuals across devices.

let frame = 0;
const spriteSheet = new Image();
spriteSheet.src = 'images/sprite-astronaut.png';

function animateSprite() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(
    spriteSheet,
    frame * 64, 0, 64, 64,
    100, 100, 64, 64
  );
  frame = (frame + 1) % 4;
  requestAnimationFrame(animateSprite);
}

spriteSheet.onload = animateSprite;

Sprite Animation

This snippet creates a sprite animation for an astronaut character, a key visual in Slot Astronaut. It uses a sprite sheet with multiple frames, drawn sequentially using requestAnimationFrame for smooth playback. The animation loops through frames to create a dynamic effect. This technique is efficient for mobile devices, minimizing CPU usage.

canvas.addEventListener('touchstart', (e) => {
  e.preventDefault();
  const touch = e.touches[0];
  const rect = canvas.getBoundingClientRect();
  const x = touch.clientX - rect.left;
  if (x > 100 && x < 200) {
    spinReels();
  }
});

function spinReels() {
  // Logic to spin the reels
  console.log('Reels spinning!');
}

Touch Input

This code handles touch inputs for mobile gameplay, critical for Slot Astronaut’s interactivity. It detects touch events on the canvas, calculates the touch position, and triggers actions like spinning reels. Preventing default browser behavior ensures smooth interactions. This approach is optimized for low-end devices with varying touch sensitivities.

Game Logic Blocks

Master the core mechanics of mobile games with these logic snippets, inspired by Slot Astronaut. From timers to physics, these examples provide practical code for building engaging gameplay. Each block is optimized for performance on low-end devices, ensuring smooth experiences for all players. Use these as building blocks for your own game projects.

Game Timer

Implement a countdown timer to add time-based challenges. This snippet uses setInterval to track time accurately. It updates the UI without overloading the CPU. Perfect for creating urgency in mobile games.

Score Updates

Track and display player scores dynamically. This code updates scores based on game events, ensuring real-time feedback. It’s lightweight and optimized for budget phones. Use it to reward player achievements.

Peg Physics

Simulate simple physics for peg-based mechanics, like in Slot Astronaut. This snippet calculates collisions and bounces for smooth animations. It’s optimized to run efficiently on low-end devices. Apply it for realistic game interactions.

Randomized Outcomes

Generate random reel outcomes for slot mechanics. This code uses Math.random with weighted probabilities for balanced gameplay. It ensures fairness while keeping performance light. Ideal for slot-style games.

UI Samples - Before

Early UI designs often lack polish and responsiveness, especially for mobile games. The example below shows a basic, unoptimized button layout from Slot Astronaut’s prototype phase. It lacked touch-friendly sizing and visual feedback, leading to poor user experience. This highlights the need for iterative design improvements.

.button {
  background: grey;
  padding: 5px;
  font-size: 12px;
}

UI Samples - After

The improved UI for Slot Astronaut focuses on mobile-friendly design and visual appeal. The optimized button uses larger tap targets, hover effects, and a cohesive sci-fi style. This snippet ensures responsiveness and smooth performance on low-end devices. Compare it to the ‘before’ to see the transformation.

.button {
  background: var(--color-primary);
  padding: 15px 30px;
  font-size: var(--font-size-h4);
  border-radius: var(--radius-md);
  transition: transform 0.2s ease;
}
.button:hover {
  transform: scale(1.05);
}

Responsive Layout Code

Creating responsive layouts is crucial for mobile games, especially on diverse devices in markets like India. This example, inspired by Slot Astronaut, shows how to adapt a game canvas and UI for different screen sizes. It includes mobile fallback notes to ensure compatibility with low-end phones. Use this code to make your game accessible across devices.

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

function setCanvasSize() {
  const dpr = window.devicePixelRatio || 1;
  const maxWidth = 800; // Max width for low-end devices
  canvas.width = Math.min(window.innerWidth, maxWidth) * dpr;
  canvas.height = (canvas.width * 9 / 16) * dpr; // 16:9 aspect ratio
  canvas.style.width = `${canvas.width / dpr}px`;
  canvas.style.height = `${canvas.height / dpr}px`;
  ctx.scale(dpr, dpr);
}

// Mobile fallback: Reduce quality for low-end devices
if (navigator.userAgent.includes('Android') && window.innerWidth < 600) {
  canvas.width = canvas.width / 2;
  canvas.height = canvas.height / 2;
  canvas.style.width = `${canvas.width / dpr}px`;
  canvas.style.height = `${canvas.height / dpr}px`;
}

window.addEventListener('resize', setCanvasSize);
setCanvasSize();

Note: This code adjusts canvas size based on device width, capping at 800px for performance. The devicePixelRatio ensures crisp visuals on high-DPI screens. For low-end Android devices (screen width < 600px), it halves resolution to reduce processing load. Test on budget phones to verify smoothness.

Best Practices for Game Development

Follow these dos and don’ts to create high-quality, performant mobile games like Slot Astronaut. These guidelines focus on optimizing code, assets, and user experience for low-end devices. Apply them to ensure your game runs smoothly and engages players effectively. Avoid common pitfalls to save time and improve quality.

Do: Optimize Assets

Use WebP images and minified JavaScript/CSS to reduce load times, critical for users on slow networks in India.

Don’t: Overuse Canvas Draws

Avoid excessive draw calls; batch shapes and use sprite sheets to maintain 30-60 FPS on budget phones.

Do: Test on Low-End Devices

Test your game on budget Android phones and browsers like UC Browser to ensure compatibility and performance.

Don’t: Ignore Touch Feedback

Ensure touch controls have visual feedback (e.g., hover effects) to improve usability on small screens.

Do: Use requestAnimationFrame

Leverage requestAnimationFrame for smooth animations and game loops, optimizing CPU usage on low-end devices.

Ready to Start Coding?

GET IN TOUCH

Contact us to learn more about our courses or get help with your game projects. Our team is here to guide you through every step of your development journey. Start building your own mobile game today! Reach out for personalized support and resources.