Here's a Twig template for a Darts scoring component, styled with Flowbite and TailwindCSS, along with a native JavaScript script for functionality and POSTing scores.
This component provides a keypad-like interface for entering dart scores, allowing for single, double, and triple values, as well as bullseyes and misses. It tracks the three darts thrown in a turn and allows submitting the total.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Darts Score Entry</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Flowbite CSS & JS CDN (JS needs to be loaded at the end of body or after elements) -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.css" rel="stylesheet" />
<style>
/* Custom styles for better button hover effects and clarity */
.btn-base {
@apply w-full py-3 text-lg font-semibold rounded-lg focus:outline-none transition-colors duration-200;
}
.btn-number {
@apply btn-base bg-gray-200 text-gray-800 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600;
}
.btn-special {
@apply btn-base bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600;
}
.btn-action {
@apply btn-base bg-red-600 text-white hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600;
}
.btn-submit {
@apply btn-base bg-green-600 text-white hover:bg-green-700 dark:bg-green-700 dark:hover:bg-green-600;
}
.btn-disabled {
@apply cursor-not-allowed opacity-50;
}
</style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 min-h-screen flex items-center justify-center p-4">
{# Twig Component: Darts Score Entry #}
<div
id="darts-score-entry"
class="max-w-md w-full p-6 bg-white rounded-lg shadow-xl dark:bg-gray-800 border border-gray-200 dark:border-gray-700"
{# Example Twig variables - these would be passed from your controller #}
data-user-id="{{ user.id|default('user-123') }}" {# Placeholder user ID #}
data-game-id="{{ game.id|default('game-abc') }}" {# Placeholder game ID #}
>
<h2 class="text-2xl font-bold text-center text-gray-900 dark:text-white mb-6">Enter Darts Score</h2>
<div class="mb-6">
<div class="flex justify-between items-center bg-gray-50 dark:bg-gray-700 p-4 rounded-lg border border-gray-200 dark:border-gray-600">
<div class="text-gray-700 dark:text-gray-300">
<span class="text-sm">Current Dart:</span>
<span id="current-dart-display" class="block text-2xl font-bold text-blue-600 dark:text-blue-400">0</span>
</div>
<div class="text-gray-700 dark:text-gray-300 text-right">
<span class="text-sm">Turn Total:</span>
<span id="turn-total-display" class="block text-3xl font-extrabold text-gray-900 dark:text-white">0</span>
</div>
</div>
<div class="mt-3 text-gray-600 dark:text-gray-400 text-sm">
Darts Thrown this Turn: <span id="darts-thrown-count">0</span>
</div>
<div class="flex flex-wrap gap-2 mt-2" id="darts-thrown-display">
{# Darts will be displayed here dynamically #}
</div>
</div>
<div class="grid grid-cols-4 gap-2">
{# Row 1: Triple Multipliers #}
<button type="button" class="btn-special col-span-1" data-value="T">T</button>
<button type="button" class="btn-number" data-value="20">20</button>
<button type="button" class="btn-number" data-value="19">19</button>
<button type="button" class="btn-number" data-value="18">18</button>
{# Row 2: Double Multipliers #}
<button type="button" class="btn-special col-span-1" data-value="D">D</button>
<button type="button" class="btn-number" data-value="17">17</button>
<button type="button" class="btn-number" data-value="16">16</button>
<button type="button" class="btn-number" data-value="15">15</button>
{# Row 3: Single Numbers & Bull #}
<button type="button" class="btn-number" data-value="14">14</button>
<button type="button" class="btn-number" data-value="13">13</button>
<button type="button" class="btn-number" data-value="12">12</button>
<button type="button" class="btn-number" data-value="11">11</button>
{# Row 4: Single Numbers & Bull #}
<button type="button" class="btn-number" data-value="10">10</button>
<button type="button" class="btn-number" data-value="9">9</button>
<button type="button" class="btn-number" data-value="8">8</button>
<button type="button" class="btn-number" data-value="7">7</button>
{# Row 5: Single Numbers & Miss #}
<button type="button" class="btn-number" data-value="6">6</button>
<button type="button" class="btn-number" data-value="5">5</button>
<button type="button" class="btn-number" data-value="4">4</button>
<button type="button" class="btn-number" data-value="3">3</button>
{# Row 6: Single Numbers & Bull/25 #}
<button type="button" class="btn-number" data-value="2">2</button>
<button type="button" class="btn-number" data-value="1">1</button>
<button type="button" class="btn-special" data-value="25">25</button> {# Outer Bull #}
<button type="button" class="btn-special" data-value="50">Bull</button> {# Bullseye #}
{# Row 7: Action Buttons #}
<button type="button" class="btn-action col-span-1" id="backspace-btn">⌫</button>
<button type="button" class="btn-action col-span-1" id="clear-turn-btn">Clear Turn</button>
<button type="button" class="btn-special col-span-1" data-value="0">Miss</button>
<button type="button" class="btn-submit col-span-1" id="enter-dart-btn">Enter Dart</button>
</div>
<div class="mt-6">
<button type="button" class="btn-submit w-full" id="submit-score-btn" disabled>Submit Turn Score</button>
</div>
{# Score Submission Feedback #}
<div id="score-feedback" class="mt-4 p-3 text-center text-sm rounded-lg hidden" role="alert"></div>
</div>
<!-- Flowbite JS CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const scoreEntryComponent = document.getElementById('darts-score-entry');
const userId = scoreEntryComponent.dataset.userId;
const gameId = scoreEntryComponent.dataset.gameId;
const currentDartDisplay = document.getElementById('current-dart-display');
const turnTotalDisplay = document.getElementById('turn-total-display');
const dartsThrownCount = document.getElementById('darts-thrown-count');
const dartsThrownDisplay = document.getElementById('darts-thrown-display');
const scoreFeedback = document.getElementById('score-feedback');
const numberButtons = document.querySelectorAll('.btn-number, .btn-special[data-value="25"], .btn-special[data-value="50"], .btn-special[data-value="0"]');
const multiplierButtons = document.querySelectorAll('.btn-special[data-value="D"], .btn-special[data-value="T"]');
const backspaceBtn = document.getElementById('backspace-btn');
const enterDartBtn = document.getElementById('enter-dart-btn');
const clearTurnBtn = document.getElementById('clear-turn-btn');
const submitScoreBtn = document.getElementById('submit-score-btn');
let currentDartValue = 0; // The value of the dart currently being entered
let hasMultiplier = false; // To prevent applying D/T multiple times
let dartsThrown = []; // Array to store scores of 3 darts in the current turn
const MAX_DARTS_PER_TURN = 3;
function updateDisplay() {
currentDartDisplay.textContent = currentDartValue;
const total = dartsThrown.reduce((sum, dart) => sum + dart, 0);
turnTotalDisplay.textContent = total;
dartsThrownCount.textContent = dartsThrown.length;
dartsThrownDisplay.innerHTML = ''; // Clear previous dart indicators
dartsThrown.forEach((dart, index) => {
const span = document.createElement('span');
span.className = 'px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded dark:bg-blue-900 dark:text-blue-200';
span.textContent = `Dart ${index + 1}: ${dart}`;
dartsThrownDisplay.appendChild(span);
});
// Button state management
enterDartBtn.disabled = currentDartValue === 0 || dartsThrown.length >= MAX_DARTS_PER_TURN;
backspaceBtn.disabled = currentDartValue === 0;
submitScoreBtn.disabled = dartsThrown.length === 0;
// Multiplier buttons enabled only if a number is entered and no multiplier applied yet
multiplierButtons.forEach(btn => {
btn.disabled = currentDartValue === 0 || hasMultiplier;
});
}
function showFeedback(message, type = 'info') {
scoreFeedback.classList.remove('hidden', 'bg-green-100', 'text-green-800', 'bg-red-100', 'text-red-800', 'bg-blue-100', 'text-blue-800');
scoreFeedback.textContent = message;
if (type === 'success') {
scoreFeedback.classList.add('bg-green-100', 'text-green-800', 'dark:bg-green-900', 'dark:text-green-200');
} else if (type === 'error') {
scoreFeedback.classList.add('bg-red-100', 'text-red-800', 'dark:bg-red-900', 'dark:text-red-200');
} else { // info
scoreFeedback.classList.add('bg-blue-100', 'text-blue-800', 'dark:bg-blue-900', 'dark:text-blue-200');
}
scoreFeedback.classList.remove('hidden');
setTimeout(() => scoreFeedback.classList.add('hidden'), 3000); // Hide after 3 seconds
}
// --- Event Listeners ---
numberButtons.forEach(button => {
button.addEventListener('click', () => {
if (dartsThrown.length >= MAX_DARTS_PER_TURN) {
showFeedback("Maximum 3 darts thrown. Please submit or clear turn.", 'info');
return;
}
const value = parseInt(button.dataset.value);
if (value === 25 || value === 50 || value === 0) {
// For special scores (25, Bull, Miss), overwrite current value directly
currentDartValue = value;
} else if (currentDartValue === 0) {
currentDartValue = value;
} else {
// Allow building a number if needed (e.g., 1 then 2 for 12, but for darts keypad, it's usually direct)
// For a standard darts keypad, you'd usually press "1" then "2" if you needed 12, but here we have explicit "12" button.
// Let's assume direct input for now, pressing a number button sets the current dart value
currentDartValue = value;
}
hasMultiplier = false; // Reset multiplier flag when new number is entered
updateDisplay();
});
});
multiplierButtons.forEach(button => {
button.addEventListener('click', () => {
if (currentDartValue === 0 || hasMultiplier) {
return; // Cannot apply multiplier to 0 or if already applied
}
const multiplier = button.dataset.value;
if (multiplier === 'D') {
if (currentDartValue > 20 && currentDartValue !== 25) { // Cannot double Bull (50) or Outer Bull (25)
showFeedback("Cannot double a Bullseye or Outer Bull.", 'error');
return;
}
currentDartValue *= 2;
} else if (multiplier === 'T') {
if (currentDartValue > 20) { // Can only triple numbers 1-20
showFeedback("Cannot triple a Bullseye or Outer Bull.", 'error');
return;
}
currentDartValue *= 3;
}
// Validate max score (T20 = 60, D20 = 40, Bull = 50)
if (currentDartValue > 60 && currentDartValue !== 50) { // 50 is Bull, highest regular is 60 (T20)
// This scenario should ideally not be possible with direct buttons,
// but as a safeguard if input changes logic.
currentDartValue = 0; // Reset invalid score
showFeedback("Invalid dart score (e.g., T25 is not possible).", 'error');
return;
}
hasMultiplier = true;
updateDisplay();
});
});
backspaceBtn.addEventListener('click', () => {
currentDartValue = 0; // For darts, backspace usually means clear the current dart input
hasMultiplier = false;
updateDisplay();
});
enterDartBtn.addEventListener('click', () => {
if (currentDartValue === 0 && dartsThrown.length === 0) {
showFeedback("Enter a score for the first dart.", 'info');
return;
}
if (currentDartValue === 0 && dartsThrown.length > 0) {
// If '0' (miss) is intentionally entered, allow it
// No need to block if `currentDartValue` is 0 and it's an intended miss
}
if (dartsThrown.length < MAX_DARTS_PER_TURN) {
dartsThrown.push(currentDartValue);
currentDartValue = 0;
hasMultiplier = false;
updateDisplay();
} else {
showFeedback("Maximum 3 darts thrown. Please submit or clear turn.", 'info');
}
});
clearTurnBtn.addEventListener('click', () => {
currentDartValue = 0;
hasMultiplier = false;
dartsThrown = [];
updateDisplay();
showFeedback("Current turn cleared.", 'info');
});
submitScoreBtn.addEventListener('click', async () => {
if (dartsThrown.length === 0) {
showFeedback("No darts thrown this turn to submit.", 'info');
return;
}
const turnTotal = dartsThrown.reduce((sum, dart) => sum + dart, 0);
showFeedback("Submitting score...", 'info');
try {
const response = await fetch('/api/v1/score', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: userId,
game_id: gameId,
score: turnTotal,
darts: dartsThrown // Optionally send individual dart scores too
}),
});
if (response.ok) {
const result = await response.json();
showFeedback('Score submitted successfully!', 'success');
console.log('Submission successful:', result);
// Reset for next turn
currentDartValue = 0;
hasMultiplier = false;
dartsThrown = [];
updateDisplay();
// You might want to trigger a page refresh or update game state here
} else {
const errorData = await response.json();
showFeedback(`Failed to submit score: ${errorData.message || 'Unknown error'}`, 'error');
console.error('Submission failed:', response.status, errorData);
}
} catch (error) {
showFeedback(`Network error: ${error.message}`, 'error');
console.error('Network error during score submission:', error);
}
});
// Initial display update
updateDisplay();
});
</script>
</body>
</html>
Explanation:
-
Twig Template (.twig):
- HTML Structure: Basic HTML5 boilerplate with
lang="en".
- CDN Includes:
tailwind.css: For utility-first styling.
flowbite.min.css: For Flowbite components (though we're mostly using Tailwind classes directly for buttons, Flowbite's JS is beneficial).
flowbite.min.js: Loaded at the end of the <body> for performance, ensures DOM is ready.
- Custom CSS: A small
<style> block defines reusable Tailwind @apply classes for consistency and better button styling.
- Main Component Container (
#darts-score-entry):
- Has
data-user-id and data-game-id attributes. These are crucial for passing server-side data (from Twig) to the client-side JavaScript.
{{ user.id|default('user-123') }} and {{ game.id|default('game-abc') }} are Twig syntax. Replace user.id and game.id with the actual variables you pass to your Twig template from your backend (e.g., a Symfony or Laravel controller). The |default() filter provides fallback values for demonstration.
- Display Areas:
#current-dart-display: Shows the score for the dart currently being input.
#turn-total-display: Shows the sum of all darts entered for the current turn.
#darts-thrown-count: Indicates how many darts have been entered out of 3.
#darts-thrown-display: Dynamically shows individual dart scores.
- Keypad:
- A
grid layout is used for the buttons.
data-value attributes are used to store the score or action associated with each button.
- Numbers (1-20, 25, 50, 0): Direct score values.
- Multipliers ('D', 'T'): Indicate double/triple.
- Actions: '⌫' (Backspace/Clear current dart), 'Clear Turn', 'Enter Dart', 'Submit Turn Score'.
- Feedback Area (
#score-feedback): A div to display success or error messages to the user.
-
JavaScript (<script>):
How to Use:
- Save as Twig: Save the code above as a Twig file (e.g.,
_darts_scoring_component.html.twig).
- Include in your main template:
{# In your main page template (e.g., templates/game/show.html.twig) #}
{% extends 'base.html.twig' %}
{% block body %}
{# Assuming you pass a 'user' and 'game' object to this template from your controller #}
{% include '_darts_scoring_component.html.twig' with {'user': app.user, 'game': game} %}
{# Or if 'user' and 'game' are available globally in Twig context: #}
{# {% include '_darts_scoring_component.html.twig' %} #}
{% endblock %}
- Backend Setup:
- Ensure your backend framework (Symfony, Laravel, etc.) serves this Twig template.
- Create an API endpoint at
/api/v1/score that accepts POST requests with a JSON body containing user_id, game_id, and score.
- Example (Conceptual PHP/Symfony Controller):
// src/Controller/ApiController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
class ApiController extends AbstractController
{
#[Route('/api/v1/score', name: 'api_v1_score', methods: ['POST'])]
public function postScore(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$userId = $data['user_id'] ?? null;
$gameId = $data['game_id'] ?? null;
$score = $data['score'] ?? null;
$darts = $data['darts'] ?? null; // Optional
if (null === $userId || null === $gameId || null === $score) {
return new JsonResponse(['message' => 'Missing required parameters (user_id, game_id, score)'], JsonResponse::HTTP_BAD_REQUEST);
}
// --- Your actual score saving logic here ---
// e.g., Save to database, update game state, etc.
// For demonstration, just log and return success.
error_log(sprintf(
"Received Darts Score: User ID: %s, Game ID: %s, Score: %d, Darts: %s",
$userId, $gameId, $score, json_encode($darts)
));
return new JsonResponse([
'message' => 'Score saved successfully!',
'received_data' => [
'user_id' => $userId,
'game_id' => $gameId,
'score' => $score,
'darts' => $darts
]
], JsonResponse::HTTP_OK);
}
}
- Testing: Open your page in a browser, use the keypad, and monitor your browser's network tab (F12 Developer Tools) to see the POST requests to
/api/v1/score.