🔌 Integration Guides

GameplayGen is engine-agnostic — it's a REST API that any HTTP client can call. Here are quick-start guides for the most popular game engines and web frameworks.

🎮 Unity (C#)

Use UnityWebRequest to call the API from a coroutine. Works in both Editor and builds (all platforms).

csharp
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class GameplayGenClient : MonoBehaviour
{
    [SerializeField] private string apiKey = "gg_live_...";

    public IEnumerator GenerateSokoban(int count = 5, float difficulty = 0.5f)
    {
        string json = JsonUtility.ToJson(new GenerateRequest {
            gameType = "sokoban",
            count = count,
            difficulty = new DifficultyConfig { target = difficulty }
        });

        using var request = new UnityWebRequest(
            "https://api.gameplaygen.com/generate", "POST");
        request.uploadHandler = new UploadHandlerRaw(
            System.Text.Encoding.UTF8.GetBytes(json));
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Authorization", "Bearer " + apiKey);

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            string responseJson = request.downloadHandler.text;
            // Parse with JsonUtility or Newtonsoft.Json
            Debug.Log($"Generated {count} puzzles!");
        }
        else
        {
            Debug.LogError($"GameplayGen error: {request.error}");
        }
    }

    [System.Serializable]
    private struct GenerateRequest
    {
        public string gameType;
        public int count;
        public DifficultyConfig difficulty;
    }

    [System.Serializable]
    private struct DifficultyConfig
    {
        public float target;
    }
}

Tip: For WebGL builds, the API must have CORS headers configured (GameplayGen's hosted API supports CORS by default). For mobile builds, no special configuration is needed.

🏗️ Unreal Engine (C++)

Use Unreal's built-in FHttpModule for async HTTP requests. Works with both C++ and Blueprint (via async nodes).

cpp
// MyGameMode.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"
#include "MyGameMode.generated.h"

UCLASS()
class AMyGameMode : public AGameModeBase
{
    GENERATED_BODY()
public:
    UFUNCTION(BlueprintCallable)
    void GeneratePuzzle(FString GameType, int32 Count, float Difficulty);

private:
    void OnPuzzleGenerated(FHttpRequestPtr Req,
        FHttpResponsePtr Res, bool bSuccess);

    FString ApiKey = TEXT("gg_live_...");
};

// MyGameMode.cpp
#include "MyGameMode.h"
#include "HttpModule.h"
#include "Json.h"

void AMyGameMode::GeneratePuzzle(
    FString GameType, int32 Count, float Difficulty)
{
    auto Request = FHttpModule::Get().CreateRequest();
    Request->SetURL(TEXT("https://api.gameplaygen.com/generate"));
    Request->SetVerb(TEXT("POST"));
    Request->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
    Request->SetHeader(TEXT("Authorization"),
        FString::Printf(TEXT("Bearer %s"), *ApiKey));

    // Build JSON body
    auto Body = MakeShared<FJsonObject>();
    Body->SetStringField("gameType", GameType);
    Body->SetNumberField("count", Count);
    auto Diff = MakeShared<FJsonObject>();
    Diff->SetNumberField("target", Difficulty);
    Body->SetObjectField("difficulty", Diff);

    FString BodyStr;
    TSharedRef<TJsonWriter<>> Writer =
        TJsonWriterFactory<>::Create(&BodyStr);
    FJsonSerializer::Serialize(Body.ToSharedRef(), Writer);
    Request->SetContentAsString(BodyStr);

    Request->OnProcessRequestComplete().BindUObject(
        this, &AMyGameMode::OnPuzzleGenerated);
    Request->ProcessRequest();
}

void AMyGameMode::OnPuzzleGenerated(
    FHttpRequestPtr Req, FHttpResponsePtr Res, bool bSuccess)
{
    if (bSuccess && Res->GetResponseCode() == 200)
    {
        TSharedPtr<FJsonObject> Json;
        TSharedRef<TJsonReader<>> Reader =
            TJsonReaderFactory<>::Create(Res->GetContentAsString());
        FJsonSerializer::Deserialize(Reader, Json);

        auto Content = Json->GetArrayField("content");
        UE_LOG(LogTemp, Log, TEXT("Generated %d puzzles"),
            Content.Num());
    }
}

⚛️ Web / React

For web games and React apps, use the standard fetch API. Works with any framework (React, Vue, Svelte, vanilla JS).

typescript
// lib/gameplaygen.ts
const API_URL = "https://api.gameplaygen.com/generate";
const API_KEY = process.env.NEXT_PUBLIC_GAMEPLAYGEN_KEY!;

interface GenerateOptions {
  gameType: string;
  params?: Record<string, unknown>;
  count?: number;
  difficulty?: number;
}

export async function generateContent(options: GenerateOptions) {
  const res = await fetch(API_URL, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      gameType: options.gameType,
      params: options.params ?? {},
      count: options.count ?? 1,
      difficulty: { target: options.difficulty ?? 0.5 },
    }),
  });

  if (!res.ok) throw new Error(`API error: ${res.status}`);
  return res.json();
}

// Usage in a React component:
function PuzzleGame() {
  const [puzzle, setPuzzle] = useState(null);

  const handleGenerate = async () => {
    const { content } = await generateContent({
      gameType: "sudoku",
      params: { difficulty: "medium" },
      difficulty: 0.5,
    });
    setPuzzle(content[0]);
  };

  return (
    <button onClick={handleGenerate}>New Puzzle</button>
  );
}

🔑 API Key Security

Server-side recommended: For production, call GameplayGen from your backend (not directly from the client) to keep your API key secure. Pre-generate content batches and serve them to players, or proxy requests through your server.

typescript
// Next.js API route (server-side proxy)
// app/api/puzzles/route.ts
export async function GET(request: Request) {
  const res = await fetch("https://api.gameplaygen.com/generate", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.GAMEPLAYGEN_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      gameType: "nonogram",
      params: { width: 10, height: 10, pattern: "symmetric" },
      count: 5,
      difficulty: { target: 0.4 },
    }),
  });
  return Response.json(await res.json());
}