Skip to content

Simple vite react based pixel game #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions completesolution/js_vite_react_game/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
33 changes: 33 additions & 0 deletions completesolution/js_vite_react_game/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'

export default [
{ ignores: ['dist'] },
{
files: ['**/*.{js,jsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...js.configs.recommended.rules,
...reactHooks.configs.recommended.rules,
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
]
13 changes: 13 additions & 0 deletions completesolution/js_vite_react_game/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
27 changes: 27 additions & 0 deletions completesolution/js_vite_react_game/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "reactgame",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/js": "^9.21.0",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.21.0",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^15.15.0",
"vite": "^6.2.0"
}
}
46 changes: 46 additions & 0 deletions completesolution/js_vite_react_game/plugins/asciiArtToCssPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import fs from 'fs';
import path from 'path';
import { generateAsciiArtCss } from './generateAsciiArtCss.js';

export default function asciiArtToCssPlugin() {
return {
name: 'ascii-art-to-css',
enforce: 'pre', // Ensure this plugin runs before other plugins
handleHotUpdate({ file, server }) {
if (file.endsWith('.atxt')) {
const content = fs.readFileSync(file, 'utf-8');
if (content.startsWith('#ascii-art')) {
// Trigger a full page reload when a valid ASCII art file changes
server.ws.send({ type: 'full-reload' });
}
}
},
transform(code, id) {
if (id.endsWith('.atxt')) {
// Extract the basename of the file (e.g., "enemy" from "enemy.atxt")
const className = path.basename(id, '.atxt');

// Generate CSS using the utility function
const cssContent = generateAsciiArtCss(code, className);

console.log(cssContent);

// During development, inject CSS dynamically
if (process.env.NODE_ENV === 'development') {
return `
const style = document.createElement('style');
style.textContent = \`${cssContent}\`;
document.head.appendChild(style);
`;
}

// During production, write CSS to disk
const cssFilePath = id.replace(/\.atxt$/, '.css');
fs.writeFileSync(cssFilePath, cssContent, 'utf-8');

// Return nothing for production builds
return '';
}
},
};
}
18 changes: 18 additions & 0 deletions completesolution/js_vite_react_game/plugins/asciiArtToSvgPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import fs from 'fs';
import path from 'path';
import { generateAsciiArtSvg } from './generateAsciiArtSvg.js';

export default function asciiArtToSvgPlugin() {
return {
name: 'ascii-art-to-svg',
enforce: 'pre', // Ensure this plugin runs before other plugins
transform(code, id) {
if (id.endsWith('.atxt')) {
// Generate the SVG string from the .atxt content
const svgContent = generateAsciiArtSvg(code, 'ascii-art-svg');
// Return the SVG string as a JavaScript module
return `export default ${JSON.stringify(svgContent)};`;
}
},
};
}
62 changes: 62 additions & 0 deletions completesolution/js_vite_react_game/plugins/generateAsciiArtCss.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* Generates CSS from an .atxt file's content.
* @param {string} atxtContent - The full content of the .atxt file, including the header.
* @param {string} className - The class name to use in the generated CSS.
* @returns {string} - The generated CSS string.
* @throws {Error} - Throws an error if the size in the header is invalid.
*/
export function generateAsciiArtCss(atxtContent, className) {
// Split the content into lines
const lines = atxtContent.trim().split('\n');

// Parse the header
const header = lines[0];
if (!header.startsWith('#ascii-art')) {
throw new Error('Invalid .atxt file: Missing #ascii-art header.');
}

// Extract the size from the header (e.g., "10x10")
const sizeMatch = header.match(/#ascii-art (\d+)x(\d+)/);
if (!sizeMatch) {
throw new Error('Invalid .atxt file: Missing or invalid size in header.');
}
const [_, width, height] = sizeMatch.map(Number);

// Extract the ASCII art content
const asciiArt = lines.slice(1);

// Fill missing rows with blank lines to match the specified height
const filledAsciiArt = Array.from({ length: height }, (_, y) => {
return asciiArt[y] ? asciiArt[y].padEnd(width, ' ') : ' '.repeat(width);
});

// Validate the dimensions of the ASCII art
for (const line of filledAsciiArt) {
if (line.length !== width) {
throw new Error(`Invalid .atxt file: Expected each row to have ${width} columns, but got "${line}".`);
}
}

// Convert ASCII art to CSS box-shadow styles
const boxShadow = filledAsciiArt
.flatMap((line, y) =>
line.split('').map((char, x) => {
if (char === ' ') return null; // Skip empty spaces
const color = char === '#' ? 'black' : 'gray'; // Define colors based on characters
return `${x}px ${y}px 0 0 ${color}`;
})
)
.filter(Boolean) // Remove null values
.join(',\n '); // Format for better readability

// Generate the CSS content
return `
.${className} {
width: 1px;
height: 1px;
box-shadow: ${boxShadow};
transform: scale(10); /* Scale up the image */
transform-origin: top left; /* Important for scaling */
}
`;
}
57 changes: 57 additions & 0 deletions completesolution/js_vite_react_game/plugins/generateAsciiArtSvg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
* Generates an SVG string from an .atxt file's content.
* @param {string} atxtContent - The full content of the .atxt file, including the header.
* @param {string} className - The class name to use in the generated SVG.
* @returns {string} - The generated SVG string.
* @throws {Error} - Throws an error if the size in the header is invalid.
*/
export function generateAsciiArtSvg(atxtContent, className) {
// Split the content into lines
const lines = atxtContent.trim().split('\n');

// Parse the header
const header = lines[0];
if (!header.startsWith('#ascii-art')) {
throw new Error('Invalid .atxt file: Missing #ascii-art header.');
}

// Extract the size from the header (e.g., "10x10")
const sizeMatch = header.match(/#ascii-art (\d+)x(\d+)/);
if (!sizeMatch) {
throw new Error('Invalid .atxt file: Missing or invalid size in header.');
}
const [_, width, height] = sizeMatch.map(Number);

// Extract the ASCII art content
const asciiArt = lines.slice(1);

// Fill missing rows with blank lines to match the specified height
const filledAsciiArt = Array.from({ length: height }, (_, y) => {
return asciiArt[y] ? asciiArt[y].padEnd(width, ' ') : ' '.repeat(width);
});

// Generate the SVG `<rect>` elements
const rects = filledAsciiArt
.flatMap((line, y) =>
line.split('').map((char, x) => {
if (char === ' ') return null; // Skip empty spaces
const color = char === '#' ? 'black' : 'gray'; // Define colors based on characters
return `<rect x="${x}" y="${y}" width="1" height="1" fill="${color}" />`;
})
)
.filter(Boolean) // Remove null values
.join('\n '); // Format for better readability

// Generate the full SVG content
return `
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 ${width} ${height}"
width="${width * 10}" // Scale width by 20x
height="${height * 10}" // Scale height by 20x
class="${className}"
>
${rects}
</svg>
`;
}
1 change: 1 addition & 0 deletions completesolution/js_vite_react_game/public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
42 changes: 42 additions & 0 deletions completesolution/js_vite_react_game/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}

.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}

.card {
padding: 2em;
}

.read-the-docs {
color: #888;
}
Loading