About the project

Technical documentation for Asken Online

Läs sidan på svenska

Version 1.1 • December 2025

1. Project overview

Asken Online is a web-based multiplayer version of the classic Swedish card game "Asken" (also known as "Sjuan" or "Fan", and related to Sevens or Fan Tan). It lets 3 to 7 players (people and/or robots) compete in real time in the browser.

Background

I created this game so that I could keep playing Asken with my daughter, who is moving to Australia to work as an au pair after graduating. Wherever in the world we are, we can now play our favourite card game together.

Main features

Multiplayer
3–7 players (people/robots)
Matchmaking
Find other players automatically
Robot players
4 difficulty levels
Chat
Talk to the other players
Persistence
Redis storage for 48 h
Responsive
Mobile & desktop
PWA
Install as an app
Game modes
Quick & Standard
Hints
Visual guidance

2. Tech stack

Node.js
Runtime
Express
Web server
Socket.io
Websockets
Redis
Data storage
CSS3
Styling
Vanilla JS
Client logic

Why these technologies?

3. Architecture

The application follows a classic client-server architecture with WebSocket communication:

Browser
HTML/CSS/JS
⟷
Node.js Server
Express + Socket.io
⟷
Redis
Game data

Communication flow

  1. The client connects through Socket.io and gets a unique socket ID
  2. When a room is created, a 4-character code is generated and the room is saved in Redis
  3. All players in the room receive updates through gameState events
  4. The server validates every move and updates Redis
  5. Redis TTL (24 hours) clears inactive rooms automatically
ℹ️ Stateless server

All game data is stored in Redis, not in the server's memory. That makes it possible to restart the server without losing games in progress.

4. File structure

asken-online/
  ├── server/
  │   └── index.js         # Main server
  ├── public/
  │   ├── index.html       # Main page + game
  │   ├── manual.html      # Rules
  │   ├── about.html       # Technical docs
  │   └── gfx/
  │       ├── asken_logo.webp
  │       ├── bg_wood.webp
  │       ├── bg_dark_steel.webp
  │       └── bg_tyg.webp
  ├── package.json
  └── render.yaml         # Deploy-config

Files in detail

File Size Description
server/index.js ~2,400 lines Express server, Socket.io handlers, game logic, robot AI
public/index.html ~3,600 lines All client code: HTML, CSS and JavaScript in one file
public/manual.html ~700 lines Rules and instructions
public/about.html ~1,100 lines Technical information

5. The client

The client is a Single Page Application (SPA) built with vanilla JavaScript. Everything (HTML, CSS, JS) lives in a single file for simple deployment.

Screens/views

State management

let gameState = {
  code: "A1B2",           // Room code
  players: [...],         // Array of players
  tableau: {...},         // Table state per suit
  currentPlayerIndex: 0,  // Whose turn
  roundNumber: 1,         // Current round
  // ... more state
};

CSS architecture

6. The server

Express-setup

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const Redis = require('ioredis');

const app = express();
app.use(express.static('public'));

const server = http.createServer(app);
const io = new Server(server);

Redis-integration

// Save room with 48 h TTL
async function saveRoom(room) {
  await redis.setex(
    `room:${room.code}`, 
    172800,  // 48 hours
    JSON.stringify(room)
  );
}

// Fetch room
async function getRoom(code) {
  const data = await redis.get(`room:${code}`);
  return data ? JSON.parse(data) : null;
}

Main socket events

Event Direction Description
createRoom Client → Server Create a new game room
joinRoom Client → Server Join a room
startGame Client → Server Start the game
playCards Client → Server Play cards
pass Client → Server Pass (take the Asken)
gameState Server → Client Update game state
error Server → Client Error message

7. Real-time communication

Socket.io handles all real-time communication between client and server. Each player has a unique socket connection that identifies them.

Connection handling

io.on('connection', (socket) => {
  console.log('Player connected:', socket.id);
  
  socket.on('disconnect', async () => {
    // Handle disconnect
    // Mark the player as disconnected
    // End the game if necessary
  });
});

State synchronisation

Every time the game state changes, a personal gameState is sent to each player. Players only see their own cards, while opponents' cards are shown as card backs.

function emitRoomStateToAll(room) {
  for (const player of room.players) {
    const state = {
      ...roomData,
      myId: player.id,
      players: room.players.map(p => ({
        ...p,
        hand: p.id === player.id ? p.hand : null,
        cardCount: p.hand.length
      }))
    };
    socket.emit('gameState', state);
  }
}

Keepalive

The client sends regular keepalive messages to update lastActivity for the room and prevent timeouts. Players have 12 hours to reconnect after being disconnected.

8. Matchmaking

The matchmaking system lets players find each other without sharing room codes. A global queue is kept in memory on the server.

Queue handling

const matchmakingQueue = [];
// Format: { socketId, name, joinedAt }

function addToMatchmaking(socketId, name) {
  matchmakingQueue.push({
    socketId,
    name,
    joinedAt: Date.now()
  });
  broadcastMatchmakingState();
}

function getMatchmakingState() {
  return {
    queueCount: matchmakingQueue.length,
    players: matchmakingQueue.map((p, i) => ({
      name: p.name,
      position: i + 1
    }))
  };
}

Starting a game

When there are at least 2 players in the queue, anyone can start the game. Whoever starts becomes the host, and everyone in the queue is moved to a new room.

9. Chat

Players can talk to each other through a built-in chat during the game. Messages are sent through Socket.io and shown to everyone in the room.

Implementation

// Server
socket.on('chatMessage', async (text) => {
  const cleanText = String(text).trim().slice(0, 200);
  if (!cleanText) return;
  
  io.to(currentRoom).emit('chatMessage', {
    sender: playerName,
    text: cleanText,
    timestamp: Date.now()
  });
});

// Client
function addChatMessage(data) {
  chatMessages.push(data);
  if (!chatOpen) unreadCount++;
  renderChatMessages();
}

Features

10. Game logic

Card representation

const card = {
  id: "hearts-7",      // Unique ID
  suit: "hearts",      // Suit
  rank: 7              // Value 1-13
};

Tableau (the table)

const tableau = {
  spades:   { low: 5, high: 9 },   // 5-6-7-8-9
  hearts:   { low: 7, high: 7 },   // Only the 7
  diamonds: { low: 3, high: 10 },  // 3 to 10
  clubs:    null                    // Not started
};

Move validation

function canPlayCard(card, tableau) {
  const row = tableau[card.suit];
  
  // If the suit is not started: only the 7
  if (!row) return card.rank === 7;
  
  // Otherwise: one step up or down
  return card.rank === row.low - 1 
      || card.rank === row.high + 1;
}

Scoring

function getCardPoints(card) {
  if (card.rank === 1) return 25;        // Ace
  if (card.rank >= 10) return 10;        // 10, J, Q, K
  return 5;                               // 2-9
}

// Asken penalty: +50 points

End of a round

A round ends when a player gets rid of all their cards. Then:

  1. Points are counted for the cards left in every hand
  2. +50 is added for whoever holds the Asken
  3. Total scores are updated
  4. A check is made for anyone reaching 500 (standard game)
  5. The result dialog is shown

11. Robot AI

Robot players are implemented entirely on the server. When it is a robot's turn, executeBotTurn() runs after a short delay so the game flows naturally.

Difficulty levels

🤖 Dim

Plays a random valid card. No strategy.

// Pick at random among playable cards
const randomCard = playableCards[
  Math.floor(Math.random() * playableCards.length)
];

🤖 Eager

Wants to get rid of its most expensive cards. It usually plays its most valuable card and sometimes a whole run at once, without caring what that opens up for the others.

🤖 Decent

Half smart. It rates every card one move ahead: cards that open nothing for the opponents are good, cards that only help the others are bad. But about every other move it gets careless and plays the first card that comes to mind.

🤖 Smart

Counts cards and plays out the rest of the round before every move:

// Smart robot - try out every possible move
for (let round = 0; round < 200; round++) {
  // Guess the opponents' cards from what is known
  const guess = dealUnknownCards(unknown, cannotHave);
  
  for (const move of moves) {
    // Play the round to the end and see how it went
    totals[move] += playOutRound(guess, move);
  }
}
// Pick the move that did best on average
return bestOf(totals);

12. Deployment

The application is deployed on Render with an external Redis instance for data storage.

Render configuration

# render.yaml
services:
  - type: web
    name: asken-online
    runtime: node
    buildCommand: npm install
    startCommand: node server/index.js
    envVars:
      - key: REDIS_URL
        sync: false
      - key: NODE_ENV
        value: production

Environment variables

Variable Description
REDIS_URL Connection string for the Redis server
PORT Port for the web server (default: 3000)
NODE_ENV production / development

Auto-deploy

Render is configured to deploy automatically on every push to the main branch on GitHub.

🔗 Links

Thanks to Lana Pistol and Iréne Pistol for ideas and testing.

Created by Patrik Pistol