Skip to content

SantasLair/CS-Compiler-With-Runtime-AI-Experiment

Repository files navigation

PixelMan C# to JavaScript Bytecode Compiler

🤖 AI Experiment: This project was created as an AI-assisted experiment to explore the feasibility of C# to JavaScript bytecode compilation for game development.

This project demonstrates a complete C# to JavaScript bytecode compilation system for game development using Phaser. The original TypeScript/JavaScript Phaser game has been rewritten in C#, and a custom compiler translates the C# code into bytecode that can be executed by a JavaScript runtime.

🧪 Experimental Nature

This is an experimental proof-of-concept created with AI assistance to demonstrate:

  • Cross-language compilation techniques
  • Virtual machine implementation in JavaScript
  • Game engine integration across different programming paradigms
  • Educational exploration of compiler design and runtime systems

Note: This project prioritizes demonstrating core concepts over production-ready implementation.

🏗️ Project Structure

├── csharp-game/                 # C# game source code
│   ├── GameConfig.cs           # Game configuration and main entry point
│   ├── Scene.cs                # Base scene class and Phaser abstractions
│   ├── GameObject.cs           # Base game object and image classes
│   ├── Player.cs               # Player character implementation
│   ├── Scenes/                 # Game scenes
│   │   ├── Boot.cs            # Boot scene for initial loading
│   │   ├── Preloader.cs       # Asset preloader scene
│   │   └── MainScene.cs       # Main game scene
│   └── Compiler/               # C# to bytecode compiler
│       ├── CSharpCompiler.cs   # Main compiler implementation
│       └── CompilerProgram.cs  # Compiler executable program
├── compiled-game/              # JavaScript runtime and demo
│   ├── index.html             # Demo web page
│   ├── js-runtime.js          # JavaScript bytecode runtime
│   └── assets/                # Game assets (images, etc.)
└── README.md                  # This file

🎯 Features

C# Game Implementation

  • Object-Oriented Design: Full C# classes with inheritance, properties, and methods
  • Game Logic: Player movement, grid-based positioning, input handling
  • Scene Management: Boot, Preloader, and Main game scenes
  • Phaser Integration: C# abstractions for Phaser concepts

Custom Compiler

  • Source Parsing: Regex-based C# source code analysis
  • Class Extraction: Automatic detection of classes, methods, fields, and properties
  • Bytecode Generation: Stack-based virtual machine instructions
  • JSON Output: Human-readable bytecode format

JavaScript Runtime

  • Virtual Machine: Stack-based execution engine
  • Phaser Bridge: Seamless integration with Phaser 3 engine
  • Object Management: Dynamic game object creation and lifecycle
  • Input Handling: Keyboard input processing and game state management

🚀 How It Works

1. C# Source Code

The game is written in C# using familiar object-oriented patterns:

public class Player : Image
{
    private float speed = 6.0f;
    private bool moving = false;
    
    public override void Update(float time, float delta)
    {
        // Game logic here
    }
}

2. Compilation Process

The compiler parses C# source files and generates bytecode:

{
  "Instructions": [
    { "OpCode": "LOAD_CONST", "Operand": "6.0", "Address": 0 },
    { "OpCode": "STORE_VAR", "Operand": "speed", "Address": 1 },
    { "OpCode": "CALL_METHOD", "Operand": "Update", "Address": 2 }
  ]
}

3. JavaScript Execution

The runtime executes bytecode instructions using a stack-based virtual machine:

switch (instruction.OpCode) {
    case 'LOAD_CONST':
        this.stack.push(this.parseValue(instruction.Operand));
        break;
    case 'CALL_METHOD':
        this.handleMethodCall(instruction.Operand);
        break;
}

🎮 Running the Demo

  1. Open the Demo: Navigate to compiled-game/index.html in a web browser
  2. Compile: Click "🔨 Compile C# Code" to simulate the compilation process
  3. Load: Click "📦 Load Bytecode" to load the generated bytecode
  4. Start: Click "🚀 Start Game" to begin execution
  5. Play: Use arrow keys to move the pixel character

🛠️ Technology Stack

  • C# Source Language: Object-oriented game logic
  • Custom Compiler: Regex-based parsing and bytecode generation
  • JSON Bytecode: Intermediate representation format
  • JavaScript Runtime: Stack-based virtual machine
  • Phaser 3: Game engine for rendering and input
  • HTML5 Canvas: Graphics rendering target

📋 Supported C# Features

Classes and Inheritance

  • Class definitions with base classes
  • Method overriding (virtual/override)
  • Static and instance members
  • Properties with getters/setters

Methods and Functions

  • Parameter parsing and default values
  • Return types and void methods
  • Method calls with arguments
  • Constructor calls

Data Types

  • Primitive types (int, float, bool, string)
  • Object references and collections
  • Automatic type inference where possible

Control Flow

  • Basic expressions and assignments
  • Method invocation chains
  • Property access and modification

🔧 Compiler Architecture

Parser Components

  • Class Extractor: Identifies class definitions and inheritance
  • Method Parser: Extracts method signatures and bodies
  • Statement Analyzer: Breaks down method bodies into statements
  • Bytecode Generator: Converts statements to VM instructions

Bytecode Instructions

  • LOAD_CONST: Push constant value onto stack
  • STORE_VAR: Pop value and store in variable
  • CALL_METHOD: Invoke method with stack arguments
  • CALL_CONSTRUCTOR: Create new object instance
  • RETURN: Return from current method

Runtime Features

  • Stack Management: Automatic stack operations
  • Object Lifecycle: Creation, storage, and cleanup
  • Method Dispatch: Dynamic method resolution
  • Phaser Integration: Seamless game engine bridge

🎯 Game Features

Player Movement

  • Grid-based tile movement (64px tiles)
  • Smooth interpolation between positions
  • Diagonal movement support
  • Input delay for responsive controls

Scene Management

  • Boot scene for initial setup
  • Preloader for asset management
  • Main scene for gameplay
  • Scene transitions and state management

Debug Features

  • Real-time position tracking
  • Movement state visualization
  • Console logging for runtime analysis
  • Step-by-step execution monitoring

🚧 Future Enhancements

Compiler Improvements

  • More sophisticated C# parsing (AST-based)
  • Support for generics and advanced language features
  • Optimization passes for bytecode efficiency
  • Error handling and debugging information

Runtime Extensions

  • Garbage collection for object management
  • Exception handling and error recovery
  • Performance profiling and optimization
  • Advanced Phaser feature integration

Game Features

  • Collision detection and physics
  • Animation system integration
  • Audio and sound effects
  • Level loading and progression

📖 Educational Value

This project demonstrates several important concepts:

  • Language Implementation: How compilers parse and translate source code
  • Virtual Machines: Stack-based execution and instruction processing
  • Game Architecture: Scene management and object-oriented design
  • Cross-Language Integration: Bridging C# concepts with JavaScript execution
  • Bytecode Systems: Intermediate representations and runtime interpretation

🤝 Contributing

This is a demonstration project showing the feasibility of C# to JavaScript bytecode compilation for game development. The implementation focuses on core concepts rather than production-ready features.

📄 License

This project is provided as an educational example and demonstration of compiler and runtime implementation techniques.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published