diff --git a/.github/ci/ci-members.json b/.github/ci/ci-members.json index 9792f1bb9b0..ffdec78b9bb 100644 --- a/.github/ci/ci-members.json +++ b/.github/ci/ci-members.json @@ -411,6 +411,7 @@ "CodenameOne/src/com/codename1/db/sql/**", "CodenameOne/src/com/codename1/hardware/**", "CodenameOne/src/com/codename1/realtime/**", + "CodenameOne/src/com/codename1/gaming/platformer/*.java", "CodenameOne/src/com/codename1/qrcode/QrCode.java", "CodenameOne/src/com/codename1/impl/office/Snappy.java", "CodenameOne/src/com/codename1/impl/MdnsEngine.java", @@ -735,6 +736,7 @@ "scripts/splat/**", "scripts/skirmish/**", "scripts/papercut/**", + "scripts/ledge/**", "scripts/dash/**", "scripts/parley/**", "scripts/hellocodenameone/common/src/main/kmp/**", @@ -779,6 +781,7 @@ "scripts/splat/**", "scripts/skirmish/**", "scripts/papercut/**", + "scripts/ledge/**", "scripts/dash/**", "scripts/parley/**", "scripts/hellocodenameone/common/src/main/kmp/**", @@ -816,6 +819,7 @@ "scripts/splat/**", "scripts/skirmish/**", "scripts/papercut/**", + "scripts/ledge/**", "scripts/dash/**", "scripts/hellocodenameone/common/src/main/kmp/**", "docs/website/content/blog/**", diff --git a/.github/workflows/developer-guide-docs.yml b/.github/workflows/developer-guide-docs.yml index cf96c472190..1dbc236305c 100644 --- a/.github/workflows/developer-guide-docs.yml +++ b/.github/workflows/developer-guide-docs.yml @@ -76,6 +76,7 @@ jobs: - 'scripts/bazaar/**' - 'scripts/skirmish/**' - 'scripts/papercut/**' + - 'scripts/ledge/**' - 'scripts/dash/**' - 'scripts/parley/**' - 'scripts/reel/**' diff --git a/.github/workflows/initializr-e2e.yml b/.github/workflows/initializr-e2e.yml index 506687bae33..ce43f4e3d67 100644 --- a/.github/workflows/initializr-e2e.yml +++ b/.github/workflows/initializr-e2e.yml @@ -24,6 +24,7 @@ on: - 'scripts/bazaar/common/src/test/**' - 'scripts/skirmish/common/src/test/**' - 'scripts/papercut/common/src/test/**' + - 'scripts/ledge/common/src/test/**' - 'scripts/dash/common/src/test/**' - 'scripts/parley/common/src/test/**' - 'scripts/reel/common/src/test/**' @@ -62,7 +63,7 @@ jobs: strategy: fail-fast: false matrix: - template: [BAREBONES, KOTLIN, WAYLINE, SAVOR, SKIRMISH, DASH, SPLAT, PAPERCUT, PARLEY, BASTION, REEL, PULSE, SLATE, FIELDLINE, BAZAAR] + template: [BAREBONES, KOTLIN, WAYLINE, SAVOR, SKIRMISH, DASH, SPLAT, PAPERCUT, PARLEY, BASTION, REEL, PULSE, SLATE, FIELDLINE, BAZAAR, LEDGE] java: ['17'] # Developers download on current JDKs too: Kotlin 1.6.0 crashed on 25 # ("IllegalArgumentException: 25") while every 17 leg was green. diff --git a/.github/workflows/samples-ios-nightly.yml b/.github/workflows/samples-ios-nightly.yml index 3cf15fa7198..c50bb97e945 100644 --- a/.github/workflows/samples-ios-nightly.yml +++ b/.github/workflows/samples-ios-nightly.yml @@ -65,7 +65,7 @@ jobs: # Watch-app samples (dash, pulse, splat, slate) are the slow ones; # they are split across the shards. - shard: a - samples: ' parley savor dash pulse bastion fieldline papercut ' + samples: ' parley savor dash pulse bastion fieldline papercut ledge ' - shard: b samples: ' wayline reel splat slate skirmish bazaar ' steps: @@ -195,4 +195,7 @@ jobs: - name: 'iOS: papercut' if: ${{ !cancelled() && contains(matrix.samples, ' papercut ') }} run: scripts/ci/build-sample-ios-simulator.sh scripts/papercut + - name: 'iOS: ledge' + if: ${{ !cancelled() && contains(matrix.samples, ' ledge ') }} + run: scripts/ci/build-sample-ios-simulator.sh scripts/ledge timeout-minutes: 45 diff --git a/.github/workflows/samples.yml b/.github/workflows/samples.yml index 5f5eb98d379..6311e054039 100644 --- a/.github/workflows/samples.yml +++ b/.github/workflows/samples.yml @@ -31,6 +31,7 @@ on: - scripts/ci/start-test-database.sh - scripts/dash/** - scripts/fieldline/** + - scripts/ledge/** - scripts/papercut/** - scripts/parley/** - scripts/pulse/** @@ -85,8 +86,8 @@ jobs: env: EVENT: ${{ github.event_name }} BASE: ${{ github.event.pull_request.base.sha || '' }} - PATHS: '{"bastion": ["scripts/bastion/**", "maven/cn1-app-kit/**"], "bazaar": ["scripts/bazaar/**", "maven/cn1-app-kit/**"], "brickyard": ["scripts/brickyard/**"], "dash": ["scripts/dash/**", "maven/cn1-app-kit/**"], "fieldline": ["scripts/fieldline/**", "maven/cn1-app-kit/**"], "papercut": ["scripts/papercut/**"], "parley": ["scripts/parley/**", "maven/cn1-app-kit/**"], "pulse": ["scripts/pulse/**", "maven/cn1-app-kit/**"], "reel": ["scripts/reel/**", "maven/cn1-app-kit/**"], "savor": ["scripts/savor/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"], "skirmish": ["scripts/skirmish/**", "maven/cn1-app-kit/**"], "slate": ["scripts/slate/**", "maven/cn1-app-kit/**"], "splat": ["scripts/splat/**"], "wayline": ["scripts/wayline/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"]}' - KINDS: '{"android": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "app": ["brickyard"], "backend": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "backend-database": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "chain": ["bastion"], "client-e2e": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "ios": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "rules": ["dash", "skirmish", "splat"], "template-sync": ["bastion", "bazaar", "dash", "fieldline", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], + PATHS: '{"bastion": ["scripts/bastion/**", "maven/cn1-app-kit/**"], "bazaar": ["scripts/bazaar/**", "maven/cn1-app-kit/**"], "brickyard": ["scripts/brickyard/**"], "dash": ["scripts/dash/**", "maven/cn1-app-kit/**"], "fieldline": ["scripts/fieldline/**", "maven/cn1-app-kit/**"], "ledge": ["scripts/ledge/**"], "papercut": ["scripts/papercut/**"], "parley": ["scripts/parley/**", "maven/cn1-app-kit/**"], "pulse": ["scripts/pulse/**", "maven/cn1-app-kit/**"], "reel": ["scripts/reel/**", "maven/cn1-app-kit/**"], "savor": ["scripts/savor/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"], "skirmish": ["scripts/skirmish/**", "maven/cn1-app-kit/**"], "slate": ["scripts/slate/**", "maven/cn1-app-kit/**"], "splat": ["scripts/splat/**"], "wayline": ["scripts/wayline/**", "scripts/ci/sample-server-tests-on-database.sh", "scripts/ci/start-test-database.sh", "scripts/ci/reset-*.sh", "maven/cn1-app-kit/**"]}' + KINDS: '{"android": ["bastion", "bazaar", "dash", "fieldline", "ledge", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "app": ["brickyard"], "backend": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "ledge", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "backend-database": ["bastion", "bazaar", "brickyard", "dash", "fieldline", "ledge", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "chain": ["bastion"], "client-e2e": ["bastion", "bazaar", "dash", "fieldline", "ledge", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "ios": ["bastion", "bazaar", "dash", "fieldline", "ledge", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "rules": ["dash", "skirmish", "splat"], "template-sync": ["bastion", "bazaar", "dash", "fieldline", "ledge", "papercut", "parley", "pulse", "reel", "savor", "skirmish", "slate", "splat", "wayline"], "web": ["bastion", "bazaar", "fieldline", "parley", "pulse", "reel", "savor", "slate", "wayline"]}' run: | python3 - <<'EOF' @@ -143,6 +144,10 @@ jobs: run: | python3 scripts/sync-initializr-template.py papercut if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' papercut ') }} + - name: 'ledge: Compare the template with scripts/ledge' + run: | + python3 scripts/sync-initializr-template.py ledge + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} - name: 'parley: Compare the template with scripts/parley' run: python3 scripts/sync-initializr-template.py parley if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' parley ') }} @@ -395,6 +400,35 @@ jobs: path: scripts/papercut/backend/target/surefire-reports/** if-no-files-found: warn retention-days: 14 + - name: 'ledge: Run the server tests on the JVM and compiled' + working-directory: scripts/ledge + run: | + mvn -B -Dcodename1.platform=backend -pl shared,backend test \ + -Dcn1.backend.compiledTests=true \ + -Dmaven.repo.local="$GITHUB_WORKSPACE/.m2-repo" + env: + JAVA_HOME: ${{ env.JDK_17_HOME }} + JDK_8_HOME: ${{ env.JDK_8_HOME }} + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} + - name: 'ledge: Check that both runners reported' + working-directory: scripts/ledge/backend/target/surefire-reports + run: | + jvm=$(find . -maxdepth 1 -name 'TEST-*.xml' ! -name '*-compiled.xml' | wc -l) + compiled=$(find . -maxdepth 1 -name 'TEST-*-compiled.xml' | wc -l) + echo "JVM reports: $jvm, compiled reports: $compiled" + if [ "$jvm" -eq 0 ] || [ "$compiled" -eq 0 ]; then + echo "::error::a runner produced no test reports" + exit 1 + fi + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} + - name: 'ledge: Upload the test reports' + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') && (!cancelled()) }} + uses: actions/upload-artifact@v7 + with: + name: ledge-backend-tests + path: scripts/ledge/backend/target/surefire-reports/** + if-no-files-found: warn + retention-days: 14 - name: 'parley: Run the server tests on the JVM and compiled' working-directory: scripts/parley run: | @@ -875,6 +909,26 @@ jobs: path: scripts/papercut/backend/target/surefire-reports/** if-no-files-found: warn retention-days: 14 + - name: 'ledge: Run the server tests on ${{ matrix.database }}' + run: | + if [ "${{ matrix.database }}" = mysql ]; then + export CN1_TEST_DATABASE_URL="mysql://cn1:secret@127.0.0.1:3306/cn1?sslmode=disable" + else + export CN1_TEST_DATABASE_URL="postgres://cn1:secret@localhost:5432/cn1?sslmode=disable" + fi + scripts/ci/sample-server-tests-on-database.sh scripts/ledge \ + -Dmaven.repo.local="$GITHUB_WORKSPACE/.m2-repo" + env: + JAVA_HOME: ${{ env.JDK_17_HOME }} + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') && (matrix.database == 'postgresql' || matrix.database == 'mysql') }} + - name: 'ledge: Upload the test reports' + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') && (matrix.database == 'postgresql' || matrix.database == 'mysql') && (always()) }} + uses: actions/upload-artifact@v7 + with: + name: ledge-backend-${{ matrix.database }}-tests + path: scripts/ledge/backend/target/surefire-reports/** + if-no-files-found: warn + retention-days: 14 - name: 'parley: Run the server tests on ${{ matrix.database }}' run: | if [ "${{ matrix.database }}" = mysql ]; then @@ -1228,6 +1282,30 @@ jobs: scripts/papercut/target/e2e-server.log if-no-files-found: warn retention-days: 14 + - name: 'ledge: Build a project generated from the Initializr template' + run: | + export JDK_8_HOME="${JAVA_HOME_8}" + export JAVA_HOME="${JAVA_HOME_17}" + export PATH="${JAVA_HOME_17}/bin:$PATH" + scripts/ledge/check-template.sh "$RUNNER_TEMP/ledge-template" + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} + - name: 'ledge: Run the application against the server' + run: | + export JDK_8_HOME="${JAVA_HOME_8}" + export JAVA_HOME="${JAVA_HOME_17}" + export PATH="${JAVA_HOME_17}/bin:$PATH" + scripts/ledge/run-e2e.sh + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} + - name: 'ledge: Upload the captures and the server log' + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') && (!cancelled()) }} + uses: actions/upload-artifact@v7 + with: + name: ledge-e2e + path: | + scripts/ledge/target/e2e-shots/** + scripts/ledge/target/e2e-server.log + if-no-files-found: warn + retention-days: 14 - name: 'parley: Build a project generated from the Initializr template' run: | export JDK_8_HOME="${JAVA_HOME_8}" @@ -1697,6 +1775,14 @@ jobs: if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' papercut ') }} env: CN1_APP_DIR: scripts/papercut + - name: 'ledge: Build the Android application' + run: | + mkdir -p ~/.codenameone + cp maven/UpdateCodenameOne.jar ~/.codenameone/ + ./scripts/build-android-app.sh -q -DskipTests + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} + env: + CN1_APP_DIR: scripts/ledge - name: 'parley: Build the Android application' run: | mkdir -p ~/.codenameone @@ -1971,6 +2057,51 @@ jobs: if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' papercut ') }} env: CN1_APP_DIR: scripts/papercut + - name: 'ledge: Generate the Xcode project' + id: build-ios-app-ledge + run: ./scripts/build-ios-app.sh -q -DskipTests + timeout-minutes: 25 + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} + env: + CN1_APP_DIR: scripts/ledge + - name: 'ledge: Build the application for the simulator' + run: | + set -euo pipefail + WORKSPACE='${{ steps.build-ios-app-ledge.outputs.workspace }}' + SCHEME='${{ steps.build-ios-app-ledge.outputs.scheme }}' + DERIVED_DATA="${{ runner.temp }}/ledge-dd" + rm -rf "$DERIVED_DATA" + # One architecture, the host's: the port's SIMD natives are NEON + # under __aarch64__, and a universal simulator build compiles an + # x86_64 slice that has no use here. + HOST_ARCH="$(uname -m)" + case "$HOST_ARCH" in + arm64|x86_64) BUILD_ARCH="$HOST_ARCH" ;; + *) BUILD_ARCH=arm64 ;; + esac + XCB_CONTAINER_FLAG="-workspace" + if [[ "$WORKSPACE" != *.xcworkspace ]]; then + XCB_CONTAINER_FLAG="-project" + fi + # No -sdk: it forces every target of the scheme onto the iPhone SDK, the + # embedded watch app included, whose watch-only icon then has nothing to + # compile for. The destination picks each target's own SDK. + xcodebuild "$XCB_CONTAINER_FLAG" "$WORKSPACE" -scheme "$SCHEME" \ + -configuration Debug \ + -destination 'generic/platform=iOS Simulator' \ + -derivedDataPath "$DERIVED_DATA" \ + ARCHS="$BUILD_ARCH" ONLY_ACTIVE_ARCH=YES \ + EXCLUDED_ARCHS="armv7 armv7s" \ + CODE_SIGNING_ALLOWED=NO build + APP_BUNDLE="$(find "$DERIVED_DATA/Build/Products" -maxdepth 3 -type d -name "${SCHEME}.app" | head -n 1)" + if [ -z "$APP_BUNDLE" ]; then + echo "::error::no .app bundle under $DERIVED_DATA" + exit 1 + fi + timeout-minutes: 20 + if: ${{ !cancelled() && contains(needs.select.outputs.samples, ' ledge ') }} + env: + CN1_APP_DIR: scripts/ledge - name: 'pulse: Generate the Xcode project' id: build-ios-app-pulse run: ./scripts/build-ios-app.sh -q -DskipTests diff --git a/CodenameOne/src/com/codename1/gaming/SpriteRenderer.java b/CodenameOne/src/com/codename1/gaming/SpriteRenderer.java index 99f9fa6fd86..f88017946d9 100644 --- a/CodenameOne/src/com/codename1/gaming/SpriteRenderer.java +++ b/CodenameOne/src/com/codename1/gaming/SpriteRenderer.java @@ -582,9 +582,12 @@ private float[] billboardMatrix(Sprite s) { float w = s.getRenderWidth() * s.getScaleX(); float h = s.getRenderHeight() * s.getScaleY(); - // y-up anchor offset (image y is top-down, world y is up) + // y-up anchor offset. The anchor is in image space, y down, so anchor + // 1 is the bottom edge: the quad must then lie above the position, + // an offset of +0.5. It was 0.5 - anchorY, which hung a sprite + // anchored at its feet one height below the ground it stood on. float[] anchor = Matrix4.translation(0.5f - (float) s.getAnchorX(), - 0.5f - (float) s.getAnchorY(), 0f); + (float) s.getAnchorY() - 0.5f, 0f); float[] scale = Matrix4.scaling(w, h, 1f); float[] roll = Matrix4.rotation((float) -Math.toRadians(s.getRotation()), 0f, 0f, 1f); float[] basis = gameCamera.getBillboardBasis(); diff --git a/CodenameOne/src/com/codename1/gaming/physics/ContactFilter.java b/CodenameOne/src/com/codename1/gaming/physics/ContactFilter.java new file mode 100644 index 00000000000..b248d653751 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/physics/ContactFilter.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.physics; + +/// Decides, step by step, whether two touching bodies in a `PhysicsWorld` push +/// on each other. Install with `PhysicsWorld#setContactFilter(ContactFilter)`. +/// +/// Returning false lets the bodies pass through each other for this step only; +/// the question is asked again on the next step while they still overlap. That +/// is how one-way platforms, team pass-through and "ghost" pickups are made -- +/// `PhysicsWorld#setOneWay(PhysicsBody, boolean)` is the stock one-way rule. +/// +/// Called from inside `PhysicsWorld#step(float)`. Do not create or destroy +/// bodies here. +public interface ContactFilter { + /// Whether two bodies collide this step. + /// + /// #### Parameters + /// + /// - `a`: one body + /// - `b`: the other + /// - `normalX`: the contact normal from `a` to `b`, screen space + /// - `normalY`: the contact normal from `a` to `b`, screen space (positive is + /// down) + /// + /// #### Returns + /// + /// false to let them pass through each other this step + boolean shouldCollide(PhysicsBody a, PhysicsBody b, float normalX, float normalY); +} diff --git a/CodenameOne/src/com/codename1/gaming/physics/PhysicsWorld.java b/CodenameOne/src/com/codename1/gaming/physics/PhysicsWorld.java index 49a3553c9e2..b62e90c1b5e 100644 --- a/CodenameOne/src/com/codename1/gaming/physics/PhysicsWorld.java +++ b/CodenameOne/src/com/codename1/gaming/physics/PhysicsWorld.java @@ -225,15 +225,51 @@ public void removeBody(PhysicsBody body) { if (bodies.remove(body)) { world.destroyBody(body.getNativeBody()); } + if (contactDispatcher != null) { + contactDispatcher.oneWay.remove(body); + } } /// Registers a contact listener notified when bodies start and stop touching. public void addContactListener(ContactListener listener) { + dispatcher().add(listener); + } + + private ContactDispatcher dispatcher() { if (contactDispatcher == null) { contactDispatcher = new ContactDispatcher(); world.setContactListener(contactDispatcher); } - contactDispatcher.add(listener); + return contactDispatcher; + } + + /// Installs a filter that can let touching bodies pass through each other, + /// asked on every step of every contact. Runs after the one-way rule of + /// `#setOneWay(PhysicsBody, boolean)`. + /// + /// #### Parameters + /// + /// - `filter`: the filter, or null for none + public void setContactFilter(ContactFilter filter) { + dispatcher().filter = filter; + } + + /// Makes a body a one-way platform: others land on its top and pass through + /// it from below and from the sides, as a jump-through ledge does. + /// + /// #### Parameters + /// + /// - `body`: the platform, normally static or kinematic + /// - `oneWay`: true to make it one-way, false to make it solid again + public void setOneWay(PhysicsBody body, boolean oneWay) { + ContactDispatcher d = dispatcher(); + if (oneWay) { + if (!d.oneWay.contains(body)) { + d.oneWay.add(body); + } + } else { + d.oneWay.remove(body); + } } public void removeContactListener(ContactListener listener) { @@ -396,6 +432,10 @@ static com.codename1.gaming.physics.box2d.dynamics.BodyType toBox2d(BodyType typ /// needed. private static final class ContactDispatcher implements com.codename1.gaming.physics.box2d.callbacks.ContactListener { private final List listeners = new ArrayList(); + private final List oneWay = new ArrayList(); + private final com.codename1.gaming.physics.box2d.collision.WorldManifold manifold = + new com.codename1.gaming.physics.box2d.collision.WorldManifold(); + private ContactFilter filter; void add(ContactListener l) { listeners.add(l); @@ -423,6 +463,33 @@ public void endContact(com.codename1.gaming.physics.box2d.dynamics.contacts.Cont @Override public void preSolve(com.codename1.gaming.physics.box2d.dynamics.contacts.Contact contact, com.codename1.gaming.physics.box2d.collision.Manifold oldManifold) { + if (filter == null && oneWay.isEmpty()) { + return; + } + Object ua = contact.getFixtureA().getBody().getUserData(); + Object ub = contact.getFixtureB().getBody().getUserData(); + if (!(ua instanceof PhysicsBody) || !(ub instanceof PhysicsBody)) { + return; + } + PhysicsBody a = (PhysicsBody) ua; + PhysicsBody b = (PhysicsBody) ub; + contact.getWorldManifold(manifold); + // Box2D's normal points from A to B with y up; the API is y down. + float nx = manifold.normal.x; + float ny = -manifold.normal.y; + // A one-way platform holds a body only when the body is above it: + // the normal from platform to body points up the screen. + if (oneWay.contains(a) && ny > -0.5f) { + contact.setEnabled(false); + return; + } + if (oneWay.contains(b) && ny < 0.5f) { + contact.setEnabled(false); + return; + } + if (filter != null && !filter.shouldCollide(a, b, nx, ny)) { + contact.setEnabled(false); + } } @Override diff --git a/CodenameOne/src/com/codename1/gaming/platformer/AIBrain.java b/CodenameOne/src/com/codename1/gaming/platformer/AIBrain.java new file mode 100644 index 00000000000..d4d9c5e58b0 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/AIBrain.java @@ -0,0 +1,484 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +import java.util.ArrayList; +import java.util.List; + +/// Enemy behaviour as a small state machine of actions and decisions, after Corgi +/// Engine's AI Brain. +/// +/// A brain does not move anything itself. Each tick it produces the `Input` bits +/// its actor would get from a player, so an enemy runs on exactly the same +/// abilities and collision as the hero, and is as deterministic. The current +/// `State` runs its `Action`, then its transitions are tried in order and the first +/// `Decision` that holds switches state. +/// +/// ```java +/// AIBrain brain = new AIBrain(); +/// AIBrain.State patrol = brain.addState("patrol", new AIBrain.Patrol()); +/// AIBrain.State chase = brain.addState("chase", new AIBrain.Chase(true)); +/// patrol.addTransition(new AIBrain.TargetWithin(Fx.of(96), true), chase); +/// chase.addTransition(new AIBrain.Not(new AIBrain.TargetWithin(Fx.of(160), false)), patrol); +/// enemy.setBrain(brain); +/// ``` +@com.codename1.impl.SharedWithBackend +public final class AIBrain { + /// Produces input for one tick. + public interface Action { + /// Computes this tick's buttons. + /// + /// #### Parameters + /// + /// - `brain`: the brain, for its timers and target + /// - `self`: the actor + /// - `world`: the world + /// + /// #### Returns + /// + /// `Input` bits + int act(AIBrain brain, Actor self, PlatformWorld world); + } + + /// A condition that switches state. + public interface Decision { + /// Whether the transition should fire. + /// + /// #### Parameters + /// + /// - `brain`: the brain + /// - `self`: the actor + /// - `world`: the world + /// + /// #### Returns + /// + /// true to switch + boolean decide(AIBrain brain, Actor self, PlatformWorld world); + } + + /// A named state: an action and its outgoing transitions. + public static final class State { + private final String name; + private final Action action; + private final List decisions = new ArrayList(); + private final List targets = new ArrayList(); + + State(String name, Action action) { + this.name = name; + this.action = action; + } + + /// The state's name. + /// + /// #### Returns + /// + /// the name + public String getName() { + return name; + } + + /// Adds a transition, tried after earlier ones. + /// + /// #### Parameters + /// + /// - `d`: the condition + /// - `target`: the state to switch to + /// + /// #### Returns + /// + /// this state, for chaining + public State addTransition(Decision d, State target) { + decisions.add(d); + targets.add(target); + return this; + } + } + + private final List states = new ArrayList(); + private State current; + private int ticksInState; + private int direction = -1; + + /// Adds a state. The first one added is where the brain starts. + /// + /// #### Parameters + /// + /// - `name`: the name + /// - `action`: what it does each tick + /// + /// #### Returns + /// + /// the state, to add transitions to + public State addState(String name, Action action) { + State s = new State(name, action); + states.add(s); + if (current == null) { + current = s; + } + return s; + } + + /// Computes the actor's input for this tick. Called by `PlatformWorld`. + /// + /// #### Parameters + /// + /// - `self`: the actor + /// - `world`: the world + /// + /// #### Returns + /// + /// `Input` bits + public int think(Actor self, PlatformWorld world) { + if (current == null) { + return 0; + } + for (int i = 0; i < current.decisions.size(); i++) { + if (current.decisions.get(i).decide(this, self, world)) { + current = current.targets.get(i); + ticksInState = 0; + break; + } + } + ticksInState++; + return current.action.act(this, self, world); + } + + /// The current state. + /// + /// #### Returns + /// + /// the state, or null for an empty brain + public State getCurrent() { + return current; + } + + /// Ticks spent in the current state. + /// + /// #### Returns + /// + /// the tick count + public int getTicksInState() { + return ticksInState; + } + + /// The patrol direction, -1 or 1, shared by the stock actions. + /// + /// #### Returns + /// + /// the direction + public int getDirection() { + return direction; + } + + /// Sets the patrol direction. + /// + /// #### Parameters + /// + /// - `d`: -1 or 1 + public void setDirection(int d) { + direction = d < 0 ? -1 : 1; + } + + long hash(long h) { + int idx = current == null ? -1 : states.indexOf(current); + return Ability.mix(Ability.mix(Ability.mix(h, idx), ticksInState), direction); + } + + private static int dirBits(int d) { + return d < 0 ? Input.LEFT : d > 0 ? Input.RIGHT : 0; + } + + /// Whether the cell ahead of an actor's feet has no floor. + /// + /// #### Parameters + /// + /// - `self`: the actor + /// - `world`: the world + /// - `dir`: -1 or 1 + /// + /// #### Returns + /// + /// true at a ledge + public static boolean ledgeAhead(Actor self, PlatformWorld world, int dir) { + Body b = self.getBody(); + TileGrid g = world.getGrid(); + int probeX = dir > 0 ? b.x + b.w + Fx.of(1) : b.x - Fx.of(1); + int k = g.get(g.col(probeX), g.row(b.y + b.h + Fx.of(1))); + return k == Tile.EMPTY || k == Tile.HAZARD || k == Tile.WATER; + } + + /// Walks back and forth, turning at walls and, if `turnAtLedges`, at drops. + public static final class Patrol implements Action { + private final boolean turnAtLedges; + + /// A patrol that turns at walls and ledges. + public Patrol() { + this(true); + } + + /// A patrol. + /// + /// #### Parameters + /// + /// - `turnAtLedges`: whether to turn at a drop instead of walking off it + public Patrol(boolean turnAtLedges) { + this.turnAtLedges = turnAtLedges; + } + + @Override + public int act(AIBrain brain, Actor self, PlatformWorld world) { + Body b = self.getBody(); + int d = brain.direction; + if ((d < 0 && b.hitLeft()) || (d > 0 && b.hitRight()) + || (turnAtLedges && b.isGrounded() && ledgeAhead(self, world, d))) { + d = -d; + brain.direction = d; + } + return dirBits(d); + } + } + + /// Moves toward the player, jumping at walls if `jumps`. + public static final class Chase implements Action { + private final boolean jumps; + + /// A chase. + /// + /// #### Parameters + /// + /// - `jumps`: whether to jump when blocked by a wall + public Chase(boolean jumps) { + this.jumps = jumps; + } + + @Override + public int act(AIBrain brain, Actor self, PlatformWorld world) { + Actor t = world.getPlayer(); + if (t == null || t == self) { // NOPMD CompareObjectsWithEquals - identity is intended + return 0; + } + Body b = self.getBody(); + Body tb = t.getBody(); + int dx = (tb.x + tb.w / 2) - (b.x + b.w / 2); + int d = dx > Fx.of(2) ? 1 : dx < -Fx.of(2) ? -1 : 0; + if (d != 0) { + brain.direction = d; + } + int bits = dirBits(d); + if (jumps && b.isGrounded() && ((d < 0 && b.hitLeft()) || (d > 0 && b.hitRight()))) { + bits |= Input.JUMP; + } + int dy = tb.y - b.y; + if (self.getGravity() == 0) { + bits |= dy < -Fx.of(2) ? Input.UP : dy > Fx.of(2) ? Input.DOWN : 0; + } + return bits; + } + } + + /// Stands still, facing the player, and fires every `interval` ticks. + public static final class Shoot implements Action { + private final int interval; + + /// A turret action. + /// + /// #### Parameters + /// + /// - `interval`: ticks between shots + public Shoot(int interval) { + this.interval = Math.max(1, interval); + } + + @Override + public int act(AIBrain brain, Actor self, PlatformWorld world) { + Actor t = world.getPlayer(); + if (t != null) { + int dx = t.getBody().x - self.getBody().x; + self.setFacing(dx < 0 ? -1 : 1); + } + return brain.ticksInState % interval == 0 ? Input.FIRE : 0; + } + } + + /// Does nothing. + public static final class Idle implements Action { + @Override + public int act(AIBrain brain, Actor self, PlatformWorld world) { + return 0; + } + } + + /// Patrols and hops every `interval` ticks. + public static final class Hop implements Action { + private final int interval; + private final Patrol patrol = new Patrol(false); + + /// A hopping patrol. + /// + /// #### Parameters + /// + /// - `interval`: ticks between hops + public Hop(int interval) { + this.interval = Math.max(2, interval); + } + + @Override + public int act(AIBrain brain, Actor self, PlatformWorld world) { + int bits = patrol.act(brain, self, world); + if (brain.ticksInState % interval < 3) { + bits |= Input.JUMP; + } + return bits; + } + } + + /// Runs two actions and combines their buttons, such as a patrol that shoots. + public static final class Both implements Action { + private final Action a; + private final Action b; + + /// A combined action. + /// + /// #### Parameters + /// + /// - `a`: the first action + /// - `b`: the second action + public Both(Action a, Action b) { + this.a = a; + this.b = b; + } + + @Override + public int act(AIBrain brain, Actor self, PlatformWorld world) { + return a.act(brain, self, world) | b.act(brain, self, world); + } + } + + /// Holds when the player is within a distance, and optionally in front. + public static final class TargetWithin implements Decision { + private final int range; + private final boolean inFront; + + /// A range check. + /// + /// #### Parameters + /// + /// - `range`: the distance, fixed point, measured on each axis + /// - `inFront`: whether the player must also be on the facing side + public TargetWithin(int range, boolean inFront) { + this.range = range; + this.inFront = inFront; + } + + @Override + public boolean decide(AIBrain brain, Actor self, PlatformWorld world) { + Actor t = world.getPlayer(); + if (t == null || t == self || !t.isAlive()) { // NOPMD CompareObjectsWithEquals - identity is intended + return false; + } + int dx = t.getBody().x - self.getBody().x; + int dy = t.getBody().y - self.getBody().y; + if (Math.abs(dx) > range || Math.abs(dy) > range) { + return false; + } + return !inFront || (dx >= 0) == (brain.direction >= 0); + } + } + + /// Holds after a number of ticks in the current state. + public static final class After implements Decision { + private final int ticks; + + /// A timer. + /// + /// #### Parameters + /// + /// - `ticks`: the time in the state + public After(int ticks) { + this.ticks = ticks; + } + + @Override + public boolean decide(AIBrain brain, Actor self, PlatformWorld world) { + return brain.ticksInState >= ticks; + } + } + + /// Holds with a chance per tick, drawn from the world's deterministic `Rng`. + public static final class Chance implements Decision { + private final int perThousand; + + /// A random check. + /// + /// #### Parameters + /// + /// - `perThousand`: the chance per tick, out of 1000 + public Chance(int perThousand) { + this.perThousand = perThousand; + } + + @Override + public boolean decide(AIBrain brain, Actor self, PlatformWorld world) { + return world.getRng().nextInt(1000) < perThousand; + } + } + + /// Holds while the actor's health is at or below a value. + public static final class HealthAtMost implements Decision { + private final int hp; + + /// A health check, for a boss changing phase. + /// + /// #### Parameters + /// + /// - `hp`: the threshold + public HealthAtMost(int hp) { + this.hp = hp; + } + + @Override + public boolean decide(AIBrain brain, Actor self, PlatformWorld world) { + return self.getHealth() != null && self.getHealth().getCurrent() <= hp; + } + } + + /// Inverts a decision. + public static final class Not implements Decision { + private final Decision d; + + /// An inversion. + /// + /// #### Parameters + /// + /// - `d`: the decision to invert + public Not(Decision d) { + this.d = d; + } + + @Override + public boolean decide(AIBrain brain, Actor self, PlatformWorld world) { + return !d.decide(brain, self, world); + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Abilities.java b/CodenameOne/src/com/codename1/gaming/platformer/Abilities.java new file mode 100644 index 00000000000..3ba5b45ff46 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Abilities.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Creates the stock abilities by name, as level files, power-ups and the editor +/// refer to them. +@com.codename1.impl.SharedWithBackend +public final class Abilities { + private static final String[] HERO_ORDER = { + "move", "ladder", "swim", "walljump", "jump", "glide", "jetpack", "crouch", "dash", "look", "weapon" + }; + + /// Every stock ability name, in a sensible processing order for a hero. + /// + /// #### Returns + /// + /// a new array + public static String[] heroOrder() { + String[] copy = new String[HERO_ORDER.length]; + System.arraycopy(HERO_ORDER, 0, copy, 0, copy.length); + return copy; + } + + private Abilities() { + } + + /// Creates an ability. + /// + /// #### Parameters + /// + /// - `name`: `move`, `jump`, `crouch`, `ladder`, `walljump`, `dash`, `jetpack`, + /// `glide`, `swim`, `fly`, `look`, `weapon` or `sword` + /// - `tileSize`: the level's tile size, fixed point, for size-relative tuning + /// + /// #### Returns + /// + /// the ability, or null for an unknown name + public static Ability create(String name, int tileSize) { + if ("move".equals(name)) { + return new MoveAbility(); + } + if ("jump".equals(name)) { + return new JumpAbility(); + } + if ("crouch".equals(name)) { + CrouchAbility a = new CrouchAbility(); + a.crouchHeight = tileSize - Fx.of(2); + return a; + } + if ("ladder".equals(name)) { + return new LadderAbility(); + } + if ("walljump".equals(name)) { + return new WallJumpAbility(); + } + if ("dash".equals(name)) { + return new DashAbility(); + } + if ("jetpack".equals(name)) { + return new JetpackAbility(); + } + if ("glide".equals(name)) { + return new GlideAbility(); + } + if ("swim".equals(name)) { + return new SwimAbility(); + } + if ("fly".equals(name)) { + return new FlyAbility(); + } + if ("look".equals(name)) { + return new LookAbility(); + } + if ("weapon".equals(name)) { + return new WeaponAbility(); + } + if ("sword".equals(name)) { + WeaponAbility w = new WeaponAbility(); + w.projectileType = "slash"; + w.speed = 0; + w.size = tileSize; + w.lifeTicks = 8; + w.cooldownTicks = 20; + w.eightWay = false; + return w; + } + return null; + } + + /// The class of the ability a name creates, for `Actor#getAbility`. + /// + /// #### Parameters + /// + /// - `name`: an ability name + /// + /// #### Returns + /// + /// the class, or null + public static Class typeOf(String name) { + Ability a = create(name, Fx.of(16)); + return a == null ? null : a.getClass(); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Ability.java b/CodenameOne/src/com/codename1/gaming/platformer/Ability.java new file mode 100644 index 00000000000..9bda04be194 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Ability.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// One thing a `Actor` can do -- walk, jump, dash, climb -- as a small, +/// separately tunable unit, in the manner of Corgi Engine's character abilities. +/// +/// An actor runs its abilities in the order they were added, three times a tick: +/// `earlyProcess` before anything moves, `process` to set velocity and state, and +/// `lateProcess` after the body has moved and its contacts are known. Order matters +/// where two abilities read the same button: an ability that consumes the jump +/// press (a wall jump, a ladder jump) belongs before `JumpAbility`. +/// +/// Abilities must be deterministic: they read only the actor, the world and +/// the tick's input, use `Fx` arithmetic and the world's `Rng`, and keep their +/// state in fields so `Actor#hash` can fold it in through `hashState`. +@com.codename1.impl.SharedWithBackend +public abstract class Ability { + private boolean enabled = true; + + /// Whether the ability runs. A disabled ability is skipped, which is how a + /// power-up grants it mid-level. + /// + /// #### Returns + /// + /// true when enabled + public boolean isEnabled() { + return enabled; + } + + /// Enables or disables the ability. + /// + /// #### Parameters + /// + /// - `enabled`: true to run it + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + /// Runs before any ability sets velocity: timers and input edges. + /// + /// #### Parameters + /// + /// - `c`: the actor + /// - `world`: the world + public void earlyProcess(Actor c, PlatformWorld world) { + } + + /// Sets velocity and claims a `MovementState`. + /// + /// #### Parameters + /// + /// - `c`: the actor + /// - `world`: the world + public abstract void process(Actor c, PlatformWorld world); + + /// Runs after the body moved, with the new contacts. + /// + /// #### Parameters + /// + /// - `c`: the actor + /// - `world`: the world + public void lateProcess(Actor c, PlatformWorld world) { + } + + /// Mixes the ability's own state into a hash, so two runs that diverge inside + /// an ability are caught. The default mixes nothing. + /// + /// #### Parameters + /// + /// - `h`: the running hash + /// + /// #### Returns + /// + /// the updated hash + public long hashState(long h) { + return h; + } + + /// FNV-1a step used by `hashState` implementations. + /// + /// #### Parameters + /// + /// - `h`: the running hash + /// - `v`: the value to mix in + /// + /// #### Returns + /// + /// the updated hash + protected static long mix(long h, long v) { + long r = h; + for (int i = 0; i < 8; i++) { + r ^= (v >>> (i * 8)) & 0xff; + r *= 0x100000001B3L; + } + return r; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Actor.java b/CodenameOne/src/com/codename1/gaming/platformer/Actor.java new file mode 100644 index 00000000000..aa24f3e802c --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Actor.java @@ -0,0 +1,628 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +import java.util.ArrayList; +import java.util.List; + +/// A player or an enemy: a `Body` driven by an ordered list of `Ability`s. +/// +/// Each `PlatformWorld#step` the actor takes its tick of `Input` bits (from a +/// player, a replay or an `AIBrain`), runs its abilities, applies gravity unless an +/// ability turned it off, moves the body, and settles a `MovementState` that the +/// renderer animates. All tuning is in fixed point (`Fx`), in pixels and ticks at +/// 60 ticks per second. +/// +/// ```java +/// Actor hero = new Actor("hero", Fx.of(32), Fx.of(80), Fx.of(12), Fx.of(14)); +/// hero.addAbility(new MoveAbility()); +/// hero.addAbility(new LadderAbility()); +/// hero.addAbility(new WallJumpAbility()); +/// hero.addAbility(new JumpAbility()); +/// hero.addAbility(new CrouchAbility()); +/// hero.addAbility(new DashAbility()); +/// world.addActor(hero); +/// ``` +@com.codename1.impl.SharedWithBackend +public class Actor { + private final String id; + private final Body body; + private final List abilities = new ArrayList(); + private int input; + private int previousInput; + private int facing = 1; + private MovementState state = MovementState.IDLE; + private boolean stateClaimed; + private boolean gravityActive; + private int gravity = Fx.ratio(1, 4); + private int maxFall = Fx.of(6); + private int controlLock; + private int airTicks; + private boolean jumpConsumed; + private boolean alive = true; + private int defeatChannel; + private final int standHeight; + private int team; + private Health health; + private int contactDamage; + private boolean stompable; + private AIBrain brain; + private String kind = "hero"; + + /// Creates an actor. + /// + /// #### Parameters + /// + /// - `id`: a name, unique in its world + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: standing height, fixed point + public Actor(String id, int x, int y, int w, int h) { + this.id = id; + this.body = new Body(x, y, w, h); + this.standHeight = h; + } + + /// Adds an ability at the end of the processing order. + /// + /// #### Parameters + /// + /// - `a`: the ability + /// + /// #### Returns + /// + /// this actor, for chaining + public Actor addAbility(Ability a) { + abilities.add(a); + return this; + } + + /// Finds an ability by class, to tune it or switch it on. + /// + /// #### Parameters + /// + /// - `type`: the ability's class + /// + /// #### Returns + /// + /// the first ability of that class, or null + @SuppressWarnings("unchecked") + public T getAbility(Class type) { + for (int i = 0; i < abilities.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Ability a = abilities.get(i); + if (a.getClass() == type) { + return (T) a; + } + } + return null; + } + + /// Advances one tick. Called by `PlatformWorld#step`. + /// + /// #### Parameters + /// + /// - `world`: the world + /// - `bits`: this tick's `Input` + public void tick(PlatformWorld world, int bits) { + previousInput = input; + input = bits; + if (!alive) { + return; + } + if (health != null) { + health.tick(); + } + stateClaimed = false; + gravityActive = true; + jumpConsumed = false; + if (controlLock > 0) { + controlLock--; + } + for (int i = 0; i < abilities.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Ability a = abilities.get(i); + if (a.isEnabled()) { + a.earlyProcess(this, world); + } + } + for (int i = 0; i < abilities.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Ability a = abilities.get(i); + if (a.isEnabled()) { + a.process(this, world); + } + } + if (gravityActive) { + body.vy = Math.min(body.vy + gravity, maxFall); + } + body.move(world.getGrid(), world.getPlatforms()); + if (body.isGrounded()) { + airTicks = 0; + } else { + airTicks++; + } + for (int i = 0; i < abilities.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Ability a = abilities.get(i); + if (a.isEnabled()) { + a.lateProcess(this, world); + } + } + if (!stateClaimed) { + if (body.isGrounded()) { + state = body.vx == 0 ? MovementState.IDLE : MovementState.WALKING; + } else { + state = body.vy < 0 ? MovementState.JUMPING : MovementState.FALLING; + } + } + } + + /// Sets this tick's state. The first ability to claim one wins, so the order of + /// abilities is also their priority. + /// + /// #### Parameters + /// + /// - `s`: the state + public void claimState(MovementState s) { + if (!stateClaimed) { + state = s; + stateClaimed = true; + } + } + + /// Replaces this tick's state even if one was claimed, for states that override + /// everything such as being hurt. + /// + /// #### Parameters + /// + /// - `s`: the state + public void forceState(MovementState s) { + state = s; + stateClaimed = true; + } + + /// The art kind the view draws this actor with (`"hero"`, `"slime"`). + /// + /// #### Returns + /// + /// the kind + public String getKind() { + return kind; + } + + /// Sets the art kind. + /// + /// #### Parameters + /// + /// - `kind`: the kind + /// + /// #### Returns + /// + /// this actor + public Actor setKind(String kind) { + this.kind = kind; + return this; + } + + /// The team: 0 for the player's side. Projectiles and contact damage never + /// hurt their own team. + /// + /// #### Returns + /// + /// the team + public int getTeam() { + return team; + } + + /// Sets the team. + /// + /// #### Parameters + /// + /// - `team`: the team + /// + /// #### Returns + /// + /// this actor + public Actor setTeam(int team) { + this.team = team; + return this; + } + + /// Hit points, or null for an actor that dies at the first hit. + /// + /// #### Returns + /// + /// the health + public Health getHealth() { + return health; + } + + /// Gives the actor hit points. + /// + /// #### Parameters + /// + /// - `health`: the health, or null + /// + /// #### Returns + /// + /// this actor + public Actor setHealth(Health health) { + this.health = health; + return this; + } + + /// Damage dealt to actors of another team on contact. + /// + /// #### Returns + /// + /// the damage, 0 for harmless + public int getContactDamage() { + return contactDamage; + } + + /// Sets contact damage. + /// + /// #### Parameters + /// + /// - `damage`: the damage + /// + /// #### Returns + /// + /// this actor + public Actor setContactDamage(int damage) { + this.contactDamage = damage; + return this; + } + + /// Whether landing on this actor's head hurts it and bounces the player. + /// + /// #### Returns + /// + /// true if stompable + public boolean isStompable() { + return stompable; + } + + /// Sets whether the actor can be stomped. + /// + /// #### Parameters + /// + /// - `stompable`: true if stompable + /// + /// #### Returns + /// + /// this actor + public Actor setStompable(boolean stompable) { + this.stompable = stompable; + return this; + } + + /// Sets a switch channel the actor's defeat turns on, so beating a boss can + /// open the way out. 0, the default, turns nothing on. + /// + /// #### Parameters + /// + /// - `channel`: the channel + /// + /// #### Returns + /// + /// this actor + public Actor setDefeatChannel(int channel) { + this.defeatChannel = channel; + return this; + } + + /// The switch channel the actor's defeat turns on. + /// + /// #### Returns + /// + /// the channel, 0 for none + public int getDefeatChannel() { + return defeatChannel; + } + + /// The brain that drives a non-player actor, or null. + /// + /// #### Returns + /// + /// the brain + public AIBrain getBrain() { + return brain; + } + + /// Gives the actor a brain; the world then ignores its input slot. + /// + /// #### Parameters + /// + /// - `brain`: the brain, or null + /// + /// #### Returns + /// + /// this actor + public Actor setBrain(AIBrain brain) { + this.brain = brain; + return this; + } + + /// The actor's id. + /// + /// #### Returns + /// + /// the id + public String getId() { + return id; + } + + /// The collision box. + /// + /// #### Returns + /// + /// the body + public Body getBody() { + return body; + } + + /// The height the actor stands at, which crouching shrinks from. + /// + /// #### Returns + /// + /// the standing height, fixed point + public int getStandHeight() { + return standHeight; + } + + /// This tick's input bits. + /// + /// #### Returns + /// + /// the input + public int getInput() { + return input; + } + + /// Whether a button is held this tick. + /// + /// #### Parameters + /// + /// - `button`: an `Input` constant + /// + /// #### Returns + /// + /// true while held + public boolean held(int button) { + return Input.held(input, button); + } + + /// Whether a button went down this tick. + /// + /// #### Parameters + /// + /// - `button`: an `Input` constant + /// + /// #### Returns + /// + /// true on the press edge + public boolean pressed(int button) { + return Input.pressed(input, previousInput, button); + } + + /// Whether a button was released this tick. + /// + /// #### Parameters + /// + /// - `button`: an `Input` constant + /// + /// #### Returns + /// + /// true on the release edge + public boolean released(int button) { + return Input.pressed(previousInput, input, button); + } + + /// Facing: 1 right, -1 left. + /// + /// #### Returns + /// + /// the facing + public int getFacing() { + return facing; + } + + /// Sets the facing. + /// + /// #### Parameters + /// + /// - `facing`: 1 right, -1 left + public void setFacing(int facing) { + this.facing = facing < 0 ? -1 : 1; + } + + /// The state settled in the last tick. + /// + /// #### Returns + /// + /// the state + public MovementState getState() { + return state; + } + + /// Whether an ability already claimed this tick's state. + /// + /// #### Returns + /// + /// true once claimed + public boolean isStateClaimed() { + return stateClaimed; + } + + /// Turns gravity off for this tick (a ladder, a dash, a jetpack). + public void suspendGravity() { + gravityActive = false; + } + + /// Gravity, fixed point per tick squared. + /// + /// #### Returns + /// + /// the gravity + public int getGravity() { + return gravity; + } + + /// Sets gravity. + /// + /// #### Parameters + /// + /// - `gravity`: fixed point per tick squared + public void setGravity(int gravity) { + this.gravity = gravity; + } + + /// Terminal falling speed. Keep it under a tile per tick. + /// + /// #### Returns + /// + /// the speed, fixed point per tick + public int getMaxFall() { + return maxFall; + } + + /// Sets the terminal falling speed. + /// + /// #### Parameters + /// + /// - `maxFall`: fixed point per tick + public void setMaxFall(int maxFall) { + this.maxFall = maxFall; + } + + /// Locks horizontal control for a number of ticks, so a wall jump or a + /// knock-back carries the actor away before input steers again. + /// + /// #### Parameters + /// + /// - `ticks`: how long input is ignored by `MoveAbility` + public void lockControl(int ticks) { + controlLock = Math.max(controlLock, ticks); + } + + /// Whether horizontal control is locked. + /// + /// #### Returns + /// + /// true while locked + public boolean isControlLocked() { + return controlLock > 0; + } + + /// Ticks since the actor last stood on something. + /// + /// #### Returns + /// + /// 0 while grounded + public int getAirTicks() { + return airTicks; + } + + /// Marks this tick's jump press as used, so later abilities do not act on it. + public void consumeJump() { + jumpConsumed = true; + } + + /// Whether an earlier ability used this tick's jump press. + /// + /// #### Returns + /// + /// true once consumed + public boolean isJumpConsumed() { + return jumpConsumed; + } + + /// Whether the actor is alive. + /// + /// #### Returns + /// + /// false after `kill` + public boolean isAlive() { + return alive; + } + + /// Kills the actor; it stops processing until `respawn`. + public void kill() { + alive = false; + state = MovementState.DEAD; + body.vx = 0; + body.vy = 0; + } + + /// Brings the actor back at a point, standing and still. + /// + /// #### Parameters + /// + /// - `x`: left, fixed point + /// - `y`: top, fixed point + public void respawn(int x, int y) { + alive = true; + body.x = x; + body.y = y; + body.vx = 0; + body.vy = 0; + body.h = standHeight; + body.setIgnoreOneWay(false); + state = MovementState.IDLE; + controlLock = 0; + airTicks = 0; + if (health != null) { + health.reset(); + } + } + + /// The actor's state as a hash, for replay verification. + /// + /// #### Parameters + /// + /// - `h`: the running hash + /// + /// #### Returns + /// + /// the updated hash + public long hash(long h) { + long r = Ability.mix(h, body.x); + r = Ability.mix(r, body.y); + r = Ability.mix(r, body.vx); + r = Ability.mix(r, body.vy); + r = Ability.mix(r, body.h); + r = Ability.mix(r, state.ordinal()); + r = Ability.mix(r, facing); + r = Ability.mix(r, alive ? 1 : 0); + for (int i = 0; i < abilities.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + r = abilities.get(i).hashState(r); + } + if (health != null) { + r = health.hash(r); + } + if (brain != null) { + r = brain.hash(r); + } + return r; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/BlockEntity.java b/CodenameOne/src/com/codename1/gaming/platformer/BlockEntity.java new file mode 100644 index 00000000000..247b300119e --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/BlockEntity.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Base for entities that are made of solid tiles which come and go: doors, gates +/// and crumbling blocks. The rectangle must be aligned to whole tiles. +@com.codename1.impl.SharedWithBackend +public abstract class BlockEntity extends Entity { + private boolean solid; + + /// Creates a block. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `type`: the kind + /// - `x`: left, fixed point, on a tile edge + /// - `y`: top, fixed point, on a tile edge + /// - `w`: width, fixed point, whole tiles + /// - `h`: height, fixed point, whole tiles + protected BlockEntity(String id, String type, int x, int y, int w, int h) { + super(id, type, x, y, w, h); + } + + @Override + public int getTouchMargin() { + return Fx.of(2); + } + + /// Whether the block's cells are currently solid. + /// + /// #### Returns + /// + /// true while solid + public boolean isSolid() { + return solid; + } + + /// Makes the cells solid or empty. Becoming solid waits while an actor is + /// inside, so nobody is ever trapped in a wall. + /// + /// #### Parameters + /// + /// - `world`: the world + /// - `s`: true for solid + /// + /// #### Returns + /// + /// true if the cells now match `s` + protected boolean setSolid(PlatformWorld world, boolean s) { + if (s == solid) { + return true; + } + if (s) { + for (int i = 0; i < world.getActors().size(); i++) { + Actor c = world.getActors().get(i); + if (c.isAlive() && c.getBody().overlaps(x, y, w, h)) { + return false; + } + } + } + TileGrid g = world.getGrid(); + int c1 = g.col(x + w - 1); + int r1 = g.row(y + h - 1); + for (int r = g.row(y); r <= r1; r++) { + for (int c = g.col(x); c <= c1; c++) { + g.set(c, r, s ? Tile.SOLID : Tile.EMPTY); + } + } + solid = s; + return true; + } + + @Override + public long hashState(long h) { + return Ability.mix(super.hashState(h), solid ? 1 : 0); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Body.java b/CodenameOne/src/com/codename1/gaming/platformer/Body.java new file mode 100644 index 00000000000..e423767b2d9 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Body.java @@ -0,0 +1,397 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +import java.util.List; + +/// A kinematic box that moves through a `TileGrid`: the platformer's collision +/// controller. +/// +/// It is not a physics body. Each tick it is given a velocity and moves the X axis +/// and then the Y axis, scanning exactly the cells its edges cross, so it never +/// tunnels and never jitters. It understands what a platformer needs and a rigid +/// body simulation does not: +/// +/// - **Slopes** of 45 and 22.5 degrees, walked up and down at full speed without +/// bouncing: while grounded the box is snapped down to the floor by up to +/// `getStepHeight()`, and steps of that height are climbed. +/// - **One-way platforms** (`Tile#ONE_WAY`, the top rung of a ladder, a +/// `MovingPlatform`) that only stop a box falling onto them from above, and +/// that `dropThrough` lets it fall through. +/// - **Riding**: a box standing on a moving platform is carried by it. +/// - **Contacts** on each side, read back by the abilities: grounded, a ceiling, a +/// wall on the left or right. +/// +/// Coordinates are fixed point (`Fx`), y grows downward, and `x`, `y` are the +/// top-left corner. +@com.codename1.impl.SharedWithBackend +public final class Body { + /// Left edge, fixed point. + public int x; + /// Top edge, fixed point. + public int y; + /// Width, fixed point. + public int w; + /// Height, fixed point. + public int h; + /// Horizontal velocity, fixed point per tick. + public int vx; + /// Vertical velocity, fixed point per tick; positive is down. + public int vy; + + private int stepHeight; + private int previousY; + private boolean below; + private boolean above; + private boolean left; + private boolean right; + private boolean onOneWay; + private int slope; + private int dropTicks; + private boolean ignoreOneWay; + private MovingPlatform riding; + + /// Creates a box. + /// + /// #### Parameters + /// + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + public Body(int x, int y, int w, int h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + this.stepHeight = Fx.of(6); + } + + /// The tallest step the box climbs, and the furthest it is pulled down to keep + /// its footing on a falling slope, while grounded. + /// + /// #### Returns + /// + /// the step height, fixed point + public int getStepHeight() { + return stepHeight; + } + + /// Sets the step height. Keep it below half a tile; it must exceed the largest + /// horizontal speed for a 45 degree slope to be climbed. + /// + /// #### Parameters + /// + /// - `stepHeight`: the step height, fixed point + public void setStepHeight(int stepHeight) { + this.stepHeight = stepHeight; + } + + /// Lets the box fall through one-way platforms for a few ticks. + /// + /// #### Parameters + /// + /// - `ticks`: how long one-way floors are ignored + public void dropThrough(int ticks) { + dropTicks = ticks; + riding = null; + } + + /// Makes one-way floors, including the top of a ladder, ignored until cleared, + /// as climbing down a ladder needs. + /// + /// #### Parameters + /// + /// - `ignore`: true to ignore one-way floors + public void setIgnoreOneWay(boolean ignore) { + ignoreOneWay = ignore; + } + + /// Whether the box stood on something after its last move. + /// + /// #### Returns + /// + /// true when grounded + public boolean isGrounded() { + return below; + } + + /// Whether the box hit a ceiling in its last move. + /// + /// #### Returns + /// + /// true on a ceiling hit + public boolean hitCeiling() { + return above; + } + + /// Whether the box was stopped by a wall on its left in its last move. + /// + /// #### Returns + /// + /// true on a left wall + public boolean hitLeft() { + return left; + } + + /// Whether the box was stopped by a wall on its right in its last move. + /// + /// #### Returns + /// + /// true on a right wall + public boolean hitRight() { + return right; + } + + /// Whether the floor under the box is one-way (a drop-through platform). + /// + /// #### Returns + /// + /// true on a one-way floor + public boolean isOnOneWay() { + return below && onOneWay; + } + + /// The slope the box stands on. + /// + /// #### Returns + /// + /// a slope `Tile` kind, or `Tile#EMPTY` on flat ground or in the air + public int getSlope() { + return slope; + } + + /// The top edge before the last move, which tells a stomp from a side hit. + /// + /// #### Returns + /// + /// the previous y, fixed point + public int getPreviousY() { + return previousY; + } + + /// Whether the box overlaps a rectangle. + /// + /// #### Parameters + /// + /// - `ox`: left, fixed point + /// - `oy`: top, fixed point + /// - `ow`: width, fixed point + /// - `oh`: height, fixed point + /// + /// #### Returns + /// + /// true on overlap + public boolean overlaps(int ox, int oy, int ow, int oh) { + return x < ox + ow && x + w > ox && y < oy + oh && y + h > oy; + } + + /// The moving platform the box stands on. + /// + /// #### Returns + /// + /// the platform, or null + public MovingPlatform getRiding() { + return riding; + } + + /// Moves the box by its velocity through the grid and the platforms, updating + /// the contact flags. Velocity into a contact is zeroed. + /// + /// #### Parameters + /// + /// - `grid`: the level + /// - `platforms`: the moving platforms, already stepped this tick; may be null + public void move(TileGrid grid, List platforms) { + boolean wasGrounded = below; + previousY = y; + if (riding != null) { + x += riding.getDx(); + y += riding.getDy(); + } + riding = null; + below = false; + above = false; + left = false; + right = false; + onOneWay = false; + slope = Tile.EMPTY; + if (dropTicks > 0) { + dropTicks--; + } + moveX(grid, wasGrounded); + moveY(grid, platforms, wasGrounded); + } + + private void moveX(TileGrid grid, boolean wasGrounded) { + if (vx == 0) { + return; + } + int ts = grid.getTileSize(); + int r0 = grid.row(y); + int r1 = grid.row(y + h - 1 - (wasGrounded ? stepHeight : 0)); + if (r1 < r0) { + r1 = r0; + } + int nx = x + vx; + if (vx > 0) { + int cStart = grid.col(x + w); + int cEnd = grid.col(nx + w - 1); + for (int c = cStart; c <= cEnd; c++) { + if (columnBlocks(grid, c, r0, r1)) { + nx = c * ts - w; + right = true; + vx = 0; + break; + } + } + } else { + int cStart = grid.col(x - 1); + int cEnd = grid.col(nx); + for (int c = cStart; c >= cEnd; c--) { + if (columnBlocks(grid, c, r0, r1)) { + nx = (c + 1) * ts; + left = true; + vx = 0; + break; + } + } + } + x = nx; + } + + private static boolean columnBlocks(TileGrid grid, int c, int r0, int r1) { + for (int r = r0; r <= r1; r++) { + if (grid.get(c, r) == Tile.SOLID) { + return true; + } + } + return false; + } + + private void moveY(TileGrid grid, List platforms, boolean wasGrounded) { + int ts = grid.getTileSize(); + int ny = y + vy; + if (vy < 0) { + int c0 = grid.col(x); + int c1 = grid.col(x + w - 1); + int rStart = grid.row(y - 1); + int rEnd = grid.row(ny); + for (int r = rStart; r >= rEnd; r--) { + for (int c = c0; c <= c1; c++) { + if (grid.get(c, r) == Tile.SOLID) { + y = (r + 1) * ts; + above = true; + vy = 0; + return; + } + } + } + y = ny; + return; + } + int oldB = y + h; + int newB = ny + h; + boolean snapping = wasGrounded; + int probeB = snapping ? newB + stepHeight : newB; + int tol = wasGrounded ? stepHeight : 0; + boolean oneWayOk = dropTicks == 0 && !ignoreOneWay; + + int best = Integer.MAX_VALUE; + boolean bestOneWay = false; + int bestSlope = Tile.EMPTY; + MovingPlatform bestPlatform = null; + + int c0 = grid.col(x); + int c1 = grid.col(x + w - 1); + int rStart = grid.row(oldB - tol); + int rEnd = grid.row(probeB - 1); + for (int r = rStart; r <= rEnd; r++) { + int top = r * ts; + if (top < oldB - tol || top > probeB || top >= best) { + continue; + } + for (int c = c0; c <= c1; c++) { + int k = grid.get(c, r); + boolean oneWay = k == Tile.ONE_WAY + || (k == Tile.LADDER && grid.get(c, r - 1) != Tile.LADDER); + if (k == Tile.SOLID || (oneWay && oneWayOk && top >= oldB)) { + if (top < best || (top == best && !oneWay)) { + best = top; + bestOneWay = oneWay; + bestSlope = Tile.EMPTY; + bestPlatform = null; + } + } + } + } + + // Slopes are sampled under the middle of the feet. + int footX = x + w / 2; + int fc = grid.col(footX); + int lx = footX - fc * ts; + int sStart = grid.row(oldB - tol - 1); + for (int r = sStart; r <= rEnd + 1; r++) { + int k = grid.get(fc, r); + if (!Tile.isSlope(k)) { + continue; + } + int surface = r * ts + Tile.slopeDepth(k, lx, ts); + if (surface >= oldB - tol && surface <= probeB && surface < best) { + best = surface; + bestOneWay = false; + bestSlope = k; + bestPlatform = null; + } + } + + if (platforms != null && oneWayOk) { + for (int i = 0; i < platforms.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + MovingPlatform p = platforms.get(i); + int top = p.getY(); + if (x + w <= p.getX() || x >= p.getX() + p.getWidth()) { + continue; + } + if (top >= oldB - (wasGrounded ? Math.abs(p.getDy()) : 0) + && top <= probeB && top < best) { + best = top; + bestOneWay = true; + bestSlope = Tile.EMPTY; + bestPlatform = p; + } + } + } + + if (best != Integer.MAX_VALUE) { + y = best - h; + vy = 0; + below = true; + onOneWay = bestOneWay; + slope = bestSlope; + riding = bestPlatform; + } else { + y = ny; + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Checkpoint.java b/CodenameOne/src/com/codename1/gaming/platformer/Checkpoint.java new file mode 100644 index 00000000000..40ed0430daa --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Checkpoint.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A checkpoint: touching it moves the player's respawn point here. +@com.codename1.impl.SharedWithBackend +public class Checkpoint extends Entity { + private boolean reached; + + /// Creates a checkpoint. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + public Checkpoint(String id, int x, int y, int w, int h) { + super(id, "checkpoint", x, y, w, h); + } + + @Override + public int getPhase() { + return reached ? 1 : 0; + } + + @Override + public void onTouch(PlatformWorld world, Actor c) { + if (reached || c != world.getPlayer()) { // NOPMD CompareObjectsWithEquals - identity is intended + return; + } + reached = true; + Body b = c.getBody(); + world.setSpawn(x + (w - b.w) / 2, y + h - c.getStandHeight()); + world.emit(WorldEvent.CHECKPOINT, x + w / 2, y, getId(), null); + } + + @Override + public long hashState(long h) { + return Ability.mix(super.hashState(h), reached ? 1 : 0); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/CrouchAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/CrouchAbility.java new file mode 100644 index 00000000000..59348150944 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/CrouchAbility.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Crouching and crawling: holding down on the ground shrinks the body to +/// `crouchHeight`, keeping its feet in place. The actor stands again only when +/// there is room above, so it can crawl through a one-tile gap and stays crouched +/// under it. +@com.codename1.impl.SharedWithBackend +public class CrouchAbility extends Ability { + /// Height while crouched, fixed point. + public int crouchHeight = Fx.of(8); + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + MovementState s = c.getState(); + if (s == MovementState.CLIMBING || s == MovementState.DASHING || s == MovementState.DEAD) { + return; + } + boolean want = b.isGrounded() && c.held(Input.DOWN) && !c.pressed(Input.JUMP); + int stand = c.getStandHeight(); + if (want && b.h > crouchHeight) { + b.y += b.h - crouchHeight; + b.h = crouchHeight; + } else if (!want && b.h < stand) { + int grow = stand - b.h; + if (!world.getGrid().blocked(b.x, b.y - grow, b.w, grow)) { + b.y -= grow; + b.h = stand; + } + } + if (b.h < stand && b.isGrounded()) { + c.claimState(b.vx == 0 ? MovementState.CROUCHING : MovementState.CRAWLING); + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/CrumbleBlock.java b/CodenameOne/src/com/codename1/gaming/platformer/CrumbleBlock.java new file mode 100644 index 00000000000..301d633fc33 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/CrumbleBlock.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A floor that gives way: `delayTicks` after the player first stands on it, its +/// cells vanish, and they come back `respawnTicks` later (never, if 0). +@com.codename1.impl.SharedWithBackend +public class CrumbleBlock extends BlockEntity { + private final int delayTicks; + private final int respawnTicks; + private int timer = -1; + private int gone = -1; + + /// Creates a crumbling block. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `x`: left, fixed point, on a tile edge + /// - `y`: top, fixed point, on a tile edge + /// - `w`: width, whole tiles, fixed point + /// - `h`: height, whole tiles, fixed point + /// - `delayTicks`: ticks between first being stood on and giving way + /// - `respawnTicks`: ticks until it returns, 0 for never + public CrumbleBlock(String id, int x, int y, int w, int h, int delayTicks, int respawnTicks) { + super(id, "crumble", x, y, w, h); + this.delayTicks = delayTicks; + this.respawnTicks = respawnTicks; + } + + @Override + public int getPhase() { + if (!isSolid()) { + return 3; + } + if (timer < 0) { + return 0; + } + return timer * 2 < delayTicks ? 2 : 1; + } + + @Override + public void onAdded(PlatformWorld world) { + setSolid(world, true); + } + + @Override + public void step(PlatformWorld world) { + if (timer > 0) { + timer--; + if (timer == 0) { + setSolid(world, false); + timer = -1; + gone = respawnTicks; + world.emit(WorldEvent.CRUMBLE, x + w / 2, y, getId(), null); + } + } else if (gone > 0) { + gone--; + if (gone == 0 && !setSolid(world, true)) { + gone = 1; + } + } + } + + @Override + public void onTouch(PlatformWorld world, Actor c) { + Body b = c.getBody(); + if (isSolid() && timer < 0 && b.isGrounded() && b.y + b.h == y) { + timer = delayTicks; + } + } + + @Override + public long hashState(long h) { + return Ability.mix(Ability.mix(super.hashState(h), timer), gone); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/DashAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/DashAbility.java new file mode 100644 index 00000000000..a585c9d653d --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/DashAbility.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A horizontal dash on `Input#DASH`: `dashTicks` at `dashSpeed` in the facing +/// direction with gravity off, then a `cooldownTicks` wait. In the air it can be +/// used `airDashes` times before landing. +@com.codename1.impl.SharedWithBackend +public class DashAbility extends Ability { + /// Dash speed, fixed point per tick. + public int dashSpeed = Fx.of(5); + /// Dash length in ticks. + public int dashTicks = 10; + /// Ticks before the next dash. + public int cooldownTicks = 24; + /// Dashes allowed per jump. + public int airDashes = 1; + + private int remaining; + private int cooldown; + private int airUsed; + private int direction; + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + if (cooldown > 0) { + cooldown--; + } + if (remaining == 0 && cooldown == 0 && c.pressed(Input.DASH) + && c.getState() != MovementState.CLIMBING + && (b.isGrounded() || airUsed < airDashes)) { + remaining = dashTicks; + cooldown = cooldownTicks; + int dir = Input.horizontal(c.getInput()); + direction = dir != 0 ? dir : c.getFacing(); + c.setFacing(direction); + if (!b.isGrounded()) { + airUsed++; + } + } + if (remaining > 0) { + remaining--; + b.vx = direction * dashSpeed; + b.vy = 0; + c.suspendGravity(); + c.claimState(MovementState.DASHING); + } + } + + @Override + public void lateProcess(Actor c, PlatformWorld world) { + Body b = c.getBody(); + if (b.isGrounded()) { + airUsed = 0; + } + if (remaining > 0 && (b.hitLeft() || b.hitRight())) { + remaining = 0; + } + if (remaining == 0 && c.getState() == MovementState.DASHING) { + b.vx = Fx.mul(b.vx, Fx.HALF); + } + } + + /// Whether a dash is under way. + /// + /// #### Returns + /// + /// true mid dash + public boolean isDashing() { + return remaining > 0; + } + + @Override + public long hashState(long h) { + return mix(mix(mix(mix(h, remaining), cooldown), airUsed), direction); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Door.java b/CodenameOne/src/com/codename1/gaming/platformer/Door.java new file mode 100644 index 00000000000..a8c42541d23 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Door.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A locked door: solid until the player touches it holding the key it names, +/// which is used up. +@com.codename1.impl.SharedWithBackend +public class Door extends BlockEntity { + private final String key; + + /// Creates a door. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `x`: left, fixed point, on a tile edge + /// - `y`: top, fixed point, on a tile edge + /// - `w`: width, whole tiles, fixed point + /// - `h`: height, whole tiles, fixed point + /// - `key`: the key name that opens it + public Door(String id, int x, int y, int w, int h, String key) { + super(id, "door", x, y, w, h); + this.key = key; + } + + /// The key that opens the door. + /// + /// #### Returns + /// + /// the key name + public String getKey() { + return key; + } + + @Override + public int getPhase() { + return isSolid() ? 0 : 1; + } + + @Override + public void onAdded(PlatformWorld world) { + setSolid(world, true); + } + + @Override + public void onTouch(PlatformWorld world, Actor c) { + if (isSolid() && c == world.getPlayer() && world.useKey(key)) { // NOPMD CompareObjectsWithEquals - identity is intended + setSolid(world, false); + world.emit(WorldEvent.OPEN, x + w / 2, y + h / 2, getId(), key); + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Entity.java b/CodenameOne/src/com/codename1/gaming/platformer/Entity.java new file mode 100644 index 00000000000..ef6ef3eedd5 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Entity.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Something in a level that is not an actor: a coin, a spring, a door, a +/// projectile, a crumbling block. +/// +/// An entity is a rectangle with a `getType()` name that the view maps to art. +/// Each tick the world calls `step`, and calls `onTouch` for every living +/// actor that overlaps it. An entity that must block movement (a door, a +/// gate, a crumbling block) writes `Tile#SOLID` cells into the grid rather than +/// colliding itself, so the controller stays one fast tile scan. +/// +/// Subclasses must be deterministic, like abilities, and fold any state that +/// changes play into `hashState`. +@com.codename1.impl.SharedWithBackend +public abstract class Entity { + private final String id; + private final String type; + /// Left edge, fixed point. + public int x; + /// Top edge, fixed point. + public int y; + /// Width, fixed point. + public int w; + /// Height, fixed point. + public int h; + private boolean active = true; + + /// Creates an entity. + /// + /// #### Parameters + /// + /// - `id`: a name, unique in its world + /// - `type`: the kind, which the view maps to art (`"coin"`, `"spring"`) + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + protected Entity(String id, String type, int x, int y, int w, int h) { + this.id = id; + this.type = type; + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + + /// The entity's id. + /// + /// #### Returns + /// + /// the id + public String getId() { + return id; + } + + /// The entity's kind. + /// + /// #### Returns + /// + /// the type name + public String getType() { + return type; + } + + /// Whether the entity still takes part. Inactive entities are skipped and not + /// drawn; the world drops them at the end of the tick. + /// + /// #### Returns + /// + /// true while active + public boolean isActive() { + return active; + } + + /// Removes the entity at the end of the tick. + public void deactivate() { + active = false; + } + + /// A small number the view reads to pick a frame: open or closed, lit or not, + /// how cracked. The default is 0. + /// + /// #### Returns + /// + /// the visual phase + public int getPhase() { + return 0; + } + + /// How far outside its rectangle the entity still counts as touched. An entity + /// that writes solid cells (a door) needs a margin, since an actor can never + /// overlap a solid cell. The default is 0. + /// + /// #### Returns + /// + /// the margin, fixed point + public int getTouchMargin() { + return 0; + } + + /// Called once when the entity is added to a world, before the first step: the + /// place to write solid cells. The default does nothing. + /// + /// #### Parameters + /// + /// - `world`: the world + public void onAdded(PlatformWorld world) { + } + + /// Advances one tick. The default does nothing. + /// + /// #### Parameters + /// + /// - `world`: the world + public void step(PlatformWorld world) { + } + + /// Called each tick a living actor overlaps the entity. + /// + /// #### Parameters + /// + /// - `world`: the world + /// - `c`: the actor + public void onTouch(PlatformWorld world, Actor c) { + } + + /// Mixes the entity's play-relevant state into a hash. The default mixes the + /// position and whether it is active. + /// + /// #### Parameters + /// + /// - `h`: the running hash + /// + /// #### Returns + /// + /// the updated hash + public long hashState(long h) { + return Ability.mix(Ability.mix(Ability.mix(h, x), y), active ? 1 : 0); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/EntityFactory.java b/CodenameOne/src/com/codename1/gaming/platformer/EntityFactory.java new file mode 100644 index 00000000000..0e289bc6c2a --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/EntityFactory.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +import java.util.Map; + +/// Creates a game's own entity types from level JSON, for types `LevelData` does +/// not know. Pass one to `LevelData#createWorld(long, EntityFactory)`. +@com.codename1.impl.SharedWithBackend +public interface EntityFactory { + /// Creates an entity, or declines. + /// + /// #### Parameters + /// + /// - `id`: the id to give it + /// - `type`: the `type` field + /// - `x`: the left edge of its cell, fixed point + /// - `y`: the top edge of its cell, fixed point + /// - `tileSize`: the tile size, fixed point + /// - `spec`: the whole JSON object, for its other fields + /// + /// #### Returns + /// + /// the entity, or null if the type is not this factory's + Entity create(String id, String type, int x, int y, int tileSize, Map spec); +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/FlyAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/FlyAbility.java new file mode 100644 index 00000000000..e8b46f2fed4 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/FlyAbility.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Free flight with no gravity, steered on both axes, for bats, ghosts and drones +/// (and a debug camera hero). +@com.codename1.impl.SharedWithBackend +public class FlyAbility extends Ability { + /// Flying speed, fixed point per tick. + public int speed = Fx.of(1); + /// Change of speed per tick. + public int acceleration = Fx.ratio(1, 8); + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + c.suspendGravity(); + int h = Input.horizontal(c.getInput()); + int v = Input.vertical(c.getInput()); + if (h != 0) { + c.setFacing(h); + } + b.vx = Fx.approach(b.vx, h * speed, acceleration); + b.vy = Fx.approach(b.vy, v * speed, acceleration); + c.claimState(MovementState.JUMPING); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Fx.java b/CodenameOne/src/com/codename1/gaming/platformer/Fx.java new file mode 100644 index 00000000000..938d877dfe0 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Fx.java @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// 16.16 fixed-point arithmetic for the platformer simulation. +/// +/// Every position, speed and size the simulation keeps is an `int` holding a value +/// scaled by `ONE` (65536). Integer arithmetic gives the same answer on every CPU, +/// every runtime and on the server, which is what lets a run recorded on a phone be +/// replayed bit for bit by the backend. Nothing in this package uses `float`, +/// `double` or a clock. +@com.codename1.impl.SharedWithBackend +public final class Fx { + /// The value 1.0. + public static final int ONE = 1 << 16; + + /// The value 0.5. + public static final int HALF = 1 << 15; + + private Fx() { + } + + /// Converts a whole number to fixed point. + /// + /// #### Parameters + /// + /// - `i`: the whole number + /// + /// #### Returns + /// + /// `i` scaled by `ONE` + public static int of(int i) { + return i << 16; + } + + /// Builds a fixed-point value from a fraction, `num / den`, without floating point. + /// + /// #### Parameters + /// + /// - `num`: the numerator + /// - `den`: the denominator, never zero + /// + /// #### Returns + /// + /// the fraction in fixed point + public static int ratio(int num, int den) { + if (den == 0) { + // Thrown explicitly: a raw zero divide answers 0 on arm64 and kills + // the process on x86-64 under ParparVM, never ArithmeticException. + throw new ArithmeticException("division by zero"); + } + return (int) (((long) num << 16) / den); + } + + /// Multiplies two fixed-point values. + /// + /// #### Parameters + /// + /// - `a`: the first factor + /// - `b`: the second factor + /// + /// #### Returns + /// + /// `a * b` in fixed point + public static int mul(int a, int b) { + return (int) (((long) a * b) >> 16); + } + + /// Divides two fixed-point values. + /// + /// #### Parameters + /// + /// - `a`: the dividend + /// - `b`: the divisor, never zero + /// + /// #### Returns + /// + /// `a / b` in fixed point + public static int div(int a, int b) { + if (b == 0) { + // Thrown explicitly: a raw zero divide answers 0 on arm64 and kills + // the process on x86-64 under ParparVM, never ArithmeticException. + throw new ArithmeticException("division by zero"); + } + return (int) (((long) a << 16) / b); + } + + /// The largest whole number not greater than a fixed-point value. + /// + /// #### Parameters + /// + /// - `a`: a fixed-point value + /// + /// #### Returns + /// + /// the floor of `a` as a whole number + public static int floor(int a) { + return a >> 16; + } + + /// Integer division that rounds toward negative infinity, as a tile index needs + /// for a coordinate left of or above the map. + /// + /// #### Parameters + /// + /// - `a`: the dividend + /// - `b`: the divisor, never zero + /// + /// #### Returns + /// + /// the floor of `a / b` + public static int floorDiv(int a, int b) { + if (b <= 0) { + throw new ArithmeticException("divisor must be positive"); + } + int q = a / b; + if (q * b != a && a < 0) { + q--; + } + return q; + } + + /// Clamps a value into a range. + /// + /// #### Parameters + /// + /// - `v`: the value + /// - `lo`: the lower bound + /// - `hi`: the upper bound + /// + /// #### Returns + /// + /// `v` limited to `[lo, hi]` + public static int clamp(int v, int lo, int hi) { + if (v < lo) { + return lo; + } + return v > hi ? hi : v; + } + + /// Moves a value toward a target by at most a step. + /// + /// #### Parameters + /// + /// - `v`: the current value + /// - `target`: the value to approach + /// - `step`: the largest change allowed, not negative + /// + /// #### Returns + /// + /// the new value + public static int approach(int v, int target, int step) { + if (v < target) { + return v + step > target ? target : v + step; + } + return v - step < target ? target : v - step; + } + + /// Parses a decimal such as `"2.75"` or `"-0.5"` into fixed point, exactly and + /// without floating point, so a level file reads the same everywhere. + /// + /// #### Parameters + /// + /// - `s`: the decimal text + /// + /// #### Returns + /// + /// the value in fixed point + /// + /// #### Throws + /// + /// - `IllegalArgumentException`: if `s` is not a decimal number + public static int parse(String s) { + int len = s.length(); + int i = 0; + boolean neg = false; + if (i < len && (s.charAt(i) == '-' || s.charAt(i) == '+')) { + neg = s.charAt(i) == '-'; + i++; + } + long whole = 0; + int digits = 0; + while (i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9') { + whole = whole * 10 + (s.charAt(i) - '0'); + if (whole > 32767) { + throw new IllegalArgumentException("Out of fixed-point range: " + s); + } + i++; + digits++; + } + long frac = 0; + long scale = 1; + if (i < len && s.charAt(i) == '.') { + i++; + while (i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9') { + if (scale < 1000000000L) { + frac = frac * 10 + (s.charAt(i) - '0'); + scale *= 10; + } + i++; + digits++; + } + } + if (digits == 0 || i != len) { + throw new IllegalArgumentException("Not a number: " + s); + } + long v = (whole << 16) + (frac << 16) / scale; + return (int) (neg ? -v : v); + } + + /// Formats a fixed-point value as a decimal with up to four places, the inverse + /// of `parse` to the precision a level file needs. + /// + /// #### Parameters + /// + /// - `v`: the fixed-point value + /// + /// #### Returns + /// + /// decimal text + public static String format(int v) { + StringBuilder sb = new StringBuilder(); + long a = v; + if (a < 0) { + sb.append('-'); + a = -a; + } + sb.append(a >> 16); + long frac = ((a & 0xffff) * 10000 + 0x8000) >> 16; + if (frac >= 10000) { + frac = 9999; + } + if (frac != 0) { + sb.append('.'); + String f = String.valueOf(10000 + frac).substring(1); + int end = f.length(); + while (end > 1 && f.charAt(end - 1) == '0') { + end--; + } + sb.append(f.substring(0, end)); + } + return sb.toString(); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Gate.java b/CodenameOne/src/com/codename1/gaming/platformer/Gate.java new file mode 100644 index 00000000000..4ae4efffb10 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Gate.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A gate wired to a channel: open while the channel is on (or off, when +/// `inverted`). `Switch`es turn channels on and off. +@com.codename1.impl.SharedWithBackend +public class Gate extends BlockEntity { + private final int channel; + private final boolean inverted; + + /// Creates a gate. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `x`: left, fixed point, on a tile edge + /// - `y`: top, fixed point, on a tile edge + /// - `w`: width, whole tiles, fixed point + /// - `h`: height, whole tiles, fixed point + /// - `channel`: the channel, 0 to 31 + /// - `inverted`: true to be open while the channel is off + public Gate(String id, int x, int y, int w, int h, int channel, boolean inverted) { + super(id, "gate", x, y, w, h); + this.channel = channel; + this.inverted = inverted; + } + + @Override + public int getPhase() { + return isSolid() ? 0 : 1; + } + + @Override + public void onAdded(PlatformWorld world) { + setSolid(world, world.isChannelOn(channel) == inverted); + } + + @Override + public void step(PlatformWorld world) { + boolean wantSolid = world.isChannelOn(channel) == inverted; + boolean was = isSolid(); + if (setSolid(world, wantSolid) && was != wantSolid) { + world.emit(WorldEvent.OPEN, x + w / 2, y + h / 2, getId(), null); + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/GlideAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/GlideAbility.java new file mode 100644 index 00000000000..d1a3d47f0ed --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/GlideAbility.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Gliding: holding `Input#ALT` (or jump, when `holdJump`) while falling caps the +/// fall at `glideFall`. +@com.codename1.impl.SharedWithBackend +public class GlideAbility extends Ability { + /// Fastest fall while gliding, fixed point per tick. + public int glideFall = Fx.ratio(3, 4); + /// Whether holding jump glides too, as in many platformers. + public boolean holdJump = true; + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + boolean held = c.held(Input.ALT) || (holdJump && c.held(Input.JUMP) && !c.pressed(Input.JUMP)); + if (!held || b.isGrounded() || b.vy < 0 || c.getState() == MovementState.CLIMBING + || c.getState() == MovementState.DASHING || c.isStateClaimed()) { + return; + } + c.suspendGravity(); + b.vy = Math.min(b.vy + c.getGravity() / 4, glideFall); + c.claimState(MovementState.GLIDING); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Health.java b/CodenameOne/src/com/codename1/gaming/platformer/Health.java new file mode 100644 index 00000000000..f7d594be1d8 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Health.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Hit points, invulnerability frames and knock-back for a `Actor`. +/// +/// `PlatformWorld#damage` is the one way to hurt something: it checks the +/// invulnerability window, knocks the actor away from the source, locks its +/// control briefly and, at zero, hands it to `PlatformWorld#onDeath`. +@com.codename1.impl.SharedWithBackend +public final class Health { + /// Hit points when full. + public int max; + /// Ticks of invulnerability after a hit. + public int invulnerableTicks = 60; + /// Horizontal knock-back speed, fixed point per tick. + public int knockbackX = Fx.of(2); + /// Upward knock-back speed, fixed point per tick. + public int knockbackY = Fx.of(3); + /// Ticks control is locked after a hit. + public int stunTicks = 14; + + private int current; + private int invulnerable; + + /// Creates a full health pool. + /// + /// #### Parameters + /// + /// - `max`: hit points + public Health(int max) { + this.max = max; + this.current = max; + } + + /// Current hit points. + /// + /// #### Returns + /// + /// the hit points + public int getCurrent() { + return current; + } + + /// Whether hits are currently ignored. + /// + /// #### Returns + /// + /// true during invulnerability + public boolean isInvulnerable() { + return invulnerable > 0; + } + + /// Ticks of invulnerability left, which a view flickers the sprite by. + /// + /// #### Returns + /// + /// the remaining ticks + public int getInvulnerableRemaining() { + return invulnerable; + } + + /// Removes hit points and starts invulnerability. + /// + /// #### Parameters + /// + /// - `amount`: hit points to remove + /// + /// #### Returns + /// + /// true if the hit landed + boolean hit(int amount) { + if (invulnerable > 0 || current <= 0) { + return false; + } + current = Math.max(0, current - amount); + invulnerable = invulnerableTicks; + return true; + } + + /// Restores hit points, up to the maximum. + /// + /// #### Parameters + /// + /// - `amount`: hit points to add + public void heal(int amount) { + current = Math.min(max, current + amount); + } + + /// Refills and clears invulnerability, on respawn. + public void reset() { + current = max; + invulnerable = 0; + } + + /// Makes the owner invulnerable for a while, as a power-up or respawn does. + /// + /// #### Parameters + /// + /// - `ticks`: how long + public void grantInvulnerability(int ticks) { + invulnerable = Math.max(invulnerable, ticks); + } + + void tick() { + if (invulnerable > 0) { + invulnerable--; + } + } + + long hash(long h) { + return Ability.mix(Ability.mix(h, current), invulnerable); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Input.java b/CodenameOne/src/com/codename1/gaming/platformer/Input.java new file mode 100644 index 00000000000..6b5cf1e6692 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Input.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// The buttons an actor reads, as bits of one `int` per tick. +/// +/// A tick's input is a single `int`, which is what makes a run cheap to record +/// (`InputLog`) and exact to replay. Touch controls, a keyboard and a gamepad all +/// produce the same bits, so the simulation never knows which one a player used. +@com.codename1.impl.SharedWithBackend +public final class Input { + /// Move left. + public static final int LEFT = 1; + /// Move right. + public static final int RIGHT = 1 << 1; + /// Up: climb, look up, enter a door. + public static final int UP = 1 << 2; + /// Down: crouch, climb down, drop through a one-way platform with `JUMP`. + public static final int DOWN = 1 << 3; + /// Jump. + public static final int JUMP = 1 << 4; + /// Run while held. + public static final int RUN = 1 << 5; + /// Dash. + public static final int DASH = 1 << 6; + /// Use the weapon. + public static final int FIRE = 1 << 7; + /// Activate what the actor stands at: a lever, a door, a sign. + public static final int ACTIVATE = 1 << 8; + /// Use the jetpack or glide while held (an ability decides which). + public static final int ALT = 1 << 9; + + /// Every defined bit. + public static final int ALL = (1 << 10) - 1; + + private Input() { + } + + /// Whether a button is held this tick. + /// + /// #### Parameters + /// + /// - `bits`: this tick's input + /// - `button`: one of the button constants + /// + /// #### Returns + /// + /// true while held + public static boolean held(int bits, int button) { + return (bits & button) != 0; + } + + /// Whether a button went down this tick. + /// + /// #### Parameters + /// + /// - `bits`: this tick's input + /// - `previous`: the previous tick's input + /// - `button`: one of the button constants + /// + /// #### Returns + /// + /// true on the press edge + public static boolean pressed(int bits, int previous, int button) { + return (bits & button) != 0 && (previous & button) == 0; + } + + /// The horizontal direction held. + /// + /// #### Parameters + /// + /// - `bits`: this tick's input + /// + /// #### Returns + /// + /// -1 for left, 1 for right, 0 for neither or both + public static int horizontal(int bits) { + int d = 0; + if ((bits & LEFT) != 0) { + d--; + } + if ((bits & RIGHT) != 0) { + d++; + } + return d; + } + + /// The vertical direction held. + /// + /// #### Parameters + /// + /// - `bits`: this tick's input + /// + /// #### Returns + /// + /// -1 for up, 1 for down, 0 for neither or both + public static int vertical(int bits) { + int d = 0; + if ((bits & UP) != 0) { + d--; + } + if ((bits & DOWN) != 0) { + d++; + } + return d; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/InputLog.java b/CodenameOne/src/com/codename1/gaming/platformer/InputLog.java new file mode 100644 index 00000000000..149739e35a6 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/InputLog.java @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A recorded run: one `Input` value per tick, run-length encoded. +/// +/// A player rarely changes buttons, so a minute of play (3600 ticks) is typically a +/// few hundred bytes of text. The text form, `bits*count` pairs in hexadecimal +/// separated by commas (`"2*3c,12*8,2*40"`), is what the app uploads and the server +/// replays with `Replay`. +@com.codename1.impl.SharedWithBackend +public final class InputLog { + private int[] values = new int[16]; + private int[] counts = new int[16]; + private int runs; + private int length; + + /// Appends one tick. + /// + /// #### Parameters + /// + /// - `bits`: the tick's `Input` bits + public void add(int bits) { + int b = bits & Input.ALL; + if (runs > 0 && values[runs - 1] == b) { + counts[runs - 1]++; + } else { + if (runs == values.length) { + int[] nv = new int[runs * 2]; + int[] nc = new int[runs * 2]; + System.arraycopy(values, 0, nv, 0, runs); + System.arraycopy(counts, 0, nc, 0, runs); + values = nv; + counts = nc; + } + values[runs] = b; + counts[runs] = 1; + runs++; + } + length++; + } + + /// The number of ticks recorded. + /// + /// #### Returns + /// + /// the tick count + public int length() { + return length; + } + + /// The input at a tick. + /// + /// #### Parameters + /// + /// - `tick`: a tick in `[0, length())` + /// + /// #### Returns + /// + /// the `Input` bits + public int get(int tick) { + int t = tick; + for (int i = 0; i < runs; i++) { + if (t < counts[i]) { + return values[i]; + } + t -= counts[i]; + } + throw new IndexOutOfBoundsException("tick " + tick + " of " + length); + } + + /// Expands the log into one value per tick. + /// + /// #### Returns + /// + /// a new array of `length()` values + public int[] toArray() { + int[] out = new int[length]; + int p = 0; + for (int i = 0; i < runs; i++) { + for (int k = 0; k < counts[i]; k++) { + out[p++] = values[i]; + } + } + return out; + } + + /// The compact text form. + /// + /// #### Returns + /// + /// the encoded log + public String encode() { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < runs; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(Integer.toHexString(values[i])).append('*').append(Integer.toHexString(counts[i])); + } + return sb.toString(); + } + + /// Reads the text form. + /// + /// #### Parameters + /// + /// - `text`: an encoded log + /// - `maxTicks`: the longest log accepted, so a hostile upload cannot claim + /// billions of ticks + /// + /// #### Returns + /// + /// the log + /// + /// #### Throws + /// + /// - `IllegalArgumentException`: on malformed text or a log over `maxTicks` + public static InputLog decode(String text, int maxTicks) { + InputLog log = new InputLog(); + if (text.length() == 0) { + return log; + } + int start = 0; + while (start <= text.length()) { + int end = text.indexOf(',', start); + if (end < 0) { + end = text.length(); + } + int star = text.indexOf('*', start); + if (star < 0 || star > end) { + throw new IllegalArgumentException("Bad run at " + start); + } + int bits = parseHex(text, start, star); + int count = parseHex(text, star + 1, end); + if (count <= 0 || (bits & ~Input.ALL) != 0 || (long) log.length + count > maxTicks) { + throw new IllegalArgumentException("Bad run at " + start); + } + for (int k = 0; k < count; k++) { + log.add(bits); + } + start = end + 1; + } + return log; + } + + private static int parseHex(String s, int from, int to) { + if (to <= from || to - from > 7) { + throw new IllegalArgumentException("Bad number at " + from); + } + int v = 0; + for (int i = from; i < to; i++) { + char c = s.charAt(i); + int d; + if (c >= '0' && c <= '9') { + d = c - '0'; + } else if (c >= 'a' && c <= 'f') { + d = c - 'a' + 10; + } else { + throw new IllegalArgumentException("Bad digit at " + i); + } + v = v * 16 + d; + } + return v; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/JetpackAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/JetpackAbility.java new file mode 100644 index 00000000000..17f53d1ef06 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/JetpackAbility.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A jetpack: holding `Input#ALT` in the air thrusts upward while fuel lasts; fuel +/// refills on the ground. +@com.codename1.impl.SharedWithBackend +public class JetpackAbility extends Ability { + /// Upward acceleration while thrusting, fixed point per tick squared. + public int thrust = Fx.ratio(9, 20); + /// Fastest rise, fixed point per tick. + public int maxRise = Fx.of(3); + /// Ticks of thrust on a full tank. + public int fuelTicks = 90; + /// Fuel regained per tick on the ground. + public int refill = 3; + + private int fuel = -1; + + @Override + public void process(Actor c, PlatformWorld world) { + if (fuel < 0) { + fuel = fuelTicks; + } + Body b = c.getBody(); + if (b.isGrounded()) { + fuel = Math.min(fuelTicks, fuel + refill); + } + MovementState s = c.getState(); + if (!c.held(Input.ALT) || fuel == 0 || b.isGrounded() || s == MovementState.CLIMBING + || s == MovementState.DASHING) { + return; + } + fuel--; + b.vy = Math.max(-maxRise, b.vy - thrust); + c.suspendGravity(); + c.claimState(MovementState.JETPACKING); + } + + /// Fuel left, for the HUD. + /// + /// #### Returns + /// + /// ticks of thrust remaining + public int getFuel() { + return fuel < 0 ? fuelTicks : fuel; + } + + @Override + public long hashState(long h) { + return mix(h, fuel); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/JumpAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/JumpAbility.java new file mode 100644 index 00000000000..6ee2fddadb3 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/JumpAbility.java @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Jumping, with the forgiveness that makes a platformer feel right: +/// +/// - **Coyote time**: a jump still works for `coyoteTicks` after walking off a ledge. +/// - **Jump buffering**: a press up to `bufferTicks` before landing jumps on landing. +/// - **Variable height**: releasing the button while rising cuts the jump. +/// - **Multi-jump**: `maxJumps` above 1 allows double (or more) jumps in the air. +/// - **Drop through**: down + jump on a one-way platform falls through it instead. +@com.codename1.impl.SharedWithBackend +public class JumpAbility extends Ability { + /// Upward speed at take-off, fixed point per tick. + public int jumpSpeed = Fx.ratio(23, 5); + /// Upward speed of an air jump. + public int airJumpSpeed = Fx.of(4); + /// Jumps allowed before landing again; 2 is a double jump. + public int maxJumps = 1; + /// Ticks after leaving the ground that a jump is still a ground jump. + public int coyoteTicks = 6; + /// Ticks a press is remembered before landing. + public int bufferTicks = 6; + /// Fraction of upward speed kept when the button is released early. + public int releaseCut = Fx.HALF; + + private int jumpsUsed; + private int buffer; + private boolean rising; + + @Override + public void earlyProcess(Actor c, PlatformWorld world) { + if (c.pressed(Input.JUMP)) { + buffer = bufferTicks + 1; + } else if (buffer > 0) { + buffer--; + } + } + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + if (c.getState() == MovementState.DEAD) { + return; + } + if (rising && b.vy < 0 && c.released(Input.JUMP)) { + b.vy = Fx.mul(b.vy, releaseCut); + rising = false; + } + if (buffer == 0 || c.isJumpConsumed()) { + return; + } + boolean grounded = b.isGrounded() || c.getState() == MovementState.CLIMBING; + boolean coyote = !grounded && c.getAirTicks() <= coyoteTicks && jumpsUsed == 0; + if (b.isGrounded() && c.held(Input.DOWN) && b.isOnOneWay()) { + b.dropThrough(10); + buffer = 0; + c.consumeJump(); + return; + } + if (grounded || coyote) { + b.vy = -jumpSpeed; + jumpsUsed = 1; + } else if (jumpsUsed < maxJumps) { + b.vy = -airJumpSpeed; + jumpsUsed = Math.max(jumpsUsed, 1) + 1; + } else { + return; + } + buffer = 0; + rising = true; + c.consumeJump(); + c.claimState(MovementState.JUMPING); + } + + @Override + public void lateProcess(Actor c, PlatformWorld world) { + Body b = c.getBody(); + if (b.isGrounded() && b.vy >= 0) { + jumpsUsed = 0; + rising = false; + } + if (b.hitCeiling()) { + rising = false; + } + } + + /// Lets the actor jump again in the air, as a wall jump or a bounce does. + /// + /// #### Parameters + /// + /// - `used`: jumps to count as used afterwards + public void resetJumps(int used) { + jumpsUsed = used; + rising = true; + } + + @Override + public long hashState(long h) { + return mix(mix(mix(h, jumpsUsed), buffer), rising ? 1 : 0); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/LadderAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/LadderAbility.java new file mode 100644 index 00000000000..5e7a2671b8d --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/LadderAbility.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Climbing `Tile#LADDER` cells. Up or down while overlapping a ladder grabs it: +/// gravity stops, the actor centres on the ladder and moves at `climbSpeed`. +/// Jumping lets go (`JumpAbility` treats a ladder as ground), as does climbing off +/// either end. Standing on top of a ladder and holding down climbs down through it. +/// +/// Add it before `JumpAbility` so a jump from the ladder sees the climbing state. +@com.codename1.impl.SharedWithBackend +public class LadderAbility extends Ability { + /// Climbing speed, fixed point per tick. + public int climbSpeed = Fx.ratio(6, 5); + + private boolean climbing; + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + TileGrid g = world.getGrid(); + int cx = b.x + b.w / 2; + int col = g.col(cx); + int v = Input.vertical(c.getInput()); + boolean onLadder = ladderAt(g, col, b.y, b.h); + boolean ladderBelow = b.isGrounded() && g.get(col, g.row(b.y + b.h)) == Tile.LADDER; + if (!climbing && c.getState() != MovementState.DASHING && v != 0 + && ((v < 0 && onLadder) || (v > 0 && (onLadder || ladderBelow)))) { + if (!(v > 0 && b.isGrounded() && !ladderBelow)) { + climbing = true; + } + } + if (climbing && (c.pressed(Input.JUMP) || !(onLadder || ladderBelow))) { + climbing = false; + b.setIgnoreOneWay(false); + } + if (!climbing) { + return; + } + int ts = g.getTileSize(); + b.x = col * ts + (ts - b.w) / 2; + b.vx = 0; + b.vy = v * climbSpeed; + b.setIgnoreOneWay(v > 0 || !b.isGrounded()); + c.suspendGravity(); + c.claimState(MovementState.CLIMBING); + } + + @Override + public void lateProcess(Actor c, PlatformWorld world) { + Body b = c.getBody(); + TileGrid g = world.getGrid(); + if (climbing && b.isGrounded() && Input.vertical(c.getInput()) >= 0 + && g.get(g.col(b.x + b.w / 2), g.row(b.y + b.h)) != Tile.LADDER) { + climbing = false; + b.setIgnoreOneWay(false); + } + } + + private static boolean ladderAt(TileGrid g, int col, int y, int h) { + int r1 = g.row(y + h - 1); + for (int r = g.row(y); r <= r1; r++) { + if (g.get(col, r) == Tile.LADDER) { + return true; + } + } + return false; + } + + /// Whether the actor is on a ladder. + /// + /// #### Returns + /// + /// true while climbing + public boolean isClimbing() { + return climbing; + } + + @Override + public long hashState(long h) { + return mix(h, climbing ? 1 : 0); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/LevelData.java b/CodenameOne/src/com/codename1/gaming/platformer/LevelData.java new file mode 100644 index 00000000000..1c128d20e70 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/LevelData.java @@ -0,0 +1,563 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +import java.util.List; +import java.util.Map; + +/// A platformer level as data, read from JSON and turned into a `PlatformWorld`. +/// +/// The format is meant to be written by hand, by the level editor and by a +/// language model alike. Positions and sizes are in tiles, speeds in pixels per +/// tick, and every number may be a decimal (read exactly, see `LevelJson`): +/// +/// ```json +/// { +/// "name": "First steps", +/// "tileSize": 16, +/// "tiles": [ +/// "#..............#", +/// "#.........====.#", +/// "#.....H........#", +/// "#.....H..../####", +/// "################" +/// ], +/// "spawn": [1, 3], +/// "goal": [14, 2, 1, 1], +/// "platforms": [{"path": [[3, 2], [8, 2]], "w": 2, "speed": 0.75, "pause": 30}], +/// "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], +/// "tuning": {"maxJumps": 2, "jumpSpeed": 4.6} +/// } +/// ``` +/// +/// `tiles` uses the actors listed on `Tile`. `abilities` lists the hero's +/// abilities in processing order (names on `Abilities`); omitted, the hero gets +/// move, ladder, walljump, jump, crouch and dash. `tuning` keys are listed on +/// `applyTuning`. `health` gives the hero hit points (otherwise one hit kills) and +/// `lives` limits retries (otherwise unlimited). +/// +/// `entities` places everything else, each with `"type"` and `"at": [col, row]`: +/// `coin`, `gem`, `heart`, `life`, `key` and `powerup` (`name`: the key or the +/// ability), `spring` (`power`), `checkpoint`, `door` (`key`, `h`), `gate` +/// (`channel`, `w`, `h`, `inverted`), `lever` and `plate` (`channel`), `crumble` +/// (`w`, `delay`, `respawn`) and `enemy` (`kind`, `brain`, `hp`, `damage`, +/// `speed`, `range`, `stompable`, and `opens`: a channel its defeat turns on). +/// Other types go to an `EntityFactory`. +@com.codename1.impl.SharedWithBackend +public final class LevelData { + private final Map json; + private final String name; + private final int tileSize; + private final String[] tiles; + + /// Limits on a level, so that a published level's replay on the server has a + /// bounded cost and every size reaching the simulation is sane. + static final int MAX_TILE_SIZE = 256; + static final int MAX_ROWS = 512; + static final int MAX_COLUMNS = 4096; + static final int MAX_CELLS = 1 << 20; + static final int MAX_PIXELS = 30000; + static final int MAX_ENTITIES = 2048; + static final int MAX_PLATFORMS = 256; + static final int MAX_PATH_POINTS = 64; + static final int MAX_TICKS_FIELD = 60 * 600; + + private LevelData(Map json) { + this.json = json; + this.name = LevelJson.str(json, "name", "Untitled"); + this.tileSize = LevelJson.integer(json, "tileSize", 16); + List rows = LevelJson.list(json, "tiles"); + if (rows.isEmpty()) { + throw new IllegalArgumentException("A level needs \"tiles\""); + } + tiles = new String[rows.size()]; + for (int i = 0; i < tiles.length; i++) { + Object r = rows.get(i); + if (!(r instanceof String)) { + throw new IllegalArgumentException("tiles[" + i + "] is not a string"); + } + tiles[i] = (String) r; + } + validate(); + } + + private void validate() { + if (tileSize < 4 || tileSize > MAX_TILE_SIZE) { + throw new IllegalArgumentException("tileSize must be 4 to " + MAX_TILE_SIZE); + } + if (tiles.length > MAX_ROWS) { + throw new IllegalArgumentException("At most " + MAX_ROWS + " rows"); + } + int cols = 1; + for (int i = 0; i < tiles.length; i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + cols = Math.max(cols, tiles[i].length()); + } + // 16.16 fixed point reaches 32767 px; keep the level, plus the fall-out + // margin below it, well inside that. + if (cols > MAX_COLUMNS || (long) cols * tiles.length > MAX_CELLS + || (long) cols * tileSize > MAX_PIXELS || (long) (tiles.length + 4) * tileSize > MAX_PIXELS) { + throw new IllegalArgumentException("The level is too large"); + } + List ents = LevelJson.list(json, "entities"); + if (ents.size() > MAX_ENTITIES) { + throw new IllegalArgumentException("At most " + MAX_ENTITIES + " entities"); + } + for (int i = 0; i < ents.size(); i++) { + Object o = ents.get(i); + if (o instanceof Map) { + @SuppressWarnings("unchecked") + Map m = (Map) o; + checkCell(LevelJson.list(m, "at"), cols, "entities[" + i + "]"); + checkTicks(m, "delay"); + checkTicks(m, "respawn"); + checkTicks(m, "interval"); + checkTicks(m, "pause"); + } + } + List plats = LevelJson.list(json, "platforms"); + if (plats.size() > MAX_PLATFORMS) { + throw new IllegalArgumentException("At most " + MAX_PLATFORMS + " platforms"); + } + for (int i = 0; i < plats.size(); i++) { + Object o = plats.get(i); + if (o instanceof Map) { + @SuppressWarnings("unchecked") + Map m = (Map) o; + List path = LevelJson.list(m, "path"); + if (path.size() > MAX_PATH_POINTS) { + throw new IllegalArgumentException("platforms[" + i + "] has too many points"); + } + for (int k = 0; k < path.size(); k++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Object pt = path.get(k); + if (pt instanceof List) { + @SuppressWarnings("unchecked") + List cell = (List) pt; + checkCell(cell, cols, "platforms[" + i + "]"); + } + } + int speed = LevelJson.fx(m, "speed", Fx.ONE); + if (speed <= 0 || speed > Fx.of(tileSize)) { + throw new IllegalArgumentException("platforms[" + i + "] speed must be above 0 and at most " + + "a tile per tick"); + } + checkTicks(m, "pause"); + } + } + } + + private void checkCell(List at, int cols, String where) { + if (at.size() < 2) { + return; + } + int c = num(at.get(0)); + int r = num(at.get(1)); + if (c < 0 || r < 0 || c > Fx.of(cols) || r > Fx.of(tiles.length)) { + throw new IllegalArgumentException(where + " is outside the level"); + } + } + + private static void checkTicks(Map m, String key) { + int v = LevelJson.integer(m, key, 0); + if (v < 0 || v > MAX_TICKS_FIELD) { + throw new IllegalArgumentException("\"" + key + "\" must be 0 to " + MAX_TICKS_FIELD); + } + } + + /// Reads a level. + /// + /// #### Parameters + /// + /// - `text`: the level JSON + /// + /// #### Returns + /// + /// the level + /// + /// #### Throws + /// + /// - `IllegalArgumentException`: when the JSON or the level is malformed + @SuppressWarnings("unchecked") + public static LevelData parse(String text) { + Object v = LevelJson.parse(text); + if (!(v instanceof Map)) { + throw new IllegalArgumentException("A level is a JSON object"); + } + return new LevelData((Map) v); + } + + /// The level's name. + /// + /// #### Returns + /// + /// the name + public String getName() { + return name; + } + + /// The tile size in pixels. + /// + /// #### Returns + /// + /// the tile size + public int getTileSize() { + return tileSize; + } + + /// The parsed JSON, for game-specific fields (enemies, pickups, art). + /// + /// #### Returns + /// + /// the root object + public Map getJson() { + return json; + } + + /// The tile rows. + /// + /// #### Returns + /// + /// a copy of the rows, top first + public String[] getTiles() { + String[] copy = new String[tiles.length]; + System.arraycopy(tiles, 0, copy, 0, tiles.length); + return copy; + } + + /// Builds a fresh world with the hero at the spawn point. + /// + /// #### Parameters + /// + /// - `seed`: the random seed + /// + /// #### Returns + /// + /// a world ready to step + public PlatformWorld createWorld(long seed) { + return createWorld(seed, null); + } + + /// Builds a fresh world, creating unknown entity types through a factory. + /// + /// #### Parameters + /// + /// - `seed`: the random seed + /// - `factory`: the game's own entity types, may be null + /// + /// #### Returns + /// + /// a world ready to step + public PlatformWorld createWorld(long seed, EntityFactory factory) { + TileGrid grid = TileGrid.parse(tiles, tileSize); + PlatformWorld world = new PlatformWorld(grid, seed); + int ts = grid.getTileSize(); + int heroW = Fx.mul(ts, Fx.ratio(3, 4)); + int heroH = ts + ts / 2 - Fx.of(2); + List spawn = LevelJson.list(json, "spawn"); + int sc = spawn.size() >= 2 ? Fx.floor(num(spawn.get(0))) : 1; + int sr = spawn.size() >= 2 ? Fx.floor(num(spawn.get(1))) : 1; + int sx = sc * ts + (ts - heroW) / 2; + int sy = (sr + 1) * ts - heroH; + world.setSpawn(sx, sy); + List goal = LevelJson.list(json, "goal"); + if (goal.size() >= 2) { + int gw = goal.size() >= 4 ? Fx.mul(num(goal.get(2)), ts) : ts; + int gh = goal.size() >= 4 ? Fx.mul(num(goal.get(3)), ts) : ts; + world.setGoal(Fx.mul(num(goal.get(0)), ts), Fx.mul(num(goal.get(1)), ts), gw, gh); + } + List plats = LevelJson.list(json, "platforms"); + for (int i = 0; i < plats.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + world.addPlatform(platform(plats.get(i), ts)); + } + Actor hero = new Actor("hero", sx, sy, heroW, heroH); + hero.getBody().setStepHeight(Math.max(Fx.of(1), ts / 2 - Fx.of(1))); + List names = LevelJson.list(json, "abilities"); + if (names.isEmpty()) { + String[] all = {"move", "ladder", "walljump", "jump", "crouch", "dash"}; + for (int i = 0; i < all.length; i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + addAbility(hero, all[i], ts); + } + } else { + for (int i = 0; i < names.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Object n = names.get(i); + if (n instanceof String) { + addAbility(hero, (String) n, ts); + } + } + } + applyTuning(hero, LevelJson.obj(json, "tuning")); + int hp = LevelJson.integer(json, "health", 0); + if (hp > 0) { + hero.setHealth(new Health(hp)); + } + world.setLives(LevelJson.integer(json, "lives", -1)); + world.addActor(hero); + List ents = LevelJson.list(json, "entities"); + for (int i = 0; i < ents.size(); i++) { + addEntity(world, ents.get(i), i, ts, factory); + } + // Entities are queued until the first tick; a world handed out + // unstepped -- to a level preview, an editor icon -- would + // otherwise report none. Flushing here is what that tick would do. + world.flushPending(); + return world; + } + + @SuppressWarnings("unchecked") + private static void addEntity(PlatformWorld world, Object o, int index, int ts, EntityFactory factory) { + if (!(o instanceof Map)) { + throw new IllegalArgumentException("entities[" + index + "] is not an object"); + } + Map m = (Map) o; + String type = LevelJson.str(m, "type", ""); + String id = LevelJson.str(m, "id", type + index); + List at = LevelJson.list(m, "at"); + if (at.size() < 2) { + throw new IllegalArgumentException("entities[" + index + "] needs \"at\": [col, row]"); + } + int x = Fx.mul(num(at.get(0)), ts); + int y = Fx.mul(num(at.get(1)), ts); + int w = Fx.mul(LevelJson.fx(m, "w", Fx.ONE), ts); + int h = Fx.mul(LevelJson.fx(m, "h", Fx.ONE), ts); + if ("enemy".equals(type)) { + world.addActor(enemy(id, m, x, y, ts)); + return; + } + Entity e = null; + if (factory != null) { + e = factory.create(id, type, x, y, ts, m); + } + if (e == null) { + e = stockEntity(id, type, m, x, y, w, h, ts); + } + if (e == null) { + throw new IllegalArgumentException("Unknown entity type \"" + type + "\""); + } + world.addEntity(e); + } + + private static Entity stockEntity(String id, String type, Map m, int x, int y, + int w, int h, int ts) { + if ("coin".equals(type) || "gem".equals(type) || "heart".equals(type) || "life".equals(type) + || "key".equals(type) || "powerup".equals(type)) { + int size = ts * 3 / 4; + int def = "gem".equals(type) ? 100 : "coin".equals(type) ? 10 : 1; + return new Pickup(id, type, x + (ts - size) / 2, y + (ts - size) / 2, size, + LevelJson.integer(m, "value", def), LevelJson.str(m, "name", null)); + } + if ("spring".equals(type)) { + int sh = ts / 2; + return new Spring(id, x, y + ts - sh, w, sh, LevelJson.fx(m, "power", Fx.of(7))); + } + if ("checkpoint".equals(type)) { + return new Checkpoint(id, x, y - ts, w, ts * 2); + } + if ("door".equals(type)) { + return new Door(id, x, y, w, Fx.mul(LevelJson.fx(m, "h", Fx.of(2)), ts), + LevelJson.str(m, "key", "")); + } + if ("gate".equals(type)) { + return new Gate(id, x, y, w, h, LevelJson.integer(m, "channel", 0), + Boolean.TRUE.equals(m.get("inverted"))); + } + if ("lever".equals(type) || "plate".equals(type)) { + boolean plate = "plate".equals(type); + int sh = plate ? ts / 4 : ts; + return new Switch(id, x, y + ts - sh, w, sh, LevelJson.integer(m, "channel", 0), plate); + } + if ("crumble".equals(type)) { + return new CrumbleBlock(id, x, y, w, h, LevelJson.integer(m, "delay", 30), + LevelJson.integer(m, "respawn", 180)); + } + return null; + } + + /// Builds a stock enemy. `kind` names the art; `brain` is one of `patrol` + /// (walks, turns at walls and ledges), `walker` (walks off ledges), `chase`, + /// `turret` (stands and shoots), `hopper`, `flyer` (chases through the air) + /// or `boss` (patrols, then chases and shoots below half health). `hp`, + /// `damage`, `speed` and `stompable` tune it. + private static Actor enemy(String id, Map m, int x, int y, int ts) { + String brainName = LevelJson.str(m, "brain", "patrol"); + String kind = LevelJson.str(m, "kind", brainName); + boolean flyer = "flyer".equals(brainName); + int ew = Fx.mul(LevelJson.fx(m, "w", Fx.ratio(3, 4)), ts); + int eh = Fx.mul(LevelJson.fx(m, "h", Fx.ratio(3, 4)), ts); + Actor c = new Actor(id, x + (ts - ew) / 2, y + ts - eh, ew, eh); + c.setKind(kind).setTeam(1); + c.getBody().setStepHeight(ts / 4); + int speed = LevelJson.fx(m, "speed", Fx.ratio(3, 5)); + if (flyer) { + FlyAbility f = new FlyAbility(); + f.speed = speed; + c.addAbility(f); + } else { + MoveAbility mv = new MoveAbility(); + mv.walkSpeed = speed; + mv.canRun = false; + c.addAbility(mv); + JumpAbility j = new JumpAbility(); + j.jumpSpeed = Fx.of(4); + c.addAbility(j); + } + boolean shoots = "turret".equals(brainName) || "boss".equals(brainName); + if (shoots) { + WeaponAbility w = new WeaponAbility(); + w.projectileType = LevelJson.str(m, "projectile", "orb"); + w.speed = Fx.of(2); + w.cooldownTicks = 30; + w.lifeTicks = 120; + w.eightWay = false; + c.addAbility(w); + } + int hp = LevelJson.integer(m, "hp", "boss".equals(brainName) ? 8 : 1); + if (hp > 1) { + Health health = new Health(hp); + health.invulnerableTicks = 30; + c.setHealth(health); + } + c.setContactDamage(LevelJson.integer(m, "damage", 1)); + c.setDefeatChannel(LevelJson.integer(m, "opens", 0) & 31); + Object st = m.get("stompable"); + c.setStompable(st instanceof Boolean ? ((Boolean) st).booleanValue() : !"turret".equals(brainName)); + AIBrain brain = new AIBrain(); + int range = Fx.mul(LevelJson.fx(m, "range", Fx.of(6)), ts); + if ("chase".equals(brainName) || flyer) { + AIBrain.State idle = brain.addState("idle", flyer ? new AIBrain.Idle() : new AIBrain.Patrol()); + AIBrain.State chase = brain.addState("chase", new AIBrain.Chase(!flyer)); + idle.addTransition(new AIBrain.TargetWithin(range, false), chase); + chase.addTransition(new AIBrain.Not(new AIBrain.TargetWithin(range * 3 / 2, false)), idle); + } else if ("turret".equals(brainName)) { + AIBrain.State wait = brain.addState("wait", new AIBrain.Idle()); + AIBrain.State fire = brain.addState("fire", new AIBrain.Shoot(LevelJson.integer(m, "interval", 60))); + wait.addTransition(new AIBrain.TargetWithin(range, false), fire); + fire.addTransition(new AIBrain.Not(new AIBrain.TargetWithin(range, false)), wait); + } else if ("hopper".equals(brainName)) { + brain.addState("hop", new AIBrain.Hop(LevelJson.integer(m, "interval", 70))); + } else if ("walker".equals(brainName)) { + brain.addState("walk", new AIBrain.Patrol(false)); + } else if ("boss".equals(brainName)) { + AIBrain.State patrol = brain.addState("patrol", new AIBrain.Both(new AIBrain.Patrol(false), + new AIBrain.Shoot(90))); + AIBrain.State rage = brain.addState("rage", new AIBrain.Both(new AIBrain.Chase(true), + new AIBrain.Shoot(45))); + patrol.addTransition(new AIBrain.HealthAtMost(hp / 2), rage); + } else { + brain.addState("patrol", new AIBrain.Patrol(true)); + } + c.setBrain(brain); + return c; + } + + private static int num(Object o) { + if (o instanceof Integer) { + return ((Integer) o).intValue(); + } + throw new IllegalArgumentException("Expected a number, got " + o); + } + + @SuppressWarnings("unchecked") + private static MovingPlatform platform(Object o, int ts) { + if (!(o instanceof Map)) { + throw new IllegalArgumentException("A platform is an object"); + } + Map m = (Map) o; + List path = LevelJson.list(m, "path"); + if (path.isEmpty()) { + throw new IllegalArgumentException("A platform needs a \"path\""); + } + int[] pts = new int[path.size() * 2]; + for (int i = 0; i < path.size(); i++) { + Object p = path.get(i); + if (!(p instanceof List) || ((List) p).size() < 2) { + throw new IllegalArgumentException("A path point is [col, row]"); + } + List pt = (List) p; + pts[i * 2] = Fx.mul(num(pt.get(0)), ts); + pts[i * 2 + 1] = Fx.mul(num(pt.get(1)), ts); + } + int w = Fx.mul(LevelJson.fx(m, "w", Fx.of(2)), ts); + int h = Fx.mul(LevelJson.fx(m, "h", Fx.ratio(1, 2)), ts); + int speed = LevelJson.fx(m, "speed", Fx.of(1)); + int pause = LevelJson.integer(m, "pause", 0); + return new MovingPlatform(pts, w, h, speed, pause); + } + + private static void addAbility(Actor c, String name, int ts) { + Ability a = Abilities.create(name, ts); + if (a == null) { + throw new IllegalArgumentException("Unknown ability \"" + name + "\""); + } + c.addAbility(a); + } + + /// Applies tuning to an actor's abilities. Keys, all optional, in pixels and + /// ticks: `gravity`, `maxFall`, `walkSpeed`, `runSpeed`, `jumpSpeed`, + /// `maxJumps`, `coyoteTicks`, `bufferTicks`, `climbSpeed`, `dashSpeed`, + /// `dashTicks`, `wallSlide`, `automaticFire`, `shotGravity`, `fireCooldown`. + /// Unknown keys are ignored so a game can keep its own + /// keys in the same object. + /// + /// #### Parameters + /// + /// - `c`: the actor + /// - `t`: the tuning object, may be null + public static void applyTuning(Actor c, Map t) { + if (t == null) { + return; + } + c.setGravity(LevelJson.fx(t, "gravity", c.getGravity())); + c.setMaxFall(LevelJson.fx(t, "maxFall", c.getMaxFall())); + MoveAbility m = c.getAbility(MoveAbility.class); + if (m != null) { + m.walkSpeed = LevelJson.fx(t, "walkSpeed", m.walkSpeed); + m.runSpeed = LevelJson.fx(t, "runSpeed", m.runSpeed); + } + JumpAbility j = c.getAbility(JumpAbility.class); + if (j != null) { + j.jumpSpeed = LevelJson.fx(t, "jumpSpeed", j.jumpSpeed); + j.maxJumps = LevelJson.integer(t, "maxJumps", j.maxJumps); + j.coyoteTicks = LevelJson.integer(t, "coyoteTicks", j.coyoteTicks); + j.bufferTicks = LevelJson.integer(t, "bufferTicks", j.bufferTicks); + } + LadderAbility l = c.getAbility(LadderAbility.class); + if (l != null) { + l.climbSpeed = LevelJson.fx(t, "climbSpeed", l.climbSpeed); + } + DashAbility d = c.getAbility(DashAbility.class); + if (d != null) { + d.dashSpeed = LevelJson.fx(t, "dashSpeed", d.dashSpeed); + d.dashTicks = LevelJson.integer(t, "dashTicks", d.dashTicks); + } + WallJumpAbility w = c.getAbility(WallJumpAbility.class); + if (w != null) { + w.slideSpeed = LevelJson.fx(t, "wallSlide", w.slideSpeed); + } + WeaponAbility weapon = c.getAbility(WeaponAbility.class); + if (weapon != null) { + weapon.automatic = Boolean.TRUE.equals(t.get("automaticFire")); + weapon.gravity = LevelJson.fx(t, "shotGravity", weapon.gravity); + weapon.cooldownTicks = LevelJson.integer(t, "fireCooldown", weapon.cooldownTicks); + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/LevelJson.java b/CodenameOne/src/com/codename1/gaming/platformer/LevelJson.java new file mode 100644 index 00000000000..ee4a55a56d5 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/LevelJson.java @@ -0,0 +1,343 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// A small JSON reader and writer for level files, shared by the app and the +/// server. +/// +/// Numbers are read straight into fixed point (`Fx#parse`) as `Integer`s, never +/// through `double`, so `"speed": 1.5` means exactly the same thing on every +/// runtime. Objects become `Map`, arrays `List`, and `true`, `false` and `null` +/// what one would expect. +@com.codename1.impl.SharedWithBackend +public final class LevelJson { + private final String src; + private int pos; + + private LevelJson(String src) { + this.src = src; + } + + /// Parses JSON text. + /// + /// #### Parameters + /// + /// - `text`: the JSON + /// + /// #### Returns + /// + /// the parsed value + /// + /// #### Throws + /// + /// - `IllegalArgumentException`: on malformed input, naming the offset + public static Object parse(String text) { + LevelJson p = new LevelJson(text); + Object v = p.value(); + p.skipWs(); + if (p.pos != text.length()) { + throw p.error("Trailing characters"); + } + return v; + } + + private IllegalArgumentException error(String msg) { + return new IllegalArgumentException(msg + " at offset " + pos); + } + + private void skipWs() { + while (pos < src.length()) { + char c = src.charAt(pos); + if (c == ' ' || c == '\n' || c == '\r' || c == '\t') { + pos++; + } else { + break; + } + } + } + + private Object value() { + skipWs(); + if (pos >= src.length()) { + throw error("Unexpected end"); + } + char c = src.charAt(pos); + if (c == '{') { + return object(); + } + if (c == '[') { + return array(); + } + if (c == '"') { + return string(); + } + if (src.startsWith("true", pos)) { + pos += 4; + return Boolean.TRUE; + } + if (src.startsWith("false", pos)) { + pos += 5; + return Boolean.FALSE; + } + if (src.startsWith("null", pos)) { + pos += 4; + return null; + } + int start = pos; + while (pos < src.length()) { + char d = src.charAt(pos); + if ((d >= '0' && d <= '9') || d == '-' || d == '+' || d == '.') { + pos++; + } else { + break; + } + } + if (start == pos) { + throw error("Unexpected '" + c + "'"); + } + try { + return Integer.valueOf(Fx.parse(src.substring(start, pos))); + } catch (IllegalArgumentException e) { + throw error(e.getMessage()); // NOPMD PreserveStackTrace - the message and position are the whole story + } + } + + private Map object() { + Map m = new HashMap(); + pos++; + skipWs(); + if (pos < src.length() && src.charAt(pos) == '}') { + pos++; + return m; + } + while (true) { + skipWs(); + if (pos >= src.length() || src.charAt(pos) != '"') { + throw error("Expected a key"); + } + String key = string(); + skipWs(); + if (pos >= src.length() || src.charAt(pos) != ':') { + throw error("Expected ':'"); + } + pos++; + m.put(key, value()); + skipWs(); + if (pos >= src.length()) { + throw error("Unclosed object"); + } + char c = src.charAt(pos++); + if (c == '}') { + return m; + } + if (c != ',') { + throw error("Expected ',' or '}'"); + } + } + } + + private List array() { + List l = new ArrayList(); + pos++; + skipWs(); + if (pos < src.length() && src.charAt(pos) == ']') { + pos++; + return l; + } + while (true) { + l.add(value()); + skipWs(); + if (pos >= src.length()) { + throw error("Unclosed array"); + } + char c = src.charAt(pos++); + if (c == ']') { + return l; + } + if (c != ',') { + throw error("Expected ',' or ']'"); + } + } + } + + private String string() { + pos++; + StringBuilder sb = new StringBuilder(); + while (pos < src.length()) { + char c = src.charAt(pos++); + if (c == '"') { + return sb.toString(); + } + if (c == '\\') { + if (pos >= src.length()) { + break; + } + char e = src.charAt(pos++); + switch (e) { + case 'n': + sb.append('\n'); + break; + case 't': + sb.append('\t'); + break; + case 'r': + sb.append('\r'); + break; + case 'b': + sb.append('\b'); + break; + case 'f': + sb.append('\f'); + break; + case 'u': + if (pos + 4 > src.length()) { + throw error("Bad escape"); + } + sb.append((char) Integer.parseInt(src.substring(pos, pos + 4), 16)); + pos += 4; + break; + default: + sb.append(e); + break; + } + } else { + sb.append(c); + } + } + throw error("Unclosed string"); + } + + /// Writes a JSON string literal. + /// + /// #### Parameters + /// + /// - `sb`: the output + /// - `s`: the string + public static void quote(StringBuilder sb, String s) { + sb.append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '"' || c == '\\') { + sb.append('\\').append(c); + } else if (c == '\n') { + sb.append("\\n"); + } else if (c < 0x20) { + String hex = Integer.toHexString(c); + sb.append("\\u"); + for (int k = hex.length(); k < 4; k++) { + sb.append('0'); + } + sb.append(hex); + } else { + sb.append(c); + } + } + sb.append('"'); + } + + /// A number field as fixed point. + /// + /// #### Parameters + /// + /// - `m`: the object + /// - `key`: the field + /// - `def`: the value when absent, fixed point + /// + /// #### Returns + /// + /// the field, fixed point + public static int fx(Map m, String key, int def) { + Object v = m == null ? null : m.get(key); + return v instanceof Integer ? ((Integer) v).intValue() : def; + } + + /// A number field as a whole number (the fixed-point value floored). + /// + /// #### Parameters + /// + /// - `m`: the object + /// - `key`: the field + /// - `def`: the value when absent + /// + /// #### Returns + /// + /// the field + public static int integer(Map m, String key, int def) { + Object v = m == null ? null : m.get(key); + return v instanceof Integer ? Fx.floor(((Integer) v).intValue()) : def; + } + + /// A string field. + /// + /// #### Parameters + /// + /// - `m`: the object + /// - `key`: the field + /// - `def`: the value when absent + /// + /// #### Returns + /// + /// the field + public static String str(Map m, String key, String def) { + Object v = m == null ? null : m.get(key); + return v instanceof String ? (String) v : def; + } + + /// An object field. + /// + /// #### Parameters + /// + /// - `m`: the object + /// - `key`: the field + /// + /// #### Returns + /// + /// the nested object, or null + @SuppressWarnings("unchecked") + public static Map obj(Map m, String key) { + Object v = m == null ? null : m.get(key); + return v instanceof Map ? (Map) v : null; + } + + /// An array field. + /// + /// #### Parameters + /// + /// - `m`: the object + /// - `key`: the field + /// + /// #### Returns + /// + /// the list, or an empty list + @SuppressWarnings("unchecked") + public static List list(Map m, String key) { + Object v = m == null ? null : m.get(key); + return v instanceof List ? (List) v : new ArrayList(); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/LookAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/LookAbility.java new file mode 100644 index 00000000000..027fd913a6f --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/LookAbility.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Looking up and down: holding up, or down, while standing still for `delayTicks` +/// sets a look direction that a camera pans by (see `getLook()`). +@com.codename1.impl.SharedWithBackend +public class LookAbility extends Ability { + /// Ticks of holding before the camera pans. + public int delayTicks = 30; + + private int held; + private int look; + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + int v = Input.vertical(c.getInput()); + if (v != 0 && b.isGrounded() && Input.horizontal(c.getInput()) == 0 + && c.getState() != MovementState.CLIMBING) { + held++; + } else { + held = 0; + } + look = held >= delayTicks ? v : 0; + } + + /// The look direction: -1 up, 1 down, 0 neither. + /// + /// #### Returns + /// + /// the direction + public int getLook() { + return look; + } + + @Override + public long hashState(long h) { + return mix(mix(h, held), look); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/MoveAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/MoveAbility.java new file mode 100644 index 00000000000..2741b6b3594 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/MoveAbility.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Horizontal movement: walking, running while `Input#RUN` is held, crawling while +/// crouched, with separate acceleration on the ground and in the air. +@com.codename1.impl.SharedWithBackend +public class MoveAbility extends Ability { + /// Walking speed, fixed point per tick. + public int walkSpeed = Fx.ratio(3, 2); + /// Running speed, fixed point per tick. + public int runSpeed = Fx.ratio(5, 2); + /// Speed while crouched. + public int crawlSpeed = Fx.ratio(3, 4); + /// Change of speed per tick on the ground. + public int groundAcceleration = Fx.ratio(1, 4); + /// Change of speed per tick on the ground with no input, the friction. + public int groundDeceleration = Fx.ratio(3, 8); + /// Change of speed per tick in the air. + public int airAcceleration = Fx.ratio(3, 20); + /// Whether `Input#RUN` is honoured. + public boolean canRun = true; + + @Override + public void process(Actor c, PlatformWorld world) { + MovementState s = c.getState(); + if (s == MovementState.DASHING || s == MovementState.CLIMBING || s == MovementState.DEAD + || c.isControlLocked()) { + return; + } + Body b = c.getBody(); + int dir = Input.horizontal(c.getInput()); + if (dir != 0) { + c.setFacing(dir); + } + boolean crouched = b.h < c.getStandHeight(); + boolean running = canRun && c.held(Input.RUN) && !crouched; + int speed = crouched ? crawlSpeed : running ? runSpeed : walkSpeed; + int target = dir * speed; + int accel; + if (b.isGrounded()) { + accel = dir == 0 ? groundDeceleration : groundAcceleration; + } else { + accel = airAcceleration; + } + b.vx = Fx.approach(b.vx, target, accel); + if (b.isGrounded() && !crouched && b.vx != 0 && running && dir != 0) { + c.claimState(MovementState.RUNNING); + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/MovementState.java b/CodenameOne/src/com/codename1/gaming/platformer/MovementState.java new file mode 100644 index 00000000000..8b812abc99a --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/MovementState.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// What a `Actor` is doing this tick, which a renderer maps to an animation +/// clip (see `ActorAnimator`) and abilities read to stay out of each other's +/// way. +@com.codename1.impl.SharedWithBackend +public enum MovementState { + /// Standing still on the ground. + IDLE, + /// Walking. + WALKING, + /// Running. + RUNNING, + /// Crouched in place. + CROUCHING, + /// Moving while crouched. + CRAWLING, + /// Rising after a jump. + JUMPING, + /// In the air, going down. + FALLING, + /// Sliding down a wall. + WALL_CLINGING, + /// Mid dash. + DASHING, + /// On a ladder. + CLIMBING, + /// Thrust from a jetpack. + JETPACKING, + /// Gliding. + GLIDING, + /// In water. + SWIMMING, + /// Hanging from a ledge or a grip point. + GRIPPING, + /// Pushing a block. + PUSHING, + /// Knocked back after a hit. + HURT, + /// Out of health. + DEAD +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/MovingPlatform.java b/CodenameOne/src/com/codename1/gaming/platformer/MovingPlatform.java new file mode 100644 index 00000000000..e6065e53af7 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/MovingPlatform.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A platform that travels back and forth along a path of waypoints and carries +/// whatever stands on it. +/// +/// It is solid from above only, like `Tile#ONE_WAY`, so an actor can jump up +/// through it. A `PlatformWorld` moves every platform before it moves the +/// actors, and a `Body` standing on one is shifted by the platform's step +/// before its own move, so a rider never slides or sinks. +@com.codename1.impl.SharedWithBackend +public final class MovingPlatform { + private final int[] path; + private final int speed; + private final int width; + private final int height; + private final int pauseTicks; + private int x; + private int y; + private int target; + private int direction = 1; + private int dx; + private int dy; + private int wait; + + /// Creates a platform at the first waypoint. + /// + /// #### Parameters + /// + /// - `path`: waypoint coordinates of the platform's top-left corner, fixed point, + /// as `x0, y0, x1, y1, ...`; at least one point + /// - `width`: the width, fixed point + /// - `height`: the height, fixed point + /// - `speed`: distance per tick, fixed point + /// - `pauseTicks`: ticks to wait at each end of the path + public MovingPlatform(int[] path, int width, int height, int speed, int pauseTicks) { + if (path.length < 2 || (path.length & 1) != 0) { + throw new IllegalArgumentException("A path needs x,y pairs"); + } + this.path = new int[path.length]; + System.arraycopy(path, 0, this.path, 0, path.length); + this.width = width; + this.height = height; + this.speed = speed; + this.pauseTicks = pauseTicks; + this.x = path[0]; + this.y = path[1]; + this.target = path.length > 2 ? 1 : 0; + } + + /// Advances one tick. + public void step() { + int ox = x; + int oy = y; + if (wait > 0) { + wait--; + } else if (path.length > 2) { + int remaining = speed; + int guard = path.length; + while (remaining > 0 && guard-- > 0) { + int tx = path[target * 2]; + int ty = path[target * 2 + 1]; + int ddx = tx - x; + int ddy = ty - y; + int dist = Math.abs(ddx) + Math.abs(ddy); + if (dist <= remaining) { + x = tx; + y = ty; + remaining -= dist; + advanceTarget(); + if (wait > 0) { + break; + } + } else { + // Manhattan-normalised step keeps this exact in integers; paths + // are horizontal or vertical in practice, where it is exact. + x += (int) ((long) ddx * remaining / dist); + y += (int) ((long) ddy * remaining / dist); + remaining = 0; + } + } + } + dx = x - ox; + dy = y - oy; + } + + private void advanceTarget() { + int points = path.length / 2; + int next = target + direction; + if (next < 0 || next >= points) { + direction = -direction; + next = target + direction; + wait = pauseTicks; + } + target = next; + } + + /// Left edge, fixed point. + /// + /// #### Returns + /// + /// the x of the top-left corner + public int getX() { + return x; + } + + /// Top edge, fixed point. + /// + /// #### Returns + /// + /// the y of the top-left corner + public int getY() { + return y; + } + + /// Width, fixed point. + /// + /// #### Returns + /// + /// the width + public int getWidth() { + return width; + } + + /// Height, fixed point. + /// + /// #### Returns + /// + /// the height + public int getHeight() { + return height; + } + + /// How far the platform moved horizontally in the last tick. + /// + /// #### Returns + /// + /// the x delta, fixed point + public int getDx() { + return dx; + } + + /// How far the platform moved vertically in the last tick. + /// + /// #### Returns + /// + /// the y delta, fixed point + public int getDy() { + return dy; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Pickup.java b/CodenameOne/src/com/codename1/gaming/platformer/Pickup.java new file mode 100644 index 00000000000..eaecabefe6a --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Pickup.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A collectible: a coin or gem that scores, a heart that heals, a key, an extra +/// life, or a power-up that switches an ability on. +/// +/// Only the player collects pickups. The kind is the entity type, and decides the +/// effect: +/// +/// | Type | Effect | +/// |---|---| +/// | `coin` | +1 coin, + `value` score | +/// | `gem` | + `value` score, counted as a secret | +/// | `heart` | heals `value` | +/// | `life` | +1 life | +/// | `key` | adds key `name` to the inventory | +/// | `powerup` | enables the ability named `name` (`"dash"`, `"walljump"`, `"jetpack"`, ...) | +/// | anything else | + `value` score | +@com.codename1.impl.SharedWithBackend +public class Pickup extends Entity { + private final int value; + private final String name; + + /// Creates a pickup. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `type`: the kind, see the class description + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `size`: width and height, fixed point + /// - `value`: score or healing + /// - `name`: the key or ability name, may be null + public Pickup(String id, String type, int x, int y, int size, int value, String name) { + super(id, type, x, y, size, size); + this.value = value; + this.name = name; + } + + /// The pickup's value. + /// + /// #### Returns + /// + /// score or healing + public int getValue() { + return value; + } + + /// The key or ability name. + /// + /// #### Returns + /// + /// the name, or null + public String getName() { + return name; + } + + @Override + public void onTouch(PlatformWorld world, Actor c) { + if (c != world.getPlayer() || !isActive()) { // NOPMD CompareObjectsWithEquals - identity is intended + return; + } + String t = getType(); + if ("coin".equals(t)) { + world.addCoins(1); + world.addScore(value); + } else if ("gem".equals(t)) { + world.addScore(value); + world.addSecret(); + } else if ("heart".equals(t)) { + if (c.getHealth() != null) { + c.getHealth().heal(value); + } + } else if ("life".equals(t)) { + world.addLife(); + } else if ("key".equals(t)) { + world.addKey(name); + } else if ("powerup".equals(t)) { + world.enableAbility(c, name); + } else { + world.addScore(value); + } + world.emit(WorldEvent.PICKUP, x + w / 2, y + h / 2, getId(), t); + deactivate(); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/PlatformWorld.java b/CodenameOne/src/com/codename1/gaming/platformer/PlatformWorld.java new file mode 100644 index 00000000000..1a43b65c028 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/PlatformWorld.java @@ -0,0 +1,689 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +import java.util.ArrayList; +import java.util.List; + +/// The whole platformer simulation: a `TileGrid`, its `MovingPlatform`s, the +/// `Actor`s and `Entity`s in it, advanced one fixed tick (1/60 s) at a time. +/// +/// The world is deterministic. Given the same level and the same `Input` bits per +/// tick it reaches the same `hash()` on every device and on the server, which is +/// what `Replay` relies on to verify a run. Rendering never feeds back into it: a +/// view reads positions after each step, interpolates between them, and plays +/// the tick's `getEvents()`. +/// +/// It also keeps the level's bookkeeping, the part of Corgi Engine's level and +/// game managers that affects play: score, coins, secrets, keys, lives, the +/// respawn point and the switch channels. +@com.codename1.impl.SharedWithBackend +public class PlatformWorld { + /// The rate the world is designed for. + public static final int TICKS_PER_SECOND = 60; + + private final TileGrid grid; + private final List platforms = new ArrayList(); + private final List actors = new ArrayList(); + private final List entities = new ArrayList(); + private final List pending = new ArrayList(); + private final List events = new ArrayList(); + private final List keys = new ArrayList(); + private final Rng rng; + private int tick; + private int spawnX; + private int spawnY; + private int goalX; + private int goalY; + private int goalW; + private int goalH; + private boolean complete; + private boolean gameOver; + private int deaths; + private int score; + private int coins; + private int secrets; + private int lives = -1; + private int channels; + private int stompBounce = Fx.ratio(7, 2); + private int tileSizeForAbilities; + + /// Creates a world over a grid. + /// + /// #### Parameters + /// + /// - `grid`: the level's collision map + /// - `seed`: the random seed + public PlatformWorld(TileGrid grid, long seed) { + this.grid = grid; + this.rng = new Rng(seed); + this.tileSizeForAbilities = grid.getTileSize(); + } + + /// Adds a moving platform. + /// + /// #### Parameters + /// + /// - `p`: the platform + public void addPlatform(MovingPlatform p) { + platforms.add(p); + } + + /// Adds an actor. The first one added is the player, which `step` drives + /// with its first input; actors with a brain ignore their input slot. + /// + /// #### Parameters + /// + /// - `c`: the actor + public void addActor(Actor c) { + actors.add(c); + } + + /// Adds an entity. Added during a step, it takes part from the next tick. + /// + /// #### Parameters + /// + /// - `e`: the entity + public void addEntity(Entity e) { + pending.add(e); + } + + /// Adds the entities queued by `addEntity`. Called on the first tick, + /// and by `LevelData.createWorld` so a world it builds lists them + /// before it ever steps. + void flushPending() { + for (int i = 0; i < pending.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Entity e = pending.get(i); + entities.add(e); + e.onAdded(this); + } + pending.clear(); + } + + /// Sets where the player starts and comes back after dying. + /// + /// #### Parameters + /// + /// - `x`: left, fixed point + /// - `y`: top, fixed point + public void setSpawn(int x, int y) { + spawnX = x; + spawnY = y; + } + + /// Sets the goal: the level is complete when the player overlaps it. + /// + /// #### Parameters + /// + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + public void setGoal(int x, int y, int w, int h) { + goalX = x; + goalY = y; + goalW = w; + goalH = h; + } + + /// Advances one tick with one input per actor, in the order they were + /// added. Actors with no input entry get no buttons. + /// + /// #### Parameters + /// + /// - `inputs`: `Input` bits per actor + public void step(int[] inputs) { + if (tick == 0) { + flushPending(); + } + tick++; + events.clear(); + if (gameOver) { + return; + } + for (int i = 0; i < platforms.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + platforms.get(i).step(); + } + int n = entities.size(); + for (int i = 0; i < n; i++) { + Entity e = entities.get(i); + if (e.isActive()) { + e.step(this); + } + } + for (int i = 0; i < actors.size(); i++) { + Actor c = actors.get(i); + if (!c.isAlive()) { + continue; + } + int bits; + if (c.getBrain() != null) { + bits = c.getBrain().think(c, this) & Input.ALL; + } else { + bits = inputs != null && i < inputs.length ? inputs[i] & Input.ALL : 0; + } + Body b = c.getBody(); + boolean wasGrounded = b.isGrounded(); + MovementState before = c.getState(); + c.tick(this, bits); + if (wasGrounded && b.vy < 0) { + emit(WorldEvent.JUMP, b.x + b.w / 2, b.y + b.h, c.getId(), null); + } else if (!wasGrounded && b.isGrounded()) { + emit(WorldEvent.LAND, b.x + b.w / 2, b.y + b.h, c.getId(), null); + } + if (c.getState() == MovementState.DASHING && before != MovementState.DASHING) { + emit(WorldEvent.DASH, b.x + b.w / 2, b.y + b.h / 2, c.getId(), null); + } + if (c.isAlive()) { + checkHazards(c); + } + } + interactActors(); + for (int i = 0; i < entities.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Entity e = entities.get(i); + if (!e.isActive()) { + continue; + } + int m = e.getTouchMargin(); + for (int k = 0; k < actors.size() && e.isActive(); k++) { + Actor c = actors.get(k); + if (c.isAlive() && c.getBody().overlaps(e.x - m, e.y - m, e.w + 2 * m, e.h + 2 * m)) { + e.onTouch(this, c); + } + } + } + for (int i = entities.size() - 1; i >= 0; i--) { + if (!entities.get(i).isActive()) { + entities.remove(i); + } + } + flushPending(); + if (!complete && !actors.isEmpty() && goalW > 0) { + Actor p = actors.get(0); + if (p.isAlive() && p.getBody().overlaps(goalX, goalY, goalW, goalH)) { + complete = true; + emit(WorldEvent.COMPLETE, goalX + goalW / 2, goalY + goalH / 2, p.getId(), null); + } + } + } + + /// Advances one tick for a single player. + /// + /// #### Parameters + /// + /// - `input`: the player's `Input` bits + public void step(int input) { + step(new int[] {input}); + } + + private void interactActors() { + for (int i = 0; i < actors.size(); i++) { + Actor a = actors.get(i); + if (!a.isAlive()) { + continue; + } + for (int k = 0; k < actors.size(); k++) { + Actor e = actors.get(k); + if (k == i || !e.isAlive() || !a.isAlive() || e.getTeam() == a.getTeam()) { + continue; + } + Body ab = a.getBody(); + Body eb = e.getBody(); + if (!ab.overlaps(eb.x, eb.y, eb.w, eb.h)) { + continue; + } + boolean fromAbove = ab.vy >= 0 && ab.getPreviousY() + ab.h <= eb.y + eb.h / 3; + if (e.isStompable() && fromAbove && a.getTeam() == 0) { + ab.vy = -stompBounce; + ab.y = eb.y - ab.h; + JumpAbility j = a.getAbility(JumpAbility.class); + if (j != null) { + j.resetJumps(1); + } + emit(WorldEvent.STOMP, eb.x + eb.w / 2, eb.y, a.getId(), e.getId()); + damage(e, 1, ab.x + ab.w / 2); + } else if (e.getContactDamage() > 0) { + damage(a, e.getContactDamage(), eb.x + eb.w / 2); + } + } + } + } + + private void checkHazards(Actor c) { + Body b = c.getBody(); + boolean fell = b.y > grid.getHeight() + grid.getTileSize() * 2; + if (fell) { + if (c.getHealth() != null) { + c.getHealth().hit(c.getHealth().getCurrent()); + } + onDeath(c); + return; + } + if (grid.overlaps(b.x + Fx.of(1), b.y + Fx.of(1), b.w - Fx.of(2), b.h - Fx.of(1), Tile.HAZARD)) { + damage(c, 1, b.x + b.w / 2 - c.getFacing()); + } + } + + /// Hurts an actor: removes hit points (respecting invulnerability), knocks it + /// away from `fromX`, and kills it at zero. An actor without `Health` dies + /// at once. + /// + /// #### Parameters + /// + /// - `c`: the actor + /// - `amount`: hit points + /// - `fromX`: where the hit came from, fixed point x + /// + /// #### Returns + /// + /// true if the hit landed + public boolean damage(Actor c, int amount, int fromX) { + if (!c.isAlive()) { + return false; + } + Health h = c.getHealth(); + if (h == null) { + emit(WorldEvent.HURT, c.getBody().x + c.getBody().w / 2, c.getBody().y, c.getId(), null); + onDeath(c); + return true; + } + if (!h.hit(amount)) { + return false; + } + Body b = c.getBody(); + emit(WorldEvent.HURT, b.x + b.w / 2, b.y, c.getId(), null); + if (h.getCurrent() <= 0) { + onDeath(c); + return true; + } + int away = b.x + b.w / 2 >= fromX ? 1 : -1; + b.vx = away * h.knockbackX; + b.vy = -h.knockbackY; + c.lockControl(h.stunTicks); + c.forceState(MovementState.HURT); + return true; + } + + /// Called when an actor runs out of health or falls out of the level. The + /// player loses a life and respawns at the last checkpoint, or the game is + /// over; any other actor dies. Override to change the rules. + /// + /// #### Parameters + /// + /// - `c`: the actor + protected void onDeath(Actor c) { + Body b = c.getBody(); + emit(WorldEvent.DEATH, b.x + b.w / 2, b.y + b.h / 2, c.getId(), c.getKind()); + if (!actors.isEmpty() && c == actors.get(0)) { // NOPMD CompareObjectsWithEquals - identity is intended + deaths++; + if (lives > 0) { + lives--; + } + if (lives == 0) { + c.kill(); + gameOver = true; + emit(WorldEvent.GAME_OVER, b.x, b.y, c.getId(), null); + return; + } + c.respawn(spawnX, spawnY); + if (c.getHealth() != null) { + c.getHealth().grantInvulnerability(60); + } + } else { + c.kill(); + if (c.getDefeatChannel() > 0) { + setChannel(c.getDefeatChannel(), true); + } + } + } + + /// Records an event for the view. + /// + /// #### Parameters + /// + /// - `type`: a `WorldEvent` constant + /// - `x`: where, fixed point + /// - `y`: where, fixed point + /// - `subject`: the id involved, may be null + /// - `detail`: extra detail, may be null + public void emit(int type, int x, int y, String subject, String detail) { + events.add(new WorldEvent(type, x, y, subject, detail)); + } + + /// The events of the last tick. + /// + /// #### Returns + /// + /// the live list, cleared at the start of each step + public List getEvents() { + return events; + } + + /// Switches an ability on for an actor, creating it if the actor lacks + /// it, as a power-up does. + /// + /// #### Parameters + /// + /// - `c`: the actor + /// - `name`: a stock ability name (see `Abilities`) + public void enableAbility(Actor c, String name) { + Class type = Abilities.typeOf(name); + if (type == null) { + return; + } + Ability a = c.getAbility(type); + if (a == null) { + a = Abilities.create(name, tileSizeForAbilities); + c.addAbility(a); + } + a.setEnabled(true); + } + + /// Whether a switch channel is on. + /// + /// #### Parameters + /// + /// - `channel`: 0 to 31 + /// + /// #### Returns + /// + /// true while on + public boolean isChannelOn(int channel) { + return (channels & (1 << (channel & 31))) != 0; + } + + /// Turns a switch channel on or off. + /// + /// #### Parameters + /// + /// - `channel`: 0 to 31 + /// - `on`: the new state + public void setChannel(int channel, boolean on) { + int bit = 1 << (channel & 31); + channels = on ? channels | bit : channels & ~bit; + } + + /// Adds to the score. + /// + /// #### Parameters + /// + /// - `points`: the points + public void addScore(int points) { + score += points; + } + + /// Adds coins. + /// + /// #### Parameters + /// + /// - `n`: the coins + public void addCoins(int n) { + coins += n; + } + + /// Counts a secret found. + public void addSecret() { + secrets++; + } + + /// Adds a life, when lives are limited. + public void addLife() { + if (lives >= 0) { + lives++; + } + } + + /// Adds a key to the inventory. + /// + /// #### Parameters + /// + /// - `name`: the key name + public void addKey(String name) { + keys.add(name == null ? "" : name); + } + + /// Uses up a key. + /// + /// #### Parameters + /// + /// - `name`: the key name + /// + /// #### Returns + /// + /// true if the key was held + public boolean useKey(String name) { + return keys.remove(name == null ? "" : name); + } + + /// The keys held. + /// + /// #### Returns + /// + /// the live list + public List getKeys() { + return keys; + } + + /// Lives left; negative means unlimited. + /// + /// #### Returns + /// + /// the lives + public int getLives() { + return lives; + } + + /// Sets the lives; negative means unlimited. + /// + /// #### Parameters + /// + /// - `lives`: the lives + public void setLives(int lives) { + this.lives = lives; + } + + /// The upward speed of a stomp bounce. + /// + /// #### Parameters + /// + /// - `speed`: fixed point per tick + public void setStompBounce(int speed) { + this.stompBounce = speed; + } + + /// The score. + /// + /// #### Returns + /// + /// the score + public int getScore() { + return score; + } + + /// The coins collected. + /// + /// #### Returns + /// + /// the coins + public int getCoins() { + return coins; + } + + /// The secrets found. + /// + /// #### Returns + /// + /// the secrets + public int getSecrets() { + return secrets; + } + + /// The collision map. + /// + /// #### Returns + /// + /// the grid + public TileGrid getGrid() { + return grid; + } + + /// The moving platforms. + /// + /// #### Returns + /// + /// the live list + public List getPlatforms() { + return platforms; + } + + /// The actors, the player first. + /// + /// #### Returns + /// + /// the live list + public List getActors() { + return actors; + } + + /// The active entities. + /// + /// #### Returns + /// + /// the live list + public List getEntities() { + return entities; + } + + /// The player, the first actor added. + /// + /// #### Returns + /// + /// the player, or null in an empty world + public Actor getPlayer() { + return actors.isEmpty() ? null : actors.get(0); + } + + /// The world's random generator. Only the simulation may draw from it. + /// + /// #### Returns + /// + /// the generator + public Rng getRng() { + return rng; + } + + /// Ticks stepped so far. + /// + /// #### Returns + /// + /// the tick count + public int getTick() { + return tick; + } + + /// Whether the player reached the goal. + /// + /// #### Returns + /// + /// true once complete + public boolean isComplete() { + return complete; + } + + /// Whether the player ran out of lives. + /// + /// #### Returns + /// + /// true once the game is over + public boolean isGameOver() { + return gameOver; + } + + /// How many times the player died. + /// + /// #### Returns + /// + /// the death count + public int getDeaths() { + return deaths; + } + + /// Spawn x, fixed point. + /// + /// #### Returns + /// + /// the spawn's left edge + public int getSpawnX() { + return spawnX; + } + + /// Spawn y, fixed point. + /// + /// #### Returns + /// + /// the spawn's top edge + public int getSpawnY() { + return spawnY; + } + + /// The goal rectangle as `{x, y, w, h}`, fixed point. + /// + /// #### Returns + /// + /// a new array + public int[] getGoal() { + return new int[] {goalX, goalY, goalW, goalH}; + } + + /// A 64-bit digest of the whole simulation state. Two worlds that stepped the + /// same level with the same inputs have the same hash; a replay compares it. + /// + /// #### Returns + /// + /// the hash + public long hash() { + long h = 0xcbf29ce484222325L; + h = Ability.mix(h, tick); + h = Ability.mix(h, rng.state()); + h = Ability.mix(h, complete ? 1 : 0); + h = Ability.mix(h, deaths); + h = Ability.mix(h, score); + h = Ability.mix(h, coins); + h = Ability.mix(h, lives); + h = Ability.mix(h, channels); + h = Ability.mix(h, keys.size()); + for (int i = 0; i < platforms.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + MovingPlatform p = platforms.get(i); + h = Ability.mix(h, p.getX()); + h = Ability.mix(h, p.getY()); + } + for (int i = 0; i < actors.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + h = actors.get(i).hash(h); + } + for (int i = 0; i < entities.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + h = entities.get(i).hashState(h); + } + return h; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Projectile.java b/CodenameOne/src/com/codename1/gaming/platformer/Projectile.java new file mode 100644 index 00000000000..8f51ef6c699 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Projectile.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A bullet, arrow or fireball: flies at a fixed velocity, optionally falls, and +/// damages the first actor of another team it touches. It disappears on a +/// solid tile, on a hit, or when its range runs out. +@com.codename1.impl.SharedWithBackend +public class Projectile extends Entity { + private final int team; + private final int damage; + private final int gravity; + private int vx; + private int vy; + private int life; + + /// Creates a projectile. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `type`: the kind, for the art (`"bullet"`, `"arrow"`, `"slash"`) + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `size`: width and height, fixed point + /// - `vx`: horizontal speed, fixed point per tick + /// - `vy`: vertical speed, fixed point per tick + /// - `gravity`: downward acceleration, 0 for a straight shot + /// - `team`: the shooter's team; it never hurts its own + /// - `damage`: hit points removed on a hit + /// - `lifeTicks`: ticks before it expires + public Projectile(String id, String type, int x, int y, int size, int vx, int vy, int gravity, + int team, int damage, int lifeTicks) { + super(id, type, x, y, size, size); + this.vx = vx; + this.vy = vy; + this.gravity = gravity; + this.team = team; + this.damage = damage; + this.life = lifeTicks; + } + + /// The horizontal speed, which the view uses to flip the sprite. + /// + /// #### Returns + /// + /// the speed, fixed point per tick + public int getVx() { + return vx; + } + + @Override + public void step(PlatformWorld world) { + life--; + if (life <= 0) { + deactivate(); + return; + } + vy += gravity; + x += vx; + y += vy; + TileGrid g = world.getGrid(); + if (g.blocked(x, y, w, h)) { + world.emit(WorldEvent.IMPACT, x + w / 2, y + h / 2, getId(), null); + deactivate(); + } + } + + @Override + public void onTouch(PlatformWorld world, Actor c) { + if (!isActive() || c.getTeam() == team) { + return; + } + // A shot is spent on whatever it hits, even a target that is still + // invulnerable from the last hit: passing through would read as a miss. + world.damage(c, damage, x + w / 2); + world.emit(WorldEvent.IMPACT, x + w / 2, y + h / 2, getId(), c.getId()); + deactivate(); + } + + @Override + public long hashState(long h) { + return Ability.mix(Ability.mix(super.hashState(h), vy), life); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Replay.java b/CodenameOne/src/com/codename1/gaming/platformer/Replay.java new file mode 100644 index 00000000000..930e3f4a94d --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Replay.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Plays a recorded run against a level and reports what happened, which is how a +/// server verifies a score instead of trusting it. +/// +/// ```java +/// Replay.Result r = Replay.run(LevelData.parse(levelJson), seed, InputLog.decode(upload, 60 * 60 * 15)); +/// if (r.isComplete() && r.getTicks() == claimedTicks) { +/// // the time is real +/// } +/// ``` +@com.codename1.impl.SharedWithBackend +public final class Replay { + private Replay() { + } + + /// The outcome of a replay. + public static final class Result { + private final boolean complete; + private final int ticks; + private final int deaths; + private final long hash; + private final int score; + private final int coins; + private final int secrets; + + /// Snapshots a world's outcome as it stands, so a client can score the + /// run it just watched with the same rules the server applies to the + /// replay. + /// + /// #### Parameters + /// + /// - `w`: the world, usually finished + public Result(PlatformWorld w) { + this.complete = w.isComplete(); + this.ticks = w.getTick(); + this.deaths = w.getDeaths(); + this.hash = w.hash(); + this.score = w.getScore(); + this.coins = w.getCoins(); + this.secrets = w.getSecrets(); + } + + /// The points the run scored in the world (pickups, stomps). + /// + /// #### Returns + /// + /// the world score + public int getScore() { + return score; + } + + /// The coins the run collected. + /// + /// #### Returns + /// + /// the coin count + public int getCoins() { + return coins; + } + + /// The secrets the run found. + /// + /// #### Returns + /// + /// the secret count + public int getSecrets() { + return secrets; + } + + /// Whether the run reached the goal. + /// + /// #### Returns + /// + /// true if complete + public boolean isComplete() { + return complete; + } + + /// The tick the goal was reached on, or the log's length if never. + /// + /// #### Returns + /// + /// the tick count + public int getTicks() { + return ticks; + } + + /// Deaths during the run. + /// + /// #### Returns + /// + /// the death count + public int getDeaths() { + return deaths; + } + + /// The world hash where the replay stopped. + /// + /// #### Returns + /// + /// the hash + public long getHash() { + return hash; + } + } + + /// Replays a log, stopping at the tick the goal is reached. + /// + /// #### Parameters + /// + /// - `level`: the level + /// - `seed`: the seed the run used + /// - `log`: the recorded input + /// + /// #### Returns + /// + /// the outcome + public static Result run(LevelData level, long seed, InputLog log) { + PlatformWorld w = level.createWorld(seed); + int[] in = log.toArray(); + for (int i = 0; i < in.length && !w.isComplete() && !w.isGameOver(); i++) { + w.step(in[i]); + } + return new Result(w); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Rng.java b/CodenameOne/src/com/codename1/gaming/platformer/Rng.java new file mode 100644 index 00000000000..01ff667af0e --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Rng.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// SplitMix64, the simulation's only source of randomness. +/// +/// Seeded from the level and the run, it yields the same sequence on every runtime, +/// so an enemy that picks a random patrol turn picks the same one in a replay. +@com.codename1.impl.SharedWithBackend +public final class Rng { + private long state; + + /// Creates a generator. + /// + /// #### Parameters + /// + /// - `seed`: the seed + public Rng(long seed) { + this.state = seed; + } + + /// The next 64 random bits. + /// + /// #### Returns + /// + /// a random `long` + public long nextLong() { + state += 0x9E3779B97F4A7C15L; + long z = state; + z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L; + z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL; + return z ^ (z >>> 31); + } + + /// A random whole number in `[0, bound)`. + /// + /// #### Parameters + /// + /// - `bound`: the exclusive upper bound, positive + /// + /// #### Returns + /// + /// a random whole number + public int nextInt(int bound) { + if (bound <= 0) { + throw new IllegalArgumentException("bound must be positive"); + } + return (int) ((nextLong() >>> 1) % bound); + } + + /// The generator's state, folded into the world hash. + /// + /// #### Returns + /// + /// the internal state + public long state() { + return state; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Spring.java b/CodenameOne/src/com/codename1/gaming/platformer/Spring.java new file mode 100644 index 00000000000..9b10f8f6b7d --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Spring.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A spring pad that launches whoever lands on it upward at `power`, restoring +/// their air jumps. +@com.codename1.impl.SharedWithBackend +public class Spring extends Entity { + private final int power; + private int compressed; + + /// Creates a spring. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + /// - `power`: launch speed, fixed point per tick + public Spring(String id, int x, int y, int w, int h, int power) { + super(id, "spring", x, y, w, h); + this.power = power; + } + + @Override + public int getPhase() { + return compressed > 0 ? 1 : 0; + } + + @Override + public void step(PlatformWorld world) { + if (compressed > 0) { + compressed--; + } + } + + @Override + public void onTouch(PlatformWorld world, Actor c) { + Body b = c.getBody(); + if (b.vy < 0 && compressed > 0) { + return; + } + if (b.getPreviousY() + b.h <= y + h / 2 || b.isGrounded()) { + b.vy = -power; + b.y = Math.min(b.y, y - b.h); + compressed = 10; + JumpAbility j = c.getAbility(JumpAbility.class); + if (j != null) { + j.resetJumps(1); + } + world.emit(WorldEvent.BOUNCE, x + w / 2, y, c.getId(), null); + } + } + + @Override + public long hashState(long h) { + return Ability.mix(super.hashState(h), compressed); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/SwimAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/SwimAbility.java new file mode 100644 index 00000000000..cb6616bbf0b --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/SwimAbility.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Swimming in `Tile#WATER`: weak gravity, a slow sink, and a stroke upward on each +/// jump press. Leaving the water at the surface with a stroke gives a small hop out. +@com.codename1.impl.SharedWithBackend +public class SwimAbility extends Ability { + /// Gravity in water, fixed point per tick squared. + public int waterGravity = Fx.ratio(1, 20); + /// Fastest sink. + public int maxSink = Fx.of(1); + /// Upward speed of a stroke. + public int stroke = Fx.ratio(5, 2); + /// Horizontal speed limit in water. + public int maxSwimSpeed = Fx.of(1); + + private boolean inWater; + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + inWater = world.getGrid().overlaps(b.x, b.y + b.h / 2, b.w, b.h / 2, Tile.WATER); + if (!inWater || c.getState() == MovementState.CLIMBING) { + return; + } + c.suspendGravity(); + b.vy = Math.min(b.vy + waterGravity, maxSink); + b.vx = Fx.clamp(b.vx, -maxSwimSpeed, maxSwimSpeed); + if (c.pressed(Input.JUMP) && !c.isJumpConsumed()) { + b.vy = -stroke; + c.consumeJump(); + } + if (c.held(Input.DOWN)) { + b.vy = Math.max(b.vy, maxSink); + } + c.claimState(MovementState.SWIMMING); + } + + /// Whether the actor is in water. + /// + /// #### Returns + /// + /// true while swimming + public boolean isInWater() { + return inWater; + } + + @Override + public long hashState(long h) { + return mix(h, inWater ? 1 : 0); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Switch.java b/CodenameOne/src/com/codename1/gaming/platformer/Switch.java new file mode 100644 index 00000000000..0a01e3e321e --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Switch.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// A lever or a pressure plate on a channel. +/// +/// A lever toggles its channel when the player presses `Input#ACTIVATE` at it; a +/// plate (`plate = true`) holds the channel on while any actor stands on it. +@com.codename1.impl.SharedWithBackend +public class Switch extends Entity { + private final int channel; + private final boolean plate; + private boolean pressed; + private boolean on; + + /// Creates a switch. + /// + /// #### Parameters + /// + /// - `id`: the id + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + /// - `channel`: the channel, 0 to 31 + /// - `plate`: true for a pressure plate, false for a lever + public Switch(String id, int x, int y, int w, int h, int channel, boolean plate) { + super(id, plate ? "plate" : "lever", x, y, w, h); + this.channel = channel; + this.plate = plate; + } + + @Override + public int getPhase() { + return on ? 1 : 0; + } + + @Override + public void step(PlatformWorld world) { + if (plate) { + if (on != pressed) { + on = pressed; + world.setChannel(channel, on); + world.emit(WorldEvent.SWITCH, x + w / 2, y, getId(), on ? "on" : "off"); + } + pressed = false; + } + } + + @Override + public void onTouch(PlatformWorld world, Actor c) { + if (plate) { + pressed = true; + } else if (c == world.getPlayer() && c.pressed(Input.ACTIVATE)) { // NOPMD CompareObjectsWithEquals - identity is intended + on = !on; + world.setChannel(channel, on); + world.emit(WorldEvent.SWITCH, x + w / 2, y, getId(), on ? "on" : "off"); + } + } + + @Override + public long hashState(long h) { + return Ability.mix(Ability.mix(super.hashState(h), on ? 1 : 0), pressed ? 1 : 0); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/Tile.java b/CodenameOne/src/com/codename1/gaming/platformer/Tile.java new file mode 100644 index 00000000000..bb207912d97 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/Tile.java @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// The collision kinds a `TileGrid` cell can hold, and the actors a level file +/// writes them with. +/// +/// A level's tiles are rows of text, one character per cell, which a person or a +/// language model can read and write directly: +/// +/// | Char | Kind | Collision | +/// |---|---|---| +/// | `.` or space | `EMPTY` | none | +/// | `#` | `SOLID` | blocks from every side | +/// | `=` | `ONE_WAY` | stands on its top, passes from below and the sides; drop through with down + jump | +/// | `/` | `SLOPE_UP` | 45 degree floor rising to the right | +/// | `\` | `SLOPE_DOWN` | 45 degree floor falling to the right | +/// | `a` `b` | `SLOPE_UP_LOW`, `SLOPE_UP_HIGH` | a 22.5 degree rise, two tiles wide | +/// | `c` `d` | `SLOPE_DOWN_HIGH`, `SLOPE_DOWN_LOW` | a 22.5 degree fall, two tiles wide | +/// | `H` | `LADDER` | climbable; the top rung of a ladder can be stood on | +/// | `^` | `HAZARD` | hurts on touch, no collision | +/// | `~` | `WATER` | a swim volume, no collision | +/// | `r` `f` | aliases for `/` and `\` | for writers that escape backslashes badly | +@com.codename1.impl.SharedWithBackend +public final class Tile { + /// Nothing. + public static final byte EMPTY = 0; + /// A full block. + public static final byte SOLID = 1; + /// A platform that is solid from above only. + public static final byte ONE_WAY = 2; + /// A 45 degree slope rising left to right. + public static final byte SLOPE_UP = 3; + /// A 45 degree slope falling left to right. + public static final byte SLOPE_DOWN = 4; + /// The low half of a 22.5 degree rise. + public static final byte SLOPE_UP_LOW = 5; + /// The high half of a 22.5 degree rise. + public static final byte SLOPE_UP_HIGH = 6; + /// The high half of a 22.5 degree fall. + public static final byte SLOPE_DOWN_HIGH = 7; + /// The low half of a 22.5 degree fall. + public static final byte SLOPE_DOWN_LOW = 8; + /// A climbable ladder. + public static final byte LADDER = 9; + /// A damaging cell such as spikes. + public static final byte HAZARD = 10; + /// Water an actor swims in. + public static final byte WATER = 11; + + private Tile() { + } + + /// Maps a level-file character to its kind. + /// + /// #### Parameters + /// + /// - `c`: the character + /// + /// #### Returns + /// + /// the kind, or `-1` for an actor that is not a tile + public static int fromChar(char c) { + switch (c) { + case '.': + case ' ': + return EMPTY; + case '#': + return SOLID; + case '=': + return ONE_WAY; + case '/': + case 'r': + return SLOPE_UP; + case '\\': + case 'f': + return SLOPE_DOWN; + case 'a': + return SLOPE_UP_LOW; + case 'b': + return SLOPE_UP_HIGH; + case 'c': + return SLOPE_DOWN_HIGH; + case 'd': + return SLOPE_DOWN_LOW; + case 'H': + return LADDER; + case '^': + return HAZARD; + case '~': + return WATER; + default: + return -1; + } + } + + /// The canonical level-file character for a kind. + /// + /// #### Parameters + /// + /// - `kind`: a tile kind + /// + /// #### Returns + /// + /// its character + public static char toChar(int kind) { + switch (kind) { + case SOLID: + return '#'; + case ONE_WAY: + return '='; + case SLOPE_UP: + return '/'; + case SLOPE_DOWN: + return '\\'; + case SLOPE_UP_LOW: + return 'a'; + case SLOPE_UP_HIGH: + return 'b'; + case SLOPE_DOWN_HIGH: + return 'c'; + case SLOPE_DOWN_LOW: + return 'd'; + case LADDER: + return 'H'; + case HAZARD: + return '^'; + case WATER: + return '~'; + default: + return '.'; + } + } + + /// Whether a kind is one of the slopes. + /// + /// #### Parameters + /// + /// - `kind`: a tile kind + /// + /// #### Returns + /// + /// true for the six slope kinds + public static boolean isSlope(int kind) { + return kind >= SLOPE_UP && kind <= SLOPE_DOWN_LOW; + } + + /// The floor height of a slope at a point across the tile, measured down from + /// the tile's top edge. + /// + /// #### Parameters + /// + /// - `kind`: a slope kind + /// - `lx`: the distance from the tile's left edge, fixed point, in `[0, ts]` + /// - `ts`: the tile size, fixed point + /// + /// #### Returns + /// + /// the distance from the tile's top down to the floor, fixed point + public static int slopeDepth(int kind, int lx, int ts) { + int x = Fx.clamp(lx, 0, ts); + switch (kind) { + case SLOPE_UP: + return ts - x; + case SLOPE_DOWN: + return x; + case SLOPE_UP_LOW: + return ts - x / 2; + case SLOPE_UP_HIGH: + return ts / 2 - x / 2; + case SLOPE_DOWN_HIGH: + return x / 2; + case SLOPE_DOWN_LOW: + return ts / 2 + x / 2; + default: + return 0; + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/TileGrid.java b/CodenameOne/src/com/codename1/gaming/platformer/TileGrid.java new file mode 100644 index 00000000000..3b34820c870 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/TileGrid.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// The collision map of a level: a grid of `Tile` kinds. +/// +/// Cells outside the grid read as `Tile#SOLID` to the left and right, so nothing +/// walks off the side of a level, and as `Tile#EMPTY` above and below, so a +/// actor can jump above the top row and falls out of the bottom one (which a +/// `PlatformWorld` treats as a death). +@com.codename1.impl.SharedWithBackend +public final class TileGrid { + private final int cols; + private final int rows; + private final int tileSize; + private final byte[] cells; + + /// Creates an empty grid. + /// + /// #### Parameters + /// + /// - `cols`: the width in tiles + /// - `rows`: the height in tiles + /// - `tileSizePx`: the side of a tile in pixels, a whole number + public TileGrid(int cols, int rows, int tileSizePx) { + if (cols <= 0 || rows <= 0 || tileSizePx <= 1) { + throw new IllegalArgumentException("Bad grid " + cols + "x" + rows + "@" + tileSizePx); + } + this.cols = cols; + this.rows = rows; + this.tileSize = Fx.of(tileSizePx); + this.cells = new byte[cols * rows]; + } + + /// Builds a grid from rows of level-file characters (see `Tile`). Short rows are + /// padded with empty cells. + /// + /// #### Parameters + /// + /// - `lines`: the rows, top first + /// - `tileSizePx`: the side of a tile in pixels + /// + /// #### Returns + /// + /// the grid + /// + /// #### Throws + /// + /// - `IllegalArgumentException`: on an actor that is not a tile + public static TileGrid parse(String[] lines, int tileSizePx) { + int w = 1; + for (int i = 0; i < lines.length; i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + if (lines[i].length() > w) { + w = lines[i].length(); + } + } + TileGrid g = new TileGrid(w, Math.max(1, lines.length), tileSizePx); + for (int r = 0; r < lines.length; r++) { + String line = lines[r]; + for (int c = 0; c < line.length(); c++) { + int k = Tile.fromChar(line.charAt(c)); + if (k < 0) { + throw new IllegalArgumentException("Unknown tile '" + line.charAt(c) + + "' at column " + c + ", row " + r); + } + g.cells[r * w + c] = (byte) k; + } + } + return g; + } + + /// The width in tiles. + /// + /// #### Returns + /// + /// the column count + public int getCols() { + return cols; + } + + /// The height in tiles. + /// + /// #### Returns + /// + /// the row count + public int getRows() { + return rows; + } + + /// The side of a tile, fixed point. + /// + /// #### Returns + /// + /// the tile size + public int getTileSize() { + return tileSize; + } + + /// The width of the level, fixed point. + /// + /// #### Returns + /// + /// the pixel width scaled by `Fx#ONE` + public int getWidth() { + return cols * tileSize; + } + + /// The height of the level, fixed point. + /// + /// #### Returns + /// + /// the pixel height scaled by `Fx#ONE` + public int getHeight() { + return rows * tileSize; + } + + /// The kind of a cell, with the out-of-bounds rule in the class description. + /// + /// #### Parameters + /// + /// - `c`: the column + /// - `r`: the row + /// + /// #### Returns + /// + /// a `Tile` kind + public int get(int c, int r) { + if (c < 0 || c >= cols) { + return Tile.SOLID; + } + if (r < 0 || r >= rows) { + return Tile.EMPTY; + } + return cells[r * cols + c]; + } + + /// Changes a cell, for breakable blocks and the level editor. Cells outside the + /// grid are ignored. + /// + /// #### Parameters + /// + /// - `c`: the column + /// - `r`: the row + /// - `kind`: the new `Tile` kind + public void set(int c, int r, int kind) { + if (c >= 0 && c < cols && r >= 0 && r < rows) { + cells[r * cols + c] = (byte) kind; + } + } + + /// The column containing a fixed-point x. + /// + /// #### Parameters + /// + /// - `x`: a fixed-point x + /// + /// #### Returns + /// + /// the column index + public int col(int x) { + return Fx.floorDiv(x, tileSize); + } + + /// The row containing a fixed-point y. + /// + /// #### Parameters + /// + /// - `y`: a fixed-point y + /// + /// #### Returns + /// + /// the row index + public int row(int y) { + return Fx.floorDiv(y, tileSize); + } + + /// Whether any cell a rectangle touches is of a kind. + /// + /// #### Parameters + /// + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + /// - `kind`: the `Tile` kind + /// + /// #### Returns + /// + /// true if one of the touched cells is `kind` + public boolean overlaps(int x, int y, int w, int h, int kind) { + int c1 = col(x + w - 1); + int r1 = row(y + h - 1); + for (int r = row(y); r <= r1; r++) { + for (int c = col(x); c <= c1; c++) { + if (get(c, r) == kind) { + return true; + } + } + } + return false; + } + + /// Whether a rectangle overlaps any solid cell, as a crouching actor asks + /// before it stands up. + /// + /// #### Parameters + /// + /// - `x`: left, fixed point + /// - `y`: top, fixed point + /// - `w`: width, fixed point + /// - `h`: height, fixed point + /// + /// #### Returns + /// + /// true if the rectangle is blocked + public boolean blocked(int x, int y, int w, int h) { + return overlaps(x, y, w, h, Tile.SOLID); + } + + /// The grid as level-file rows, the inverse of `parse`. + /// + /// #### Returns + /// + /// one string per row, top first + public String[] toLines() { + String[] out = new String[rows]; + StringBuilder sb = new StringBuilder(); + for (int r = 0; r < rows; r++) { + sb.setLength(0); + for (int c = 0; c < cols; c++) { + sb.append(Tile.toChar(cells[r * cols + c])); + } + out[r] = sb.toString(); + } + return out; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/WallJumpAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/WallJumpAbility.java new file mode 100644 index 00000000000..690aa2381d7 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/WallJumpAbility.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Wall clinging and wall jumping. Falling while pushing into a wall slows the fall +/// to `slideSpeed`; jumping from the wall (or within `graceTicks` of leaving it) +/// kicks the actor up and away, locking control for `lockTicks` so the kick +/// carries before input steers again. +/// +/// Add it before `JumpAbility`, which it pre-empts on the wall. +@com.codename1.impl.SharedWithBackend +public class WallJumpAbility extends Ability { + /// Fastest fall while clinging, fixed point per tick. + public int slideSpeed = Fx.of(1); + /// Horizontal kick of a wall jump. + public int kickX = Fx.ratio(5, 2); + /// Vertical speed of a wall jump. + public int kickY = Fx.ratio(21, 5); + /// Ticks horizontal control is locked after a wall jump. + public int lockTicks = 8; + /// Ticks after leaving a wall that a wall jump still works. + public int graceTicks = 4; + + private int wallSide; + private int grace; + + @Override + public void process(Actor c, PlatformWorld world) { + Body b = c.getBody(); + if (c.getState() == MovementState.CLIMBING || c.getState() == MovementState.DASHING) { + grace = 0; + return; + } + if (grace > 0 && !b.isGrounded() && c.pressed(Input.JUMP) && !c.isJumpConsumed()) { + b.vy = -kickY; + b.vx = -wallSide * kickX; + c.setFacing(-wallSide); + c.lockControl(lockTicks); + c.consumeJump(); + JumpAbility j = c.getAbility(JumpAbility.class); + if (j != null) { + j.resetJumps(1); + } + grace = 0; + c.claimState(MovementState.JUMPING); + return; + } + int dir = Input.horizontal(c.getInput()); + if (!b.isGrounded() && wallSide != 0 && dir == wallSide && b.vy > 0) { + c.suspendGravity(); + b.vy = Math.min(b.vy + c.getGravity(), slideSpeed); + c.claimState(MovementState.WALL_CLINGING); + } + } + + @Override + public void lateProcess(Actor c, PlatformWorld world) { + Body b = c.getBody(); + int dir = Input.horizontal(c.getInput()); + int touching = b.hitLeft() ? -1 : b.hitRight() ? 1 : 0; + if (!b.isGrounded() && touching != 0 && dir == touching) { + wallSide = touching; + grace = graceTicks; + } else { + if (grace > 0) { + grace--; + } + if (grace == 0 || b.isGrounded()) { + wallSide = 0; + grace = 0; + } + } + } + + @Override + public long hashState(long h) { + return mix(mix(h, wallSide), grace); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/WeaponAbility.java b/CodenameOne/src/com/codename1/gaming/platformer/WeaponAbility.java new file mode 100644 index 00000000000..f1c2056c7aa --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/WeaponAbility.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Firing on `Input#FIRE`: projectiles (a blaster, a bow) or a melee swing, with a +/// cooldown, optional ammunition and eight-way aiming from the held directions. +/// +/// A melee weapon (`speed` 0) is a short-lived projectile that does not move, +/// placed in front of the actor, so one mechanism covers both. +@com.codename1.impl.SharedWithBackend +public class WeaponAbility extends Ability { + /// The projectile's art type. + public String projectileType = "bullet"; + /// Projectile speed, fixed point per tick; 0 makes a melee weapon. + public int speed = Fx.of(5); + /// Projectile size, fixed point. + public int size = Fx.of(4); + /// Gravity on the projectile, 0 for straight shots. + public int gravity; + /// Damage per hit. + public int damage = 1; + /// Ticks between shots. + public int cooldownTicks = 14; + /// Ticks a projectile lives (its range). + public int lifeTicks = 50; + /// Rounds left; negative is unlimited. + public int ammo = -1; + /// Whether up/down aim the shot diagonally or vertically. + public boolean eightWay = true; + /// Whether the trigger can be held for automatic fire. + public boolean automatic; + + private int cooldown; + private int shots; + + @Override + public void process(Actor c, PlatformWorld world) { + if (cooldown > 0) { + cooldown--; + } + boolean trigger = automatic ? c.held(Input.FIRE) : c.pressed(Input.FIRE); + if (!trigger || cooldown > 0 || ammo == 0 || !c.isAlive() + || c.getState() == MovementState.CLIMBING) { + return; + } + cooldown = cooldownTicks; + if (ammo > 0) { + ammo--; + } + Body b = c.getBody(); + int dx = c.getFacing(); + int dy = 0; + if (eightWay) { + int v = Input.vertical(c.getInput()); + int hdir = Input.horizontal(c.getInput()); + if (v != 0) { + dy = v; + dx = hdir; + if (v > 0 && b.isGrounded()) { + dy = 0; + dx = c.getFacing(); + } + } + } + int vx; + int vy; + if (dx != 0 && dy != 0) { + int diag = Fx.mul(speed, 46341); + vx = dx * diag; + vy = dy * diag; + } else { + vx = dx * speed; + vy = dy * speed; + } + int px; + int py = b.y + b.h / 2 - size / 2; + if (speed == 0) { + px = dx >= 0 ? b.x + b.w : b.x - size; + py = b.y + (b.h - size) / 2; + } else { + px = b.x + b.w / 2 - size / 2 + dx * (b.w / 2); + } + shots++; + Projectile p = new Projectile(c.getId() + "#" + shots, projectileType, px, py, size, vx, vy, + gravity, c.getTeam(), damage, lifeTicks); + world.addEntity(p); + world.emit(WorldEvent.FIRE, px, py, c.getId(), projectileType); + } + + @Override + public long hashState(long h) { + return mix(mix(mix(h, cooldown), ammo), shots); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/WorldEvent.java b/CodenameOne/src/com/codename1/gaming/platformer/WorldEvent.java new file mode 100644 index 00000000000..813e5aa1571 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/WorldEvent.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer; + +/// Something that happened in a tick that a view should show or play: a jump, a +/// coin, a hit. The simulation never calls into a view; it records events, and the +/// view reads `PlatformWorld#getEvents()` after each step to trigger sounds, +/// particles and screen shake. +@com.codename1.impl.SharedWithBackend +public final class WorldEvent { + /// An actor jumped. + public static final int JUMP = 1; + /// An actor landed. + public static final int LAND = 2; + /// A pickup was collected; `detail` is its kind name. + public static final int PICKUP = 3; + /// An actor was hurt. + public static final int HURT = 4; + /// An actor died. + public static final int DEATH = 5; + /// The player stomped an enemy. + public static final int STOMP = 6; + /// A weapon fired. + public static final int FIRE = 7; + /// A projectile hit something. + public static final int IMPACT = 8; + /// A checkpoint was reached. + public static final int CHECKPOINT = 9; + /// A spring launched an actor. + public static final int BOUNCE = 10; + /// A door opened or a gate changed. + public static final int OPEN = 11; + /// A block crumbled. + public static final int CRUMBLE = 12; + /// An actor dashed. + public static final int DASH = 13; + /// The level was completed. + public static final int COMPLETE = 14; + /// The player ran out of lives. + public static final int GAME_OVER = 15; + /// A switch was activated. + public static final int SWITCH = 16; + + private final int type; + private final int x; + private final int y; + private final String subject; + private final String detail; + + /// Creates an event. + /// + /// #### Parameters + /// + /// - `type`: one of the constants + /// - `x`: where, fixed point + /// - `y`: where, fixed point + /// - `subject`: the id of the actor or entity involved, may be null + /// - `detail`: extra information such as a pickup kind, may be null + public WorldEvent(int type, int x, int y, String subject, String detail) { + this.type = type; + this.x = x; + this.y = y; + this.subject = subject; + this.detail = detail; + } + + /// The event type. + /// + /// #### Returns + /// + /// one of the constants + public int getType() { + return type; + } + + /// Where it happened. + /// + /// #### Returns + /// + /// x, fixed point + public int getX() { + return x; + } + + /// Where it happened. + /// + /// #### Returns + /// + /// y, fixed point + public int getY() { + return y; + } + + /// The id of the actor or entity involved. + /// + /// #### Returns + /// + /// the id, or null + public String getSubject() { + return subject; + } + + /// Extra information. + /// + /// #### Returns + /// + /// the detail, or null + public String getDetail() { + return detail; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/package-info.java b/CodenameOne/src/com/codename1/gaming/platformer/package-info.java new file mode 100644 index 00000000000..532bb130345 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/package-info.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +/// A deterministic 2D platformer engine: the character controller, abilities and +/// level model behind the Ledge template, in the spirit of Unity's Corgi Engine. +/// +/// The simulation is integer only (`Fx` fixed point, 60 ticks a second) and shared +/// with the backend, so a run recorded as an `InputLog` replays identically on the +/// server (`Replay`) -- leaderboards, ghosts and speedruns can be verified rather +/// than trusted. +/// +/// - `TileGrid` and `Tile`: the collision map, written as rows of characters. +/// - `Body`: a kinematic box with slopes, one-way platforms, steps and riding. +/// - `MovingPlatform`: waypoint platforms that carry riders. +/// - `Actor` and `Ability`: a body driven by an ordered list of abilities -- +/// `MoveAbility`, `JumpAbility` (coyote time, buffering, variable height, +/// multi-jump, drop-through), `CrouchAbility`, `LadderAbility`, +/// `WallJumpAbility` and `DashAbility`. +/// - `PlatformWorld`: steps everything one tick from `Input` bits. +/// - `LevelData` and `LevelJson`: the JSON level format. +/// - `InputLog` and `Replay`: recording and verifying runs. +package com.codename1.gaming.platformer; diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/ActorAnimator.java b/CodenameOne/src/com/codename1/gaming/platformer/view/ActorAnimator.java new file mode 100644 index 00000000000..0440f229cad --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/ActorAnimator.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.platformer.MovementState; + +/// Chooses an `Actor`'s animation frame from its `MovementState`: the +/// presentation half of Corgi Engine's animator parameters. +/// +/// Each state maps to a `Clip` of frame indices in a sprite sheet. A state with +/// no clip of its own borrows a related one -- running falls back to walking, +/// crawling to crouching, every airborne state to jumping or falling, and in the +/// end everything to idle -- so a character drawn with only idle, walk and jump +/// frames still animates sensibly. One animator can serve every actor of a kind; +/// the per-actor progress lives in a `Track`. +public class ActorAnimator { + private final Clip[] clips = new Clip[MovementState.values().length]; + + /// A run of frames. + public static final class Clip { + final int[] frames; + final int ticksPerFrame; + final boolean loop; + + /// Creates a clip. + /// + /// #### Parameters + /// + /// - `frames`: frame indices into the sheet, at least one + /// - `ticksPerFrame`: world ticks (1/60 s) each frame shows + /// - `loop`: whether it repeats; otherwise it holds the last frame + public Clip(int[] frames, int ticksPerFrame, boolean loop) { + if (frames.length == 0) { + throw new IllegalArgumentException("A clip needs a frame"); + } + this.frames = new int[frames.length]; + System.arraycopy(frames, 0, this.frames, 0, frames.length); + this.ticksPerFrame = Math.max(1, ticksPerFrame); + this.loop = loop; + } + + /// The frame shown a number of ticks into the clip. + /// + /// #### Parameters + /// + /// - `ticks`: ticks since the clip started + /// + /// #### Returns + /// + /// a sheet frame index + public int frameAt(int ticks) { + int i = Math.max(0, ticks) / ticksPerFrame; + i = loop ? i % frames.length : Math.min(i, frames.length - 1); + return frames[i]; + } + } + + /// One actor's place in its animation. + public static final class Track { + private MovementState state; + private int ticks; + + /// Advances one world tick. + /// + /// #### Parameters + /// + /// - `s`: the actor's state this tick + public void tick(MovementState s) { + if (s != state) { + state = s; + ticks = 0; + } else { + ticks++; + } + } + + /// The state being shown. + /// + /// #### Returns + /// + /// the state, null before the first tick + public MovementState getState() { + return state; + } + + /// Ticks spent in the state. + /// + /// #### Returns + /// + /// the tick count + public int getTicks() { + return ticks; + } + } + + /// Sets a state's clip. + /// + /// #### Parameters + /// + /// - `state`: the state + /// - `clip`: its clip, or null to borrow a related one + /// + /// #### Returns + /// + /// this animator + public ActorAnimator set(MovementState state, Clip clip) { + clips[state.ordinal()] = clip; + return this; + } + + /// Sets a state's clip from frames. + /// + /// #### Parameters + /// + /// - `state`: the state + /// - `ticksPerFrame`: ticks each frame shows + /// - `loop`: whether it repeats + /// - `frames`: the sheet frame indices + /// + /// #### Returns + /// + /// this animator + public ActorAnimator set(MovementState state, int ticksPerFrame, boolean loop, int... frames) { + return set(state, new Clip(frames, ticksPerFrame, loop)); + } + + /// The clip a state shows, borrowed if it has none. + /// + /// #### Parameters + /// + /// - `state`: the state + /// + /// #### Returns + /// + /// the clip, or null if not even idle has one + public Clip clipFor(MovementState state) { + MovementState s = state; + for (int guard = 0; s != null && guard < 6; guard++) { + Clip c = clips[s.ordinal()]; + if (c != null) { + return c; + } + s = fallback(s); + } + return clips[MovementState.IDLE.ordinal()]; + } + + /// The frame for a track. + /// + /// #### Parameters + /// + /// - `track`: the actor's track + /// + /// #### Returns + /// + /// the sheet frame index, 0 if nothing is set + public int frameFor(Track track) { + Clip c = clipFor(track.state == null ? MovementState.IDLE : track.state); + return c == null ? 0 : c.frameAt(track.ticks); + } + + static MovementState fallback(MovementState s) { + // An if chain rather than an enum switch, which would compile to a + // synthetic lookup class per caller. + if (s == MovementState.RUNNING || s == MovementState.PUSHING) { + return MovementState.WALKING; + } + if (s == MovementState.CRAWLING) { + return MovementState.CROUCHING; + } + if (s == MovementState.FALLING || s == MovementState.GLIDING || s == MovementState.JETPACKING + || s == MovementState.DASHING) { + return MovementState.JUMPING; + } + if (s == MovementState.WALL_CLINGING || s == MovementState.GRIPPING) { + return MovementState.CLIMBING; + } + if (s == MovementState.CLIMBING || s == MovementState.SWIMMING || s == MovementState.HURT + || s == MovementState.DEAD) { + return MovementState.FALLING; + } + return s == MovementState.IDLE ? null : MovementState.IDLE; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/Feedback.java b/CodenameOne/src/com/codename1/gaming/platformer/view/Feedback.java new file mode 100644 index 00000000000..df0f8d06abd --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/Feedback.java @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.platformer.WorldEvent; + +/// "Juice": what the player sees and hears when something happens, chosen per +/// `WorldEvent` type -- the role of Corgi Engine's MMFeedbacks. +/// +/// A `Reaction` bundles a camera shake, a screen flash, a sound name and a +/// particle burst. `PlatformView` runs every event of every tick through +/// `#react`, which shakes its `PlatformCamera` and hands the sound and the burst +/// to a `Sink` the game supplies (a `com.codename1.gaming.SoundPool`, a +/// `com.codename1.gaming.ParticleEmitter`, a haptic tap). The defaults make a +/// level feel alive before any tuning: landings thud, stomps pop, hits shake. +public class Feedback { + private final Reaction[] reactions = new Reaction[32]; + private int flashColor; + private double flashTime; + private double flashDuration; + private double intensity = 1; + + /// Receives what a reaction plays. + public interface Sink { + /// Plays a named sound. + /// + /// #### Parameters + /// + /// - `name`: the reaction's sound name + /// - `x`: where in the world, pixels + /// - `y`: where in the world, pixels + void sound(String name, double x, double y); + + /// Bursts particles. + /// + /// #### Parameters + /// + /// - `x`: where in the world, pixels + /// - `y`: where in the world, pixels + /// - `count`: how many + /// - `color`: ARGB + void burst(double x, double y, int count, int color); + } + + /// What one kind of event does. + public static final class Reaction { + double shake; + double shakeSeconds; + int flash; + double flashSeconds; + String sound; + int particles; + int particleColor = 0xffffffff; + boolean playerOnly; + + /// Shakes the camera. + /// + /// #### Parameters + /// + /// - `pixels`: the amplitude + /// - `seconds`: the duration + /// + /// #### Returns + /// + /// this reaction + public Reaction shake(double pixels, double seconds) { + shake = pixels; + shakeSeconds = seconds; + return this; + } + + /// Flashes the screen. + /// + /// #### Parameters + /// + /// - `argb`: the color; its alpha is the strongest opacity + /// - `seconds`: the fade time + /// + /// #### Returns + /// + /// this reaction + public Reaction flash(int argb, double seconds) { + flash = argb; + flashSeconds = seconds; + return this; + } + + /// Plays a sound. + /// + /// #### Parameters + /// + /// - `name`: passed to the `Sink` + /// + /// #### Returns + /// + /// this reaction + public Reaction sound(String name) { + sound = name; + return this; + } + + /// Bursts particles. + /// + /// #### Parameters + /// + /// - `count`: how many + /// - `argb`: their color + /// + /// #### Returns + /// + /// this reaction + public Reaction particles(int count, int argb) { + particles = count; + particleColor = argb; + return this; + } + + /// Limits the shake and flash to events about the player, so an enemy + /// landing off screen does not rattle the camera. + /// + /// #### Returns + /// + /// this reaction + public Reaction playerOnly() { + playerOnly = true; + return this; + } + } + + /// Creates feedback with the stock reactions. + public Feedback() { + on(WorldEvent.JUMP).sound("jump").particles(4, 0xffd8d0c0).playerOnly(); + on(WorldEvent.LAND).sound("land").particles(6, 0xffd8d0c0).playerOnly(); + on(WorldEvent.PICKUP).sound("pickup").particles(8, 0xffffd34d); + on(WorldEvent.HURT).sound("hurt").shake(5, 0.25).flash(0x66ff2020, 0.2).playerOnly(); + on(WorldEvent.DEATH).sound("death").shake(8, 0.4).particles(18, 0xffff5050); + on(WorldEvent.STOMP).sound("stomp").shake(3, 0.12).particles(10, 0xffffffff); + on(WorldEvent.FIRE).sound("fire"); + on(WorldEvent.IMPACT).sound("impact").particles(6, 0xffffe0a0); + on(WorldEvent.CHECKPOINT).sound("checkpoint").flash(0x44ffffff, 0.3).particles(14, 0xff7cf0a0); + on(WorldEvent.BOUNCE).sound("bounce").particles(6, 0xffffffff); + on(WorldEvent.OPEN).sound("open").shake(2, 0.15); + on(WorldEvent.CRUMBLE).sound("crumble").shake(2, 0.2).particles(10, 0xffa08060); + on(WorldEvent.DASH).sound("dash").particles(6, 0xff9fd8ff).playerOnly(); + on(WorldEvent.COMPLETE).sound("complete").flash(0x88ffffff, 0.6).particles(30, 0xffffd34d); + on(WorldEvent.GAME_OVER).sound("gameover").flash(0xaa000000, 1.2); + on(WorldEvent.SWITCH).sound("switch").shake(1, 0.1); + } + + /// The reaction to an event type, created empty if it had none. + /// + /// #### Parameters + /// + /// - `eventType`: a `WorldEvent` constant + /// + /// #### Returns + /// + /// the reaction to configure + public final Reaction on(int eventType) { + int i = eventType & 31; + if (reactions[i] == null) { + reactions[i] = new Reaction(); + } + return reactions[i]; + } + + /// Removes the reaction to an event type. + /// + /// #### Parameters + /// + /// - `eventType`: a `WorldEvent` constant + public void off(int eventType) { + reactions[eventType & 31] = null; + } + + /// Scales every shake and flash, for an accessibility "reduce motion" setting. + /// + /// #### Parameters + /// + /// - `intensity`: 0 for none, 1 for full + public void setIntensity(double intensity) { + this.intensity = Math.max(0, intensity); + } + + /// How strong shakes, flashes and particle bursts are. + /// + /// #### Returns + /// + /// 0 for none, 1 for full + public double getIntensity() { + return intensity; + } + + /// Plays an event. + /// + /// #### Parameters + /// + /// - `e`: the event + /// - `aboutPlayer`: whether the player is its subject + /// - `camera`: shaken, may be null + /// - `sink`: receives sounds and particles, may be null + public void react(WorldEvent e, boolean aboutPlayer, PlatformCamera camera, Sink sink) { + Reaction r = reactions[e.getType() & 31]; + if (r == null) { + return; + } + double x = e.getX() / 65536.0; + double y = e.getY() / 65536.0; + if (sink != null) { + if (r.sound != null) { + sink.sound(r.sound, x, y); + } + if (r.particles > 0) { + sink.burst(x, y, r.particles, r.particleColor); + } + } + if (r.playerOnly && !aboutPlayer) { + return; + } + if (camera != null && r.shake > 0 && intensity > 0) { + camera.shake(r.shake * intensity, r.shakeSeconds); + } + if (r.flashSeconds > 0 && intensity > 0) { + flashColor = r.flash; + flashDuration = r.flashSeconds; + flashTime = r.flashSeconds; + } + } + + /// Fades the flash. + /// + /// #### Parameters + /// + /// - `seconds`: time since the last frame + public void update(double seconds) { + flashTime = Math.max(0, flashTime - seconds); + } + + /// The flash color with its current opacity, 0 when none is showing. + /// + /// #### Returns + /// + /// ARGB + public int getFlash() { + if (flashTime <= 0 || flashDuration <= 0) { + return 0; + } + int a = (int) (((flashColor >>> 24) & 0xff) * (flashTime / flashDuration) * Math.min(1, intensity)); + return (a << 24) | (flashColor & 0xffffff); + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/InputMapper.java b/CodenameOne/src/com/codename1/gaming/platformer/view/InputMapper.java new file mode 100644 index 00000000000..c9bc2ff3018 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/InputMapper.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.GameInput; +import com.codename1.gaming.Gamepad; +import com.codename1.gaming.platformer.Input; +import com.codename1.ui.Display; + +/// Reads the keyboard, a gamepad and the on-screen controls of a +/// `com.codename1.gaming.GameInput` into the `Input` bits a `PlatformWorld` steps +/// with. Keyboard: arrows or WASD move, space/K jump, R run, Z/J dash, X/L +/// fire, E activate, C alternate (jetpack, glide). Gamepad: stick or d-pad move, +/// A jump, B dash, X fire, Y activate, right shoulder run, left shoulder +/// alternate. On-screen buttons send the key codes above. +/// +/// Subclass it or set other key codes to remap; the world only ever sees bits, +/// so a replay is the same whichever device produced it. +public class InputMapper { + private int[] jumpKeys = {' ', 'k', 'K'}; + private int[] runKeys = {'r', 'R'}; + private int[] dashKeys = {'z', 'Z', 'j', 'J'}; + private int[] fireKeys = {'x', 'X', 'l', 'L'}; + private int[] activateKeys = {'e', 'E'}; + private int[] altKeys = {'c', 'C'}; + private float stickDeadZone = 0.35f; + private boolean alwaysRun; + + /// The keys that jump. On-screen buttons should send the first. + /// + /// #### Parameters + /// + /// - `keys`: key codes + public void setJumpKeys(int... keys) { + jumpKeys = copy(keys); + } + + /// The keys that fire. + /// + /// #### Parameters + /// + /// - `keys`: key codes + public void setFireKeys(int... keys) { + fireKeys = copy(keys); + } + + /// The keys that dash. + /// + /// #### Parameters + /// + /// - `keys`: key codes + public void setDashKeys(int... keys) { + dashKeys = copy(keys); + } + + /// Runs without holding a key, as touch players expect. + /// + /// #### Parameters + /// + /// - `alwaysRun`: true to always run + public void setAlwaysRun(boolean alwaysRun) { + this.alwaysRun = alwaysRun; + } + + /// The key code an on-screen jump button should send. + /// + /// #### Returns + /// + /// a key code + public int getJumpKey() { + return jumpKeys.length == 0 ? ' ' : jumpKeys[0]; + } + + /// The key code an on-screen fire button should send. + /// + /// #### Returns + /// + /// a key code + public int getFireKey() { + return fireKeys.length == 0 ? 'x' : fireKeys[0]; + } + + /// The key code an on-screen dash button should send. + /// + /// #### Returns + /// + /// a key code + public int getDashKey() { + return dashKeys.length == 0 ? 'z' : dashKeys[0]; + } + + private static int[] copy(int[] a) { + int[] c = new int[a.length]; + System.arraycopy(a, 0, c, 0, a.length); + return c; + } + + /// Reads the current input. + /// + /// #### Parameters + /// + /// - `in`: the view's input state + /// + /// #### Returns + /// + /// `Input` bits + public int read(GameInput in) { + int bits = 0; + float ax = in.getAxisX(); + float ay = in.getAxisY(); + if (in.isGameKeyDown(Display.GAME_LEFT) || any(in, 'a', 'A') || ax < -stickDeadZone + || in.isGamepadButtonDown(Gamepad.BUTTON_DPAD_LEFT)) { + bits |= Input.LEFT; + } + if (in.isGameKeyDown(Display.GAME_RIGHT) || any(in, 'd', 'D') || ax > stickDeadZone + || in.isGamepadButtonDown(Gamepad.BUTTON_DPAD_RIGHT)) { + bits |= Input.RIGHT; + } + if (in.isGameKeyDown(Display.GAME_UP) || any(in, 'w', 'W') || ay < -stickDeadZone + || in.isGamepadButtonDown(Gamepad.BUTTON_DPAD_UP)) { + bits |= Input.UP; + } + if (in.isGameKeyDown(Display.GAME_DOWN) || any(in, 's', 'S') || ay > stickDeadZone + || in.isGamepadButtonDown(Gamepad.BUTTON_DPAD_DOWN)) { + bits |= Input.DOWN; + } + if (any(in, jumpKeys) || in.isGamepadButtonDown(Gamepad.BUTTON_A)) { + bits |= Input.JUMP; + } + if (alwaysRun || any(in, runKeys) || in.isGamepadButtonDown(Gamepad.BUTTON_RIGHT_SHOULDER)) { + bits |= Input.RUN; + } + if (any(in, dashKeys) || in.isGamepadButtonDown(Gamepad.BUTTON_B)) { + bits |= Input.DASH; + } + if (any(in, fireKeys) || in.isGameKeyDown(Display.GAME_FIRE) || in.isGamepadButtonDown(Gamepad.BUTTON_X)) { + bits |= Input.FIRE; + } + if (any(in, activateKeys) || in.isGamepadButtonDown(Gamepad.BUTTON_Y)) { + bits |= Input.ACTIVATE; + } + if (any(in, altKeys) || in.isGamepadButtonDown(Gamepad.BUTTON_LEFT_SHOULDER)) { + bits |= Input.ALT; + } + return bits; + } + + private static boolean any(GameInput in, int... keys) { + for (int i = 0; i < keys.length; i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + if (in.isKeyDown(keys[i])) { + return true; + } + } + return false; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformArt.java b/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformArt.java new file mode 100644 index 00000000000..09eda504f6a --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformArt.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.SpriteSheet; +import com.codename1.gaming.platformer.Actor; +import com.codename1.gaming.platformer.Entity; +import com.codename1.gaming.platformer.MovingPlatform; +import com.codename1.gaming.platformer.TileGrid; +import com.codename1.ui.Image; + +/// Supplies the images a `PlatformView` draws. The simulation never sees any of +/// it, so art can change -- a skin, a seasonal theme, a 2.5D model set -- +/// without changing how a level plays or what a replay hashes to. +/// +/// `ProceduralArt` implements every method with generated shapes, so a level is +/// playable before any art exists; extend it and override what you have art for. +public interface PlatformArt { + /// The image for one cell. Called when the view first draws a cell and again + /// whenever the cell changes (a door opening, a block crumbling). + /// + /// #### Parameters + /// + /// - `grid`: the grid, to look at neighbors for auto-tiling + /// - `col`: the column + /// - `row`: the row + /// + /// #### Returns + /// + /// an image the size of a tile in pixels, or null to draw nothing + Image tile(TileGrid grid, int col, int row); + + /// The sprite sheet for an actor; frames are chosen by `#animator(Actor)`. + /// The frame is drawn centered on the body horizontally and standing on its + /// bottom edge, so a sheet may be larger than the body. + /// + /// #### Parameters + /// + /// - `actor`: the actor; `Actor#getKind()` names its art + /// + /// #### Returns + /// + /// the sheet + SpriteSheet sheet(Actor actor); + + /// The animator for an actor. + /// + /// #### Parameters + /// + /// - `actor`: the actor + /// + /// #### Returns + /// + /// the animator, typically shared by every actor of a kind + ActorAnimator animator(Actor actor); + + /// The image for an entity this tick. Called every tick, so return cached + /// images. + /// + /// #### Parameters + /// + /// - `entity`: the entity; `Entity#getType()` and `Entity#getPhase()` select + /// the image + /// - `tick`: the world tick, for animating + /// + /// #### Returns + /// + /// the image, drawn centered on the entity, or null to draw nothing + Image entity(Entity entity, int tick); + + /// The image for a moving platform. + /// + /// #### Parameters + /// + /// - `platform`: the platform + /// + /// #### Returns + /// + /// an image the platform's size in pixels + Image platform(MovingPlatform platform); + + /// The image for the level's goal this tick, drawn centered on the goal + /// rectangle (`PlatformWorld#getGoal()`). + /// + /// #### Parameters + /// + /// - `width`: the goal's width in pixels + /// - `height`: the goal's height in pixels + /// - `tick`: the world tick, for animating + /// + /// #### Returns + /// + /// the image, or null to draw nothing + Image goal(int width, int height, int tick); +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformCamera.java b/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformCamera.java new file mode 100644 index 00000000000..a92b77b9cb8 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformCamera.java @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +/// A side-scroller camera: follows a target through a dead zone, leads in the +/// direction it faces, eases toward where it wants to be, stays inside the level +/// and shakes on demand. +/// +/// It is pure arithmetic in pixels and knows nothing of the world or the +/// renderer, so it can be tested and reused: call `#update` once per rendered +/// frame with the target's center, then read `#getX()`/`#getY()`, the top-left +/// corner of the view in world pixels. +public class PlatformCamera { + private double x; + private double y; + private double viewWidth; + private double viewHeight; + private double minX; + private double minY; + private double maxX = Double.MAX_VALUE; + private double maxY = Double.MAX_VALUE; + private double deadZoneWidth = 0.15; + private double deadZoneHeight = 0.25; + private double lookAhead = 0.12; + private double smoothing = 8; + private double lead; + private double shakeAmplitude; + private double shakeTime; + private double shakeDuration; + private double offsetX; + private double offsetY; + private long shakeSeed = 0x2545F4914F6CDD1DL; + private boolean placed; + + /// Sets the size of the view in world pixels. + /// + /// #### Parameters + /// + /// - `width`: the width + /// - `height`: the height + public void setViewSize(double width, double height) { + this.viewWidth = width; + this.viewHeight = height; + } + + /// Keeps the view inside a rectangle, normally the level. + /// + /// #### Parameters + /// + /// - `left`: the left edge + /// - `top`: the top edge + /// - `right`: the right edge + /// - `bottom`: the bottom edge + public void setBounds(double left, double top, double right, double bottom) { + minX = left; + minY = top; + maxX = right; + maxY = bottom; + } + + /// Sets the dead zone, as fractions of the view, inside which the target moves + /// without moving the camera. + /// + /// #### Parameters + /// + /// - `width`: fraction of the view width + /// - `height`: fraction of the view height + public void setDeadZone(double width, double height) { + deadZoneWidth = width; + deadZoneHeight = height; + } + + /// How far ahead of the target the camera leads, as a fraction of the view + /// width. + /// + /// #### Parameters + /// + /// - `fraction`: 0 for none + public void setLookAhead(double fraction) { + lookAhead = fraction; + } + + /// How quickly the camera catches up; higher is snappier, 0 snaps at once. + /// + /// #### Parameters + /// + /// - `rate`: per second + public void setSmoothing(double rate) { + smoothing = rate; + } + + /// Starts a shake that fades out. + /// + /// #### Parameters + /// + /// - `amplitude`: the strongest offset in pixels + /// - `seconds`: how long it lasts + public void shake(double amplitude, double seconds) { + if (amplitude >= shakeAmplitude * remainingShake()) { + shakeAmplitude = amplitude; + shakeDuration = seconds; + shakeTime = seconds; + } + } + + private double remainingShake() { + return shakeDuration <= 0 ? 0 : shakeTime / shakeDuration; + } + + /// Jumps straight to a target, as at the start of a level or after a respawn. + /// + /// #### Parameters + /// + /// - `targetX`: the target's center + /// - `targetY`: the target's center + public void snapTo(double targetX, double targetY) { + x = targetX - viewWidth / 2; + y = targetY - viewHeight / 2; + lead = 0; + clamp(); + placed = true; + } + + /// Moves the camera for one frame. + /// + /// #### Parameters + /// + /// - `targetX`: the target's center + /// - `targetY`: the target's center + /// - `facing`: 1 right, -1 left + /// - `seconds`: time since the last frame + public void update(double targetX, double targetY, int facing, double seconds) { + if (!placed) { + snapTo(targetX, targetY); + } + double wantLead = facing * lookAhead * viewWidth; + double k = smoothing <= 0 ? 1 : Math.min(1, smoothing * seconds); + lead += (wantLead - lead) * k * 0.5; + double cx = x + viewWidth / 2 - lead; + double cy = y + viewHeight / 2; + double hw = deadZoneWidth * viewWidth / 2; + double hh = deadZoneHeight * viewHeight / 2; + double wantX = x; + double wantY = y; + if (targetX > cx + hw) { + wantX += targetX - (cx + hw); + } else if (targetX < cx - hw) { + wantX += targetX - (cx - hw); + } + if (targetY > cy + hh) { + wantY += targetY - (cy + hh); + } else if (targetY < cy - hh) { + wantY += targetY - (cy - hh); + } + x += (wantX - x) * k; + y += (wantY - y) * k; + clamp(); + offsetX = 0; + offsetY = 0; + if (shakeTime > 0) { + shakeTime = Math.max(0, shakeTime - seconds); + double a = shakeAmplitude * remainingShake(); + offsetX = (nextUnit() * 2 - 1) * a; + offsetY = (nextUnit() * 2 - 1) * a; + } + } + + private double nextUnit() { + shakeSeed ^= shakeSeed << 13; + shakeSeed ^= shakeSeed >>> 7; + shakeSeed ^= shakeSeed << 17; + return ((shakeSeed >>> 11) & 0xfffff) / (double) 0x100000; + } + + private void clamp() { + double right = maxX - viewWidth; + double bottom = maxY - viewHeight; + x = right < minX ? (minX + maxX - viewWidth) / 2 : Math.max(minX, Math.min(right, x)); + y = bottom < minY ? (minY + maxY - viewHeight) / 2 : Math.max(minY, Math.min(bottom, y)); + } + + /// The left edge of the view, shake included. + /// + /// #### Returns + /// + /// world pixels + public double getX() { + return x + offsetX; + } + + /// The top edge of the view, shake included. + /// + /// #### Returns + /// + /// world pixels + public double getY() { + return y + offsetY; + } + + /// The view width. + /// + /// #### Returns + /// + /// world pixels + public double getViewWidth() { + return viewWidth; + } + + /// The view height. + /// + /// #### Returns + /// + /// world pixels + public double getViewHeight() { + return viewHeight; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformView.java b/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformView.java new file mode 100644 index 00000000000..0188da8838e --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/PlatformView.java @@ -0,0 +1,1053 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.GameView; +import com.codename1.gaming.Model; +import com.codename1.gaming.Sprite; +import com.codename1.gaming.SpriteSheet; +import com.codename1.gaming.platformer.Actor; +import com.codename1.gaming.platformer.Body; +import com.codename1.gaming.platformer.Entity; +import com.codename1.gaming.platformer.MovingPlatform; +import com.codename1.gaming.platformer.PlatformWorld; +import com.codename1.gaming.platformer.Tile; +import com.codename1.gaming.platformer.TileGrid; +import com.codename1.gaming.platformer.WorldEvent; +import com.codename1.gpu.GraphicsDevice; +import com.codename1.gpu.Material; +import com.codename1.gpu.Mesh; +import com.codename1.gpu.Primitives; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/// Plays a `PlatformWorld` on screen: steps it at a fixed 60 Hz from the player's +/// input, draws it through a `PlatformArt`, follows the player with a +/// `PlatformCamera` and plays each tick's events through `Feedback`. +/// +/// ```java +/// LevelData level = LevelData.parse(json); +/// PlatformWorld world = level.createWorld(seed); +/// PlatformView view = new PlatformView(world, new ProceduralArt(level.getTileSize())); +/// form.add(BorderLayout.CENTER, view); +/// form.show(); +/// view.start(); +/// ``` +/// +/// Drawing is interpolated between the last two ticks, so motion is smooth at +/// any display rate while the simulation stays exactly 60 Hz. Tiles are baked +/// into chunk images once and re-baked only where the grid changes. Positions +/// are in world pixels multiplied by a scale chosen so `#setVisibleRows` rows of +/// tiles fill the height of the view. +/// +/// `#setDepth(boolean)` turns on 2.5D: the same world, the same rules and the +/// same replay, drawn with a perspective camera. Solid ground becomes extruded +/// blocks and actors, entities and backdrops become billboards at depth, so +/// backdrops get real parallax. The simulation cannot tell the difference. +/// +/// Override `#onEvent` for game rules the view should react to (a HUD, a +/// win screen), or set an `InputSource` to drive the world from a replay or a +/// network peer instead of the local player. +public class PlatformView extends GameView { + private static final int CHUNK = 16; + private static final int Z_BACK = -100; + private static final int Z_TILES = 0; + private static final int Z_PLATFORMS = 5; + private static final int Z_ENTITIES = 10; + private static final int Z_ACTORS = 20; + private static final int Z_PARTICLES = 30; + private static final int Z_FLASH = 1000; + private static final int MAX_PARTICLES = 160; + + private PlatformWorld world; + private PlatformArt art; + private final PlatformCamera camera = new PlatformCamera(); + private Feedback feedback = new Feedback(); + private InputMapper mapper = new InputMapper(); + private InputSource source; + private Feedback.Sink sink; + private final Feedback.Sink ownSink = new Feedback.Sink() { + @Override + public void sound(String name, double x, double y) { + if (sink != null) { + sink.sound(name, x, y); + } + } + + @Override + public void burst(double x, double y, int count, int color) { + spawnParticles(x, y, count, color); + if (sink != null) { + sink.burst(x, y, count, color); + } + } + }; + private final List particles = new ArrayList(); + private final java.util.Random particleRandom = new java.util.Random(7); + private Image particleImage; + + /// A spark of a feedback burst: view state only, never part of the world. + private static final class Particle { + Sprite sprite; + double x; + double y; + double vx; + double vy; + double life; + double max; + double size; + } + private double visibleRows = 12; + private double artScale = 1; + private double scale = 1; + private final Map shown = new HashMap(); + private final List gone = new ArrayList(); + private Sprite[] chunks = new Sprite[0]; + private boolean[] dirty = new boolean[0]; + private byte[] cells = new byte[0]; + private int chunkCols; + private Sprite flash; + private final List backgrounds = new ArrayList(); + private int lastBits; + private boolean depth; + private GraphicsDevice device; + private final Model[] blocks = new Model[4]; + private final int[] blockColors = {0xff5b4b8a, 0xff8a6a4a, 0xffd8dde8, 0xffb08850}; + private final Image[] blockImages = new Image[4]; + private boolean blocksDirty = true; + private float fov = 40f; + private float depthTilt = 0.18f; + private float blockDepth = 1.6f; + + /// Supplies the player's input instead of the device, for a replay or a + /// remote player. + public interface InputSource { + /// The input for the next tick. + /// + /// #### Parameters + /// + /// - `world`: the world about to step + /// - `local`: what the local devices read this tick + /// + /// #### Returns + /// + /// `com.codename1.gaming.platformer.Input` bits per actor, in the + /// order they were added; actors with a brain ignore theirs + int[] next(PlatformWorld world, int local); + } + + private static final class Shown { + final Sprite sprite; + final ActorAnimator.Track track; + double prevX; + double prevY; + double x; + double y; + boolean seen; + + Shown(Sprite sprite, boolean actor) { + this.sprite = sprite; + this.track = actor ? new ActorAnimator.Track() : null; + } + } + + /// Creates a view. + /// + /// #### Parameters + /// + /// - `world`: the world to play + /// - `art`: draws it + public PlatformView(PlatformWorld world, PlatformArt art) { + setFixedTimestep(1.0 / PlatformWorld.TICKS_PER_SECOND); + Image white = Image.createImage(1, 1, 0xffffffff); + flash = new Sprite(white); + flash.setAnchor(0, 0); + flash.setParallax(0, 0); + flash.setZOrder(Z_FLASH); + flash.setVisible(false); + getScene().add(flash); + setWorld(world, art); + } + + /// Replaces the world, as when the next level starts or a level restarts. + /// + /// #### Parameters + /// + /// - `world`: the new world + /// - `art`: draws it + public final void setWorld(PlatformWorld world, PlatformArt art) { + for (Shown s : shown.values()) { + getScene().remove(s.sprite); + } + shown.clear(); + for (int i = 0; i < chunks.length; i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + if (chunks[i] != null) { + getScene().remove(chunks[i]); + releaseTexture(chunks[i].getImage()); + } + } + this.world = world; + this.art = art; + TileGrid g = world.getGrid(); + chunkCols = (g.getCols() + CHUNK - 1) / CHUNK; + int chunkRows = (g.getRows() + CHUNK - 1) / CHUNK; + chunks = new Sprite[chunkCols * chunkRows]; + dirty = new boolean[chunks.length]; + for (int i = 0; i < dirty.length; i++) { + dirty[i] = true; + } + cells = new byte[g.getCols() * g.getRows()]; + snapshotCells(false); + camera.setBounds(0, 0, g.getCols() * (g.getTileSize() >> 16), g.getRows() * (g.getTileSize() >> 16)); + blocksDirty = true; + syncSprites(true); + snapCamera(); + } + + /// Draws in 2.5D: a perspective camera over extruded blocks and billboard + /// sprites. Call before `#start()` or at any time after. + /// + /// #### Parameters + /// + /// - `depth`: true for 2.5D, false for flat 2D + public void setDepth(boolean depth) { + this.depth = depth; + if (depth) { + getCamera().setPerspective(fov, 0.1f, 600f); + } else { + getCamera().setOrthographic2D(); + } + blocksDirty = true; + for (int i = 0; i < chunks.length; i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + if (chunks[i] != null) { + chunks[i].setVisible(!depth); + } + } + } + + /// Whether the view draws in 2.5D. + /// + /// #### Returns + /// + /// true in 2.5D + public boolean isDepth() { + return depth; + } + + /// Tunes the 2.5D look. + /// + /// #### Parameters + /// + /// - `fovDegrees`: the vertical field of view, 40 by default + /// - `tilt`: how far above the action the camera sits, as a fraction of its + /// distance; 0.18 by default + /// - `blockDepth`: how deep solid ground extrudes, in tiles; 1.6 by default + public void setDepthLook(float fovDegrees, float tilt, float blockDepth) { + this.fov = fovDegrees; + this.depthTilt = tilt; + this.blockDepth = blockDepth; + blocksDirty = true; + if (depth) { + getCamera().setPerspective(fov, 0.1f, 600f); + } + } + + /// Textures the depth mode's blocks with tile art instead of flat colour. + /// Every face of a block shows the whole image, so a tile with grass + /// along its top reads as a grassy block from the front and the side. + /// Any argument may be null to keep that kind's colour. Call before the + /// view starts. + /// + /// #### Parameters + /// + /// - `solid`: solid ground and slopes + /// - `ledge`: one-way ledges + /// - `hazard`: spikes + /// - `ladder`: ladders + public void setDepthTextures(Image solid, Image ledge, Image hazard, Image ladder) { + blockImages[0] = solid; + blockImages[1] = ledge; + blockImages[2] = hazard; + blockImages[3] = ladder; + } + + /// The 2.5D block colors. + /// + /// #### Parameters + /// + /// - `solid`: ground and slopes + /// - `ledge`: one-way ledges + /// - `hazard`: spikes + /// - `ladder`: ladders + public void setDepthColors(int solid, int ledge, int hazard, int ladder) { + blockColors[0] = solid; + blockColors[1] = ledge; + blockColors[2] = hazard; + blockColors[3] = ladder; + for (int i = 0; i < blocks.length; i++) { + if (blocks[i] != null) { + blocks[i].getMaterial().setColor(blockColors[i]); + } + } + } + + @Override + protected void onSetup(GraphicsDevice device) { + super.onSetup(device); + this.device = device; + Mesh cube = Primitives.cube(device, 1f); + for (int i = 0; i < blocks.length; i++) { + Material mat = new Material(Material.Type.LAMBERT).setColor(blockColors[i]); + if (blockImages[i] != null) { + mat.setColor(0xffffffff).setTexture(device.createTexture(blockImages[i])); + } + blocks[i] = new Model(cube, mat); + blocks[i].setVisible(false); + addModel(blocks[i]); + } + blocksDirty = true; + } + + private void rebuildBlocks() { + blocksDirty = false; + if (device == null) { + return; + } + TileGrid g = world.getGrid(); + float[][] m = new float[4][]; + int[] n = new int[4]; + int cap = g.getCols() * g.getRows() * 4; + for (int i = 0; i < 4; i++) { + m[i] = new float[16 * Math.min(cap, 64)]; + } + for (int r = 0; r < g.getRows(); r++) { + for (int c = 0; c < g.getCols(); c++) { + int k = g.get(c, r); + if (k == Tile.SOLID) { + m[0] = box(m[0], n[0]++, c, r, 0, 0, 1, 1, blockDepth); + } else if (Tile.isSlope(k)) { + // A slope is a staircase of four columns sampled at their + // centers, close enough at play distance. + for (int s = 0; s < 4; s++) { + int fs = 4 << 16; + int top = Tile.slopeDepth(k, (s << 16) + (1 << 15), fs); + float t = top / 65536f / 4f; + m[0] = box(m[0], n[0]++, c, r, s / 4f, t, 0.25f, 1 - t, blockDepth); + } + } else if (k == Tile.ONE_WAY) { + m[1] = box(m[1], n[1]++, c, r, 0, 0, 1, 0.22f, blockDepth * 0.8f); + } else if (k == Tile.HAZARD) { + for (int s = 0; s < 3; s++) { + m[2] = box(m[2], n[2]++, c, r, s / 3f + 0.08f, 0.55f, 0.18f, 0.45f, blockDepth * 0.6f); + } + } else if (k == Tile.LADDER) { + m[3] = box(m[3], n[3]++, c, r, 0.18f, 0, 0.1f, 1, 0.1f); + m[3] = box(m[3], n[3]++, c, r, 0.72f, 0, 0.1f, 1, 0.1f); + m[3] = box(m[3], n[3]++, c, r, 0.18f, 0.45f, 0.64f, 0.08f, 0.1f); + } + } + } + for (int i = 0; i < 4; i++) { + blocks[i].setInstances(m[i], null, n[i]); + blocks[i].setVisible(depth && n[i] > 0); + } + } + + /// Writes the transform of a box in tile units: cell (c, r), offset (ox, oy) + /// from its top-left, size w x h, extruded `d` into the screen. World y is up. + private static float[] box(float[] m, int index, int c, int r, float ox, float oy, float w, float h, float d) { + float[] out = m; + if ((index + 1) * 16 > out.length) { + out = new float[out.length * 2]; + System.arraycopy(m, 0, out, 0, m.length); + } + int o = index * 16; + for (int i = 0; i < 16; i++) { + out[o + i] = 0; + } + out[o] = w; + out[o + 5] = h; + out[o + 10] = d; + out[o + 12] = c + ox + w / 2; + out[o + 13] = -(r + oy + h / 2); + out[o + 14] = -d / 2 + 0.5f; + out[o + 15] = 1; + return out; + } + + /// Adds a parallax backdrop behind the level, repeated across the view. + /// + /// #### Parameters + /// + /// - `image`: the layer + /// - `factor`: how much it scrolls with the world; 0 pinned, 1 with the level + /// - `y`: its top in world pixels + public void addBackground(Image image, float factor, double y) { + TileGrid g = world.getGrid(); + double worldW = g.getCols() * (g.getTileSize() >> 16); + // Copies to cross the whole level, in world pixels: the image is + // `artScale` art pixels to one of those, and dividing by its art + // width left a far layer a quarter of the copies it needed, ending + // mid-screen. The level's width, not `factor` of it, also covers a + // view wider than the distance a slow layer travels. + double imageW = image.getWidth() / artScale; + int copies = (int) Math.ceil(worldW / imageW) + 2; + // One copy starts left of the level: in depth the layer is laid out + // about the camera's centre, so at the level's left edge it reaches + // further left than the first copy. + for (int i = -1; i < copies; i++) { + Sprite s = new Sprite(image); + s.setAnchor(0, 0); + s.setParallax(factor, factor); + s.setZOrder(Z_BACK + backgrounds.size()); + s.setUserData(new double[] {i * image.getWidth() / artScale, y}); + backgrounds.add(s); + getScene().add(s); + } + } + + /// How many art pixels the `PlatformArt` draws per world pixel. A level with + /// 16 pixel tiles and art drawn at 64 pixels a tile uses 4: tiles, sprites + /// and backdrops are then drawn at their full resolution instead of being + /// scaled up from the level's own pixel size. Call before `#start()`. + /// + /// #### Parameters + /// + /// - `scale`: art pixels per world pixel, 1 by default + public void setArtScale(double scale) { + this.artScale = Math.max(0.25, scale); + for (int i = 0; i < dirty.length; i++) { + dirty[i] = true; + } + } + + /// Art pixels per world pixel. + /// + /// #### Returns + /// + /// the art scale + public double getArtScale() { + return artScale; + } + + /// How many rows of tiles fill the view's height; sets the scale. + /// + /// #### Parameters + /// + /// - `rows`: rows, 12 by default + public void setVisibleRows(double rows) { + visibleRows = Math.max(2, rows); + } + + /// The camera, to tune its dead zone, look-ahead and smoothing. + /// + /// #### Returns + /// + /// the camera + public PlatformCamera getPlatformCamera() { + return camera; + } + + /// The feedback, to change what events look and sound like. + /// + /// #### Returns + /// + /// the feedback + public Feedback getFeedback() { + return feedback; + } + + /// Replaces the feedback. + /// + /// #### Parameters + /// + /// - `feedback`: the feedback + public void setFeedback(Feedback feedback) { + this.feedback = feedback; + } + + /// Receives the sounds and particle bursts of the feedback. + /// + /// #### Parameters + /// + /// - `sink`: the sink, may be null + public void setFeedbackSink(Feedback.Sink sink) { + this.sink = sink; + } + + /// The input mapper, to remap keys. + /// + /// #### Returns + /// + /// the mapper + public InputMapper getInputMapper() { + return mapper; + } + + /// Replaces the input mapper. + /// + /// #### Parameters + /// + /// - `mapper`: the mapper + public void setInputMapper(InputMapper mapper) { + this.mapper = mapper; + } + + /// Drives the world from somewhere other than the local devices. + /// + /// #### Parameters + /// + /// - `source`: the source, or null for the local player + public void setInputSource(InputSource source) { + this.source = source; + } + + /// The world being played. + /// + /// #### Returns + /// + /// the world + public PlatformWorld getWorld() { + return world; + } + + /// The art the view draws with. + /// + /// #### Returns + /// + /// the art + public PlatformArt getArt() { + return art; + } + + /// The `Input` bits the local devices produced on the last tick, for a + /// recorder. + /// + /// #### Returns + /// + /// the bits + public int getLastInput() { + return lastBits; + } + + @Override + protected void update(double deltaSeconds) { + if (world.isComplete() || world.isGameOver()) { + return; + } + int local = mapper.read(getInput()); + lastBits = local; + for (Shown s : shown.values()) { + s.prevX = s.x; + s.prevY = s.y; + } + if (source != null) { + world.step(source.next(world, local)); + } else { + world.step(local); + } + for (int i = 0; i < ghosts.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick + Ghost gh = ghosts.get(i); + if (!gh.world.isComplete() && !gh.world.isGameOver()) { + int t = gh.world.getTick(); + gh.world.step(t < gh.inputs.length ? gh.inputs[t] : 0); + } + } + onTick(local); + Actor player = world.getPlayer(); + List events = world.getEvents(); + for (int i = 0; i < events.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + WorldEvent e = events.get(i); + boolean aboutPlayer = player != null && player.getId().equals(e.getSubject()); + feedback.react(e, aboutPlayer, camera, ownSink); + if (e.getType() == WorldEvent.DEATH && aboutPlayer && player.isAlive()) { + // Respawned: jump the camera rather than pan across the level. + snapCamera(); + } + onEvent(e); + } + snapshotCells(true); + syncSprites(false); + } + + /// Called after every tick, before the events are played. + /// + /// #### Parameters + /// + /// - `localInput`: what the local devices read + protected void onTick(int localInput) { + } + + /// Called for every event of every tick, after its feedback played. + /// + /// #### Parameters + /// + /// - `e`: the event + protected void onEvent(WorldEvent e) { + } + + private void snapshotCells(boolean markChanges) { + TileGrid g = world.getGrid(); + int w = g.getCols(); + for (int r = 0; r < g.getRows(); r++) { + for (int c = 0; c < w; c++) { + byte k = (byte) g.get(c, r); + int i = r * w + c; + if (cells[i] != k) { + cells[i] = k; + if (markChanges) { + blocksDirty = true; + markDirty(c, r); + markDirty(c, r + 1); + } + } + } + } + } + + private void markDirty(int c, int r) { + TileGrid g = world.getGrid(); + if (c < 0 || r < 0 || c >= g.getCols() || r >= g.getRows()) { + return; + } + dirty[(r / CHUNK) * chunkCols + c / CHUNK] = true; + } + + private void bakeChunks() { + TileGrid g = world.getGrid(); + int ts = (g.getTileSize() >> 16); + int px = (int) Math.round(ts * artScale); + for (int i = 0; i < chunks.length; i++) { + if (!dirty[i]) { + continue; + } + dirty[i] = false; + int chunkRow = i / chunkCols; + int c0 = (i - chunkRow * chunkCols) * CHUNK; + int r0 = chunkRow * CHUNK; + Image img = null; + Graphics gr = null; + for (int r = r0; r < Math.min(r0 + CHUNK, g.getRows()); r++) { + for (int c = c0; c < Math.min(c0 + CHUNK, g.getCols()); c++) { + Image t = art.tile(g, c, r); + if (t == null) { + continue; + } + if (img == null) { + img = Image.createImage(CHUNK * px, CHUNK * px, 0); + gr = img.getGraphics(); + } + gr.drawImage(t, (c - c0) * px, (r - r0) * px, px, px); + } + } + Sprite s = chunks[i]; + if (s != null) { + releaseTexture(s.getImage()); + if (img == null) { + getScene().remove(s); + chunks[i] = null; + } else { + s.setImage(img); + } + } else if (img != null) { + s = new Sprite(img); + s.setAnchor(0, 0); + s.setZOrder(Z_TILES); + s.setUserData(new double[] {c0 * ts, r0 * ts}); + s.setVisible(!depth); + chunks[i] = s; + getScene().add(s); + } + } + } + + private final Object goalKey = new Object(); + private final List ghosts = new ArrayList(); + + /// A recorded run raced alongside the live one: its own world, stepped + /// tick for tick with the live world from its own input log. + private static final class Ghost { + final PlatformWorld world; + final int[] inputs; + final int alpha; + + Ghost(PlatformWorld world, int[] inputs, int alpha) { + this.world = world; + this.inputs = inputs; + this.alpha = alpha; + } + } + + /// Races a recorded run alongside this one: `ghostWorld` is stepped with + /// `inputs` on every tick the live world steps, and its hero is drawn + /// translucent. Nothing it does reaches the live world, the feedback or + /// the events -- it is a picture of another run, which is exactly what a + /// replayed log reproduces. Build `ghostWorld` from the same level and + /// seed the run was recorded with, and add it before the first tick. + /// + /// #### Parameters + /// + /// - `ghostWorld`: a fresh world for the ghost + /// - `inputs`: its input for every tick, as `InputLog.toArray` gives it + /// - `alpha`: how opaque to draw it, 0 to 255 + public void addGhost(PlatformWorld ghostWorld, int[] inputs, int alpha) { + ghosts.add(new Ghost(ghostWorld, inputs, Math.max(0, Math.min(255, alpha)))); + } + + /// Removes every ghost. + public void clearGhosts() { + ghosts.clear(); + } + + /// The ghosts' worlds, in the order they were added, so a HUD can say who + /// is ahead. + /// + /// #### Returns + /// + /// a new list + public List getGhostWorlds() { + List out = new ArrayList(); + for (int i = 0; i < ghosts.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator + out.add(ghosts.get(i).world); + } + return out; + } + + private void syncSprites(boolean reset) { + for (Shown s : shown.values()) { + s.seen = false; + } + List plats = world.getPlatforms(); + for (int i = 0; i < plats.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + MovingPlatform p = plats.get(i); + Shown s = show(p, Z_PLATFORMS, false); + s.sprite.setImage(art.platform(p)); + place(s, p.getX(), p.getY(), reset); + } + List ents = world.getEntities(); + for (int i = 0; i < ents.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Entity e = ents.get(i); + Image img = art.entity(e, world.getTick()); + Shown s = show(e, Z_ENTITIES, false); + s.sprite.setVisible(img != null); + if (img != null) { + s.sprite.setImage(img); + } + place(s, e.x + e.w / 2, e.y + e.h / 2, reset); + } + int[] goal = world.getGoal(); + if (goal[2] > 0 && goal[3] > 0) { + Image img = art.goal(goal[2] >> 16, goal[3] >> 16, world.getTick()); + Shown s = show(goalKey, Z_ENTITIES - 1, false); + s.sprite.setVisible(img != null); + if (img != null) { + s.sprite.setImage(img); + } + place(s, goal[0] + goal[2] / 2, goal[1] + goal[3] / 2, reset); + } + List actors = world.getActors(); + for (int i = 0; i < actors.size(); i++) { + Actor a = actors.get(i); + if (!a.isAlive()) { + continue; + } + Shown s = show(a, Z_ACTORS + (i == 0 ? 1 : 0), true); + s.track.tick(a.getState()); + SpriteSheet sheet = art.sheet(a); + int frame = art.animator(a).frameFor(s.track); + s.sprite.setImage(sheet.getFrame(Math.max(0, Math.min(frame, sheet.getFrameCount() - 1)))); + Body b = a.getBody(); + place(s, b.x + b.w / 2, b.y + b.h, reset); + boolean blink = a.getHealth() != null && a.getHealth().isInvulnerable() && (world.getTick() / 4) % 2 == 0; + s.sprite.setAlpha(blink ? 90 : 255); + s.sprite.setUserData(a.getFacing() < 0 ? Boolean.TRUE : Boolean.FALSE); + } + for (int i = 0; i < ghosts.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick + Ghost gh = ghosts.get(i); + Actor a = gh.world.getPlayer(); + if (a == null || !a.isAlive() || gh.world.isComplete()) { + continue; + } + Shown s = show(gh, Z_ACTORS - 1, true); + s.track.tick(a.getState()); + SpriteSheet sheet = art.sheet(a); + int frame = art.animator(a).frameFor(s.track); + s.sprite.setImage(sheet.getFrame(Math.max(0, Math.min(frame, sheet.getFrameCount() - 1)))); + Body b = a.getBody(); + place(s, b.x + b.w / 2, b.y + b.h, reset); + s.sprite.setAlpha(gh.alpha); + s.sprite.setUserData(a.getFacing() < 0 ? Boolean.TRUE : Boolean.FALSE); + } + gone.clear(); + for (Map.Entry en : shown.entrySet()) { + if (!en.getValue().seen) { + gone.add(en.getKey()); + } + } + for (int i = 0; i < gone.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + getScene().remove(shown.remove(gone.get(i)).sprite); + } + } + + private Shown show(Object key, int z, boolean actor) { + Shown s = shown.get(key); + if (s == null) { + Sprite sp = new Sprite(); + sp.setAnchor(0.5, actor ? 1 : 0.5); + if (key instanceof MovingPlatform) { + sp.setAnchor(0, 0); + } + sp.setZOrder(z); + getScene().add(sp); + s = new Shown(sp, actor); + shown.put(key, s); + s.seen = true; + s.prevX = Double.NaN; + return s; + } + s.seen = true; + return s; + } + + private static void place(Shown s, int fx, int fy, boolean reset) { + s.x = fx / 65536.0; + s.y = fy / 65536.0; + if (reset || Double.isNaN(s.prevX)) { + s.prevX = s.x; + s.prevY = s.y; + } + } + + private void snapCamera() { + Actor p = world.getPlayer(); + if (p != null) { + Body b = p.getBody(); + camera.snapTo((b.x + b.w / 2) / 65536.0, (b.y + b.h / 2) / 65536.0); + } + } + + /// Positions everything for this frame, between the last two ticks. + @Override + public void frame(double deltaSeconds) { + super.frame(deltaSeconds); + int vw = Math.max(1, getWidth()); + int vh = Math.max(1, getHeight()); + TileGrid g = world.getGrid(); + scale = vh / (visibleRows * (g.getTileSize() >> 16)); + camera.setViewSize(vw / scale, vh / scale); + double alpha = getInterpolationAlpha(); + Actor p = world.getPlayer(); + if (p != null && p.isAlive()) { + Shown ps = shown.get(p); + Body b = p.getBody(); + double cx = ps == null ? (b.x + b.w / 2) / 65536.0 : ps.prevX + (ps.x - ps.prevX) * alpha; + double cy = ps == null ? (b.y + b.h / 2) / 65536.0 + : ps.prevY + (ps.y - ps.prevY) * alpha - (b.h / 65536.0) / 2; + camera.update(cx, cy, p.getFacing(), deltaSeconds); + } + feedback.update(deltaSeconds); + updateParticles(deltaSeconds); + bakeChunks(); + if (blocksDirty) { + rebuildBlocks(); + } + if (depth) { + positionDepth(alpha); + } else { + positionFlat(alpha); + } + int f = feedback.getFlash(); + flash.setVisible(f != 0); + if (f != 0) { + flash.setColor(f); + if (depth) { + double ts = (g.getTileSize() >> 16); + double cx = (camera.getX() + camera.getViewWidth() / 2) / ts; + double cy = -(camera.getY() + camera.getViewHeight() / 2) / ts; + double dist = cameraDistance(); + double hh = 2 * (dist / 2) * Math.tan(Math.toRadians(fov / 2)) * 1.2; + flash.setAnchor(0.5, 0.5); + flash.setPosition(cx, cy, dist / 2); + flash.setSize((float) (hh * vw / vh), (float) hh); + } else { + flash.setAnchor(0, 0); + flash.setPosition(0, 0); + flash.setSize(vw, vh); + } + } + } + + /// The image a particle is drawn with: a soft white dot, tinted per burst. + /// Override for sparks, leaves or embers. + /// + /// #### Returns + /// + /// the particle image + protected Image createParticleImage() { + int d = 16; + Image img = Image.createImage(d, d, 0); + Graphics g = img.getGraphics(); + g.setAntiAliased(true); + for (int r = d / 2; r > 0; r--) { + int a = 255 * (d / 2 - r + 1) / (d / 2); + g.setColor(0xffffff); + g.setAlpha(Math.min(255, a)); + g.fillArc(d / 2 - r, d / 2 - r, r * 2, r * 2, 0, 360); + } + return img; + } + + private void spawnParticles(double x, double y, int count, int color) { + if (particleImage == null) { + particleImage = createParticleImage(); + } + int n = (int) Math.round(count * feedback.getIntensity()); + for (int i = 0; i < n && particles.size() < MAX_PARTICLES; i++) { + Particle p = new Particle(); + double a = particleRandom.nextDouble() * Math.PI * 2; + double v = 30 + particleRandom.nextDouble() * 110; + p.x = x; + p.y = y; + p.vx = Math.cos(a) * v; + p.vy = Math.sin(a) * v - 60; + p.max = 0.35 + particleRandom.nextDouble() * 0.4; + p.life = p.max; + p.size = 2 + particleRandom.nextDouble() * 3; + p.sprite = new Sprite(particleImage); + p.sprite.setAnchor(0.5, 0.5); + p.sprite.setZOrder(Z_PARTICLES); + p.sprite.setColor(color | 0xff000000); + particles.add(p); + getScene().add(p.sprite); + } + } + + private void updateParticles(double dt) { + double ts = world.getGrid().getTileSize() >> 16; + for (int i = particles.size() - 1; i >= 0; i--) { + Particle p = particles.get(i); + p.life -= dt; + if (p.life <= 0) { + getScene().remove(p.sprite); + particles.remove(i); + continue; + } + p.vy += 260 * dt; + p.vx *= 1 - 2.5 * dt; + p.x += p.vx * dt; + p.y += p.vy * dt; + double k = p.life / p.max; + p.sprite.setAlpha((int) (255 * Math.min(1, k * 1.6))); + double size = p.size * (0.4 + 0.6 * k); + if (depth) { + p.sprite.setPosition(p.x / ts, -p.y / ts, 0.7); + p.sprite.setSize((float) (size / ts), (float) (size / ts)); + } else { + p.sprite.setPosition(p.x * scale, p.y * scale, 0); + p.sprite.setSize((float) (size * scale), (float) (size * scale)); + } + } + } + + private double cameraDistance() { + return (visibleRows / 2) / Math.tan(Math.toRadians(fov / 2)); + } + + private void positionFlat(double alpha) { + double camX = camera.getX(); + double camY = camera.getY(); + getScene().setCamera((int) Math.round(camX * scale), (int) Math.round(camY * scale)); + for (int i = 0; i < chunks.length; i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Sprite s = chunks[i]; + if (s != null) { + double[] at = (double[]) s.getUserData(); + s.setPosition(Math.floor(at[0] * scale), Math.floor(at[1] * scale), 0); + // Overlap by a pixel so a fractional scale never opens a seam. + s.setSize((float) Math.ceil(s.getImage().getWidth() * scale / artScale) + 1, + (float) Math.ceil(s.getImage().getHeight() * scale / artScale) + 1); + } + } + for (Map.Entry en : shown.entrySet()) { + Shown s = en.getValue(); + double x = s.prevX + (s.x - s.prevX) * alpha; + double y = s.prevY + (s.y - s.prevY) * alpha; + s.sprite.setPosition(x * scale, y * scale, 0); + s.sprite.setSize(0, 0); + boolean flip = en.getKey() instanceof Actor && Boolean.TRUE.equals(s.sprite.getUserData()); + float k = (float) (scale / artScale); + s.sprite.setScale(flip ? -k : k, k); + } + for (int i = 0; i < backgrounds.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Sprite s = backgrounds.get(i); + double[] at = (double[]) s.getUserData(); + s.setPosition(at[0] * scale, at[1] * scale, 0); + s.setScale((float) (scale / artScale)); + } + } + + private void positionDepth(double alpha) { + double ts = (world.getGrid().getTileSize() >> 16); + double cx = (camera.getX() + camera.getViewWidth() / 2) / ts; + double cy = -(camera.getY() + camera.getViewHeight() / 2) / ts; + double dist = cameraDistance(); + getCamera().setPosition((float) cx, (float) (cy + dist * depthTilt), (float) dist); + getCamera().setTarget((float) cx, (float) cy, 0f); + float unit = (float) (1 / (ts * artScale)); + for (Map.Entry en : shown.entrySet()) { + Shown s = en.getValue(); + double x = s.prevX + (s.x - s.prevX) * alpha; + double y = s.prevY + (s.y - s.prevY) * alpha; + boolean isActor = en.getKey() instanceof Actor; + s.sprite.setPosition(x / ts, -y / ts, isActor ? 0.6 : 0.55); + Image img = s.sprite.getImage(); + if (img != null) { + s.sprite.setSize(img.getWidth() * unit, img.getHeight() * unit); + } + boolean flip = isActor && Boolean.TRUE.equals(s.sprite.getUserData()); + s.sprite.setScale(flip ? -1f : 1f, 1f); + } + for (int i = 0; i < backgrounds.size(); i++) { // NOPMD ForLoopCanBeForeach - indexed: no iterator per tick, list may grow + Sprite s = backgrounds.get(i); + double[] at = (double[]) s.getUserData(); + float factor = s.getParallaxX(); + // Depth gives parallax for free: a layer that scrolls at `factor` + // sits where perspective makes it move that fast. + double z = -dist * (1 / Math.max(0.05, factor) - 1); + double grow = (dist - z) / dist; + // About the camera's centre on both axes, so the layer stays in + // view and slides at `factor` of the world's speed. + float h = (float) (s.getImage().getHeight() * unit * grow); + // The anchor (0, 0) is the image's top-left in depth as in 2D, so + // the layer is placed by its top edge. + s.setPosition(at[0] / ts * grow + cx * (1 - grow), -at[1] / ts * grow + cy * (1 - grow), z); + s.setSize((float) (s.getImage().getWidth() * unit * grow), h); + s.setScale(1f); + } + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/ProceduralArt.java b/CodenameOne/src/com/codename1/gaming/platformer/view/ProceduralArt.java new file mode 100644 index 00000000000..071e03f3429 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/ProceduralArt.java @@ -0,0 +1,429 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.SpriteSheet; +import com.codename1.gaming.platformer.Actor; +import com.codename1.gaming.platformer.Entity; +import com.codename1.gaming.platformer.MovementState; +import com.codename1.gaming.platformer.MovingPlatform; +import com.codename1.gaming.platformer.Tile; +import com.codename1.gaming.platformer.TileGrid; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; + +import java.util.HashMap; +import java.util.Map; + +/// Art drawn from code: flat tiles with a lit top edge, rounded characters with +/// eyes and stepping feet, coins, keys, doors and springs. Every image is made +/// once and cached. +/// +/// It makes a level playable and readable before any art exists, and it is the +/// fallback a game keeps for whatever it has not drawn yet: extend it and +/// override `#tile`, `#sheet` or `#entity` for the kinds you have art for. The +/// palette is set with `#setPalette`. +public class ProceduralArt implements PlatformArt { + /// Frames in a generated actor sheet: 0-1 idle, 2-5 walk, 6 jump, 7 fall, + /// 8 crouch, 9 climb, 10 hurt, 11 dash. + public static final int FRAMES = 12; + + private final int tileSize; + private int ground = 0xff5b4b8a; + private int groundTop = 0xff9d8be0; + private int accent = 0xffffd34d; + private final Map cache = new HashMap(); + private final Map sheets = new HashMap(); + private final ActorAnimator animator; + + /// Creates the art for a tile size. + /// + /// #### Parameters + /// + /// - `tileSize`: pixels per tile + public ProceduralArt(int tileSize) { + this.tileSize = tileSize; + animator = new ActorAnimator() + .set(MovementState.IDLE, 30, true, 0, 1) + .set(MovementState.WALKING, 7, true, 2, 3, 4, 5) + .set(MovementState.RUNNING, 4, true, 2, 3, 4, 5) + .set(MovementState.JUMPING, 1, false, 6) + .set(MovementState.FALLING, 1, false, 7) + .set(MovementState.CROUCHING, 1, false, 8) + .set(MovementState.CRAWLING, 8, true, 8, 0) + .set(MovementState.CLIMBING, 8, true, 9, 9) + .set(MovementState.HURT, 1, false, 10) + .set(MovementState.DASHING, 1, false, 11); + } + + /// Sets the colors. + /// + /// #### Parameters + /// + /// - `ground`: solid tiles + /// - `groundTop`: the lit top edge of solid tiles + /// - `accent`: coins and highlights + public void setPalette(int ground, int groundTop, int accent) { + this.ground = ground; + this.groundTop = groundTop; + this.accent = accent; + cache.clear(); + } + + /// The tile size. + /// + /// #### Returns + /// + /// pixels + protected int getTileSize() { + return tileSize; + } + + @Override + public Image tile(TileGrid grid, int col, int row) { + int k = grid.get(col, row); + if (k == Tile.EMPTY) { + return null; + } + boolean open = k == Tile.SOLID && !isGround(grid.get(col, row - 1)); + String key = "t" + k + (open ? "o" : ""); + Image img = cache.get(key); + if (img == null) { + img = drawTile(k, open); + cache.put(key, img); + } + return img; + } + + private static boolean isGround(int k) { + return k == Tile.SOLID || Tile.isSlope(k); + } + + private Image drawTile(int k, boolean open) { + int s = tileSize; + Image img = Image.createImage(s, s, 0); + Graphics g = img.getGraphics(); + g.setAntiAliased(false); + if (k == Tile.SOLID) { + g.setColor(ground & 0xffffff); + g.fillRect(0, 0, s, s); + g.setColor(darker(ground)); + g.fillRect(0, s - Math.max(1, s / 8), s, Math.max(1, s / 8)); + if (open) { + g.setColor(groundTop & 0xffffff); + g.fillRect(0, 0, s, Math.max(2, s / 5)); + } + } else if (Tile.isSlope(k)) { + int[] xs = new int[s + 3]; + int[] ys = new int[s + 3]; + int fs = s << 16; + for (int x = 0; x <= s; x++) { + int lx = Math.min(x, s - 1) << 16; + xs[x] = x; + ys[x] = Tile.slopeDepth(k, lx, fs) >> 16; + } + xs[s + 1] = s; + ys[s + 1] = s; + xs[s + 2] = 0; + ys[s + 2] = s; + g.setColor(ground & 0xffffff); + g.fillPolygon(xs, ys, s + 3); + g.setColor(groundTop & 0xffffff); + for (int x = 0; x < s; x++) { + g.fillRect(x, ys[x], 1, Math.max(2, s / 6)); + } + } else if (k == Tile.ONE_WAY) { + g.setColor(0x8a6a4a); + g.fillRect(0, 0, s, Math.max(3, s / 4)); + g.setColor(0xc9a27a); + g.fillRect(0, 0, s, Math.max(1, s / 10)); + } else if (k == Tile.LADDER) { + g.setColor(0xb08850); + int rail = Math.max(1, s / 8); + g.fillRect(s / 5, 0, rail, s); + g.fillRect(s - s / 5 - rail, 0, rail, s); + for (int y = s / 6; y < s; y += s / 3) { + g.fillRect(s / 5, y, s - 2 * (s / 5), rail); + } + } else if (k == Tile.HAZARD) { + g.setColor(0xd8dde8); + int teeth = 3; + int w = s / teeth; + for (int i = 0; i < teeth; i++) { + g.fillTriangle(i * w, s, i * w + w / 2, s / 3, i * w + w, s); + } + } else if (k == Tile.WATER) { + g.setColor(0x3d7fd9); + g.setAlpha(120); + g.fillRect(0, 0, s, s); + g.setAlpha(255); + } + return img; + } + + private static int darker(int argb) { + int r = ((argb >> 16) & 0xff) * 3 / 4; + int gr = ((argb >> 8) & 0xff) * 3 / 4; + int b = (argb & 0xff) * 3 / 4; + return (r << 16) | (gr << 8) | b; + } + + @Override + public SpriteSheet sheet(Actor actor) { + String kind = actor.getKind(); + int w = Math.max(4, actor.getBody().w >> 16); + int h = Math.max(4, actor.getStandHeight() >> 16); + String key = kind + w + "x" + h; + SpriteSheet sheet = sheets.get(key); + if (sheet == null) { + sheet = drawActor(colorFor(actor), w, h, actor.getTeam() != 0); + sheets.put(key, sheet); + } + return sheet; + } + + /// The body color for an actor: the hero is the accent, others are derived + /// from the kind name. + /// + /// #### Parameters + /// + /// - `actor`: the actor + /// + /// #### Returns + /// + /// RGB + protected int colorFor(Actor actor) { + if (actor.getTeam() == 0) { + return 0x4fc3f7; + } + int h = actor.getKind().hashCode(); + int[] hues = {0xef5350, 0x66bb6a, 0xab47bc, 0xffa726, 0x8d6e63, 0x26a69a}; + return hues[(h & 0x7fffffff) % hues.length]; + } + + private SpriteSheet drawActor(int color, int w, int h, boolean enemy) { + int fw = w + 4; + int fh = h + 2; + Image img = Image.createImage(fw * FRAMES, fh, 0); + Graphics g = img.getGraphics(); + g.setAntiAliased(true); + for (int f = 0; f < FRAMES; f++) { + int ox = f * fw + 2; + int bh = h; + int bob = 0; + int step = 0; + if (f == 1) { + bob = 1; + } else if (f >= 2 && f <= 5) { + step = (f & 1) == 0 ? 2 : -2; + bob = (f & 1); + } else if (f == 8) { + bh = h * 2 / 3; + } else if (f == 6) { + bob = -1; + } + int top = fh - bh + bob - 1; + int footH = Math.max(2, h / 8); + g.setColor(darker(color)); + g.fillRect(ox + w / 4 - 1 + step, fh - footH, Math.max(2, w / 4), footH); + g.setColor(darker(color)); + g.fillRect(ox + w * 3 / 4 - Math.max(2, w / 4) + 1 - step, fh - footH, Math.max(2, w / 4), footH); + g.setColor(f == 10 ? 0xffffff : color); + int arc = Math.max(3, w / 2); + g.fillRoundRect(ox, top, w, bh - footH + 1, arc, arc); + int eyeY = top + Math.max(2, bh / 4); + int eyeW = Math.max(2, w / 5); + g.setColor(0xffffff); + g.fillRect(ox + w / 2, eyeY, eyeW + 1, eyeW + 1); + g.fillRect(ox + w / 2 + eyeW + 2, eyeY, eyeW + 1, eyeW + 1); + g.setColor(enemy ? 0x400000 : 0x1a1a40); + g.fillRect(ox + w / 2 + 1, eyeY + 1, Math.max(1, eyeW - 1), Math.max(1, eyeW - 1)); + g.fillRect(ox + w / 2 + eyeW + 3, eyeY + 1, Math.max(1, eyeW - 1), Math.max(1, eyeW - 1)); + if (f == 9) { + g.setColor(darker(color)); + g.fillRect(ox - 1, top + bh / 3, 2, bh / 4); + g.fillRect(ox + w - 1, top + bh / 4, 2, bh / 4); + } + if (f == 11) { + g.setColor(0x9fd8ff); + g.fillRect(ox - 2, top + bh / 2, 2, 1); + } + } + return new SpriteSheet(img, fw, fh); + } + + @Override + public ActorAnimator animator(Actor actor) { + return animator; + } + + @Override + public Image entity(Entity e, int tick) { + int w = Math.max(2, e.w >> 16); + int h = Math.max(2, e.h >> 16); + String type = e.getType(); + int phase = e.getPhase(); + int spin = 0; + if ("coin".equals(type)) { + spin = (tick / 8) % 4; + } + String key = type + phase + ":" + w + "x" + h + ":" + spin; + Image img = cache.get(key); + if (img == null) { + img = drawEntity(type, phase, w, h, spin); + cache.put(key, img); + } + return img; + } + + private Image drawEntity(String type, int phase, int w, int h, int spin) { + Image img = Image.createImage(w, h, 0); + Graphics g = img.getGraphics(); + g.setAntiAliased(true); + if ("coin".equals(type)) { + int cw = spin == 1 || spin == 3 ? w / 2 : spin == 2 ? Math.max(2, w / 6) : w; + g.setColor(accent & 0xffffff); + g.fillArc((w - cw) / 2, 0, cw, h, 0, 360); + g.setColor(0xfff3b0); + g.fillArc((w - cw) / 2 + cw / 4, h / 4, Math.max(1, cw / 3), h / 3, 0, 360); + } else if ("gem".equals(type)) { + g.setColor(0x4dd0e1); + g.fillPolygon(new int[] {w / 2, w, w / 2, 0}, new int[] {0, h / 2, h, h / 2}, 4); + } else if ("heart".equals(type) || "life".equals(type)) { + g.setColor("life".equals(type) ? 0x66bb6a : 0xef5350); + g.fillArc(0, 0, w / 2 + 1, h / 2 + 1, 0, 360); + g.fillArc(w / 2 - 1, 0, w / 2 + 1, h / 2 + 1, 0, 360); + g.fillTriangle(0, h / 4 + 1, w, h / 4 + 1, w / 2, h); + } else if ("key".equals(type)) { + g.setColor(accent & 0xffffff); + g.fillArc(0, 0, h / 2, h / 2, 0, 360); + g.fillRect(h / 4, h / 4 - 1, w - h / 4, 3); + g.fillRect(w - 3, h / 4, 2, h / 3); + } else if ("powerup".equals(type)) { + g.setColor(0xab47bc); + g.fillRoundRect(0, 0, w, h, w / 2, h / 2); + g.setColor(0xffffff); + g.fillArc(w / 4, h / 4, w / 2, h / 2, 0, 360); + } else if ("spring".equals(type)) { + g.setColor(0x9e9e9e); + int coil = phase == 1 ? h / 3 : h * 2 / 3; + for (int y = h - 2; y > h - coil; y -= 3) { + g.fillRect(w / 4, y, w / 2, 1); + } + g.setColor(0xef5350); + g.fillRect(0, h - coil - 2, w, 3); + g.fillRect(0, h - 2, w, 2); + } else if ("checkpoint".equals(type)) { + g.setColor(0xbdbdbd); + g.fillRect(w / 2 - 1, 0, 2, h); + g.setColor(phase == 1 ? 0x66bb6a : 0x757575); + g.fillTriangle(w / 2 + 1, 1, w, h / 6, w / 2 + 1, h / 3); + } else if ("door".equals(type) || "gate".equals(type)) { + if (phase == 0) { + g.setColor("door".equals(type) ? 0x8d6e63 : 0x78909c); + g.fillRect(0, 0, w, h); + g.setColor(accent & 0xffffff); + if ("door".equals(type)) { + g.fillRect(w * 2 / 3, h / 2, 2, 2); + } else { + for (int x = 2; x < w; x += 4) { + g.fillRect(x, 0, 1, h); + } + } + } else { + g.setColor(0x3e2723); + g.setAlpha(90); + g.fillRect(0, 0, w, h); + g.setAlpha(255); + } + } else if ("lever".equals(type) || "plate".equals(type)) { + g.setColor(0x757575); + g.fillRect(0, h - Math.max(2, h / 4), w, Math.max(2, h / 4)); + if ("lever".equals(type)) { + g.setColor(phase == 1 ? 0x66bb6a : 0xef5350); + int bx = phase == 1 ? w * 3 / 4 : w / 4; + g.drawLine(w / 2, h - 2, bx, h / 3); + g.fillArc(bx - 2, h / 3 - 2, 5, 5, 0, 360); + } else if (phase == 1) { + g.setColor(0x66bb6a); + g.fillRect(1, h - Math.max(2, h / 4), w - 2, 1); + } + } else if ("crumble".equals(type)) { + if (phase != 3) { + g.setColor(phase == 2 ? 0x6d4c41 : 0xa1887f); + g.fillRect(0, 0, w, h); + g.setColor(0x4e342e); + for (int x = tileSize; x < w; x += tileSize) { + g.fillRect(x, 0, 1, h); + } + if (phase > 0) { + g.drawLine(w / 4, 0, w / 2, h); + g.drawLine(w * 3 / 4, 0, w / 2 + 2, h / 2); + } + } + } else { + g.setColor(0xfff176); + g.fillArc(0, 0, w, h, 0, 360); + } + return img; + } + + @Override + public Image platform(MovingPlatform p) { + int w = Math.max(2, p.getWidth() >> 16); + int h = Math.max(2, p.getHeight() >> 16); + String key = "p" + w + "x" + h; + Image img = cache.get(key); + if (img == null) { + img = Image.createImage(w, h, 0); + Graphics g = img.getGraphics(); + g.setColor(0x607d8b); + g.fillRect(0, 0, w, h); + g.setColor(0x90a4ae); + g.fillRect(0, 0, w, Math.max(1, h / 4)); + cache.put(key, img); + } + return img; + } + + @Override + public Image goal(int width, int height, int tick) { + int w = Math.max(2, width); + int h = Math.max(2, height); + String key = "g" + w + "x" + h + "_" + ((tick / 8) % 4); + Image img = cache.get(key); + if (img == null) { + img = Image.createImage(w, h, 0); + Graphics g = img.getGraphics(); + g.setAntiAliased(true); + g.setColor(0x4527a0); + g.fillRoundRect(0, 0, w, h, w, w); + g.setColor(accent & 0xffffff); + int inset = 2 + (tick / 8) % 4; + g.drawRoundRect(inset, inset, w - inset * 2 - 1, h - inset * 2 - 1, w / 2, w / 2); + cache.put(key, img); + } + return img; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/TileLayerCollision.java b/CodenameOne/src/com/codename1/gaming/platformer/view/TileLayerCollision.java new file mode 100644 index 00000000000..da33635a804 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/TileLayerCollision.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.SpriteSheet; +import com.codename1.gaming.level.TileLayer; +import com.codename1.gaming.platformer.Tile; +import com.codename1.gaming.platformer.TileGrid; + +/// Converts between a drawn `com.codename1.gaming.level.TileLayer` and the +/// collision `TileGrid` the simulation reads. +/// +/// A game painting its levels with an atlas keeps one table, "frame N of the +/// sheet is solid, frame M is a one-way ledge", and derives the collision from +/// the art with `#toGrid`; a game that writes `Tile` characters derives the art +/// from the collision with `#toLayer`. +public final class TileLayerCollision { + private TileLayerCollision() { + } + + /// Builds the collision grid for a tile layer. + /// + /// #### Parameters + /// + /// - `layer`: the drawn layer + /// - `frameKinds`: the `Tile` kind of each sheet frame; frames past the end and + /// empty cells are `Tile#EMPTY` + /// + /// #### Returns + /// + /// a grid of the same size and tile size + public static TileGrid toGrid(TileLayer layer, int[] frameKinds) { + TileGrid g = new TileGrid(layer.getCols(), layer.getRows(), layer.getTileSize()); + for (int r = 0; r < layer.getRows(); r++) { + for (int c = 0; c < layer.getCols(); c++) { + int f = layer.getTile(c, r); + g.set(c, r, f >= 0 && f < frameKinds.length ? frameKinds[f] : Tile.EMPTY); + } + } + return g; + } + + /// Builds a tile layer that draws a collision grid. + /// + /// #### Parameters + /// + /// - `grid`: the grid + /// - `sheet`: the tileset + /// - `kindFrames`: the sheet frame for each `Tile` kind, indexed by kind; -1 or + /// past the end draws nothing + /// + /// #### Returns + /// + /// the layer + public static TileLayer toLayer(TileGrid grid, SpriteSheet sheet, int[] kindFrames) { + TileLayer layer = new TileLayer(sheet, grid.getCols(), grid.getRows(), grid.getTileSize() >> 16); + for (int r = 0; r < grid.getRows(); r++) { + for (int c = 0; c < grid.getCols(); c++) { + int k = grid.get(c, r); + layer.setTile(c, r, k >= 0 && k < kindFrames.length ? kindFrames[k] : -1); + } + } + return layer; + } +} diff --git a/CodenameOne/src/com/codename1/gaming/platformer/view/package-info.java b/CodenameOne/src/com/codename1/gaming/platformer/view/package-info.java new file mode 100644 index 00000000000..5496330c0e9 --- /dev/null +++ b/CodenameOne/src/com/codename1/gaming/platformer/view/package-info.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +/// Draws and plays a `com.codename1.gaming.platformer.PlatformWorld`: the client +/// half of the platformer engine. +/// +/// `PlatformView` is a `com.codename1.gaming.GameView` that steps the world at a +/// fixed 60 Hz from an `InputMapper` (keyboard, gamepad, on-screen controls), +/// interpolates drawing between ticks, follows the player with a +/// `PlatformCamera` (dead zone, look-ahead, level bounds, shake) and plays each +/// tick's events through `Feedback`. What it draws comes from a `PlatformArt`; +/// `ProceduralArt` draws everything from code so a level is playable before any +/// art exists, and `ActorAnimator` maps movement states to sprite-sheet frames. +/// +/// Nothing here feeds back into the simulation, which is why the simulation +/// package is shared with the server and this one is not. +package com.codename1.gaming.platformer.view; diff --git a/NOTICE b/NOTICE index b2de9b78026..5829b7a75bd 100644 --- a/NOTICE +++ b/NOTICE @@ -165,6 +165,12 @@ Papercut sample fonts (GochiHand-Regular.ttf, PatrickHand-Regular.ttf) by Patrick Wagesreiter, licensed under the SIL Open Font License 1.1; the licence text is in scripts/papercut/common/src/main/css/fonts/OFL.txt. +Ledge sample font (LilitaOne-Regular.ttf) + Lilita One, Copyright (c) 2011 Juan Montoreano, with Reserved Font Name + Lilita, licensed under the SIL Open Font License 1.1; the licence text is in + scripts/ledge/common/src/main/css/fonts/OFL.txt. Every image and sound in + the Ledge sample is drawn or synthesised by scripts/ledge/tools/make-art.py. + ================================================================================ .NET Standard reference assembly ================================================================================ diff --git a/docs/demos/common/src/main/snippets/developer-guide/ledge.sh b/docs/demos/common/src/main/snippets/developer-guide/ledge.sh new file mode 100644 index 00000000000..3732de33a91 --- /dev/null +++ b/docs/demos/common/src/main/snippets/developer-guide/ledge.sh @@ -0,0 +1,34 @@ +// Snippets of the Ledge chapter of the developer guide. Edit them here, not inline. + +// tag::ledge-sh-server[] +CN1_PROFILE=dev backend/server.sh run +// end::ledge-sh-server[] + +// tag::ledge-sh-simulator[] +mvn verify -Psimulator -DskipTests -Dcodename1.platform=javase +// end::ledge-sh-simulator[] + +// tag::ledge-sh-ios[] +mvn package -DskipTests -Dcodename1.platform=ios -Dcodename1.buildTarget=ios-source -Dopen=false +// end::ledge-sh-ios[] + +// tag::ledge-sh-level[] +python3 tools/sketch.py levels/src/2-4.sketch > levels/2-4.json +mvn -pl shared,backend -Dcodename1.platform=backend test -Dtest=LevelsTest -Dledge.record=2-4 +python3 tools/pack-levels.py +// end::ledge-sh-level[] + +// tag::ledge-sh-art[] +python3 tools/make-art.py +python3 tools/make-art.py actors +// end::ledge-sh-art[] + +// tag::ledge-sh-ai[] +ledge.ai.provider=anthropic +ledge.ai.key=... +// end::ledge-sh-ai[] + +// tag::ledge-sh-tests[] +mvn -pl shared,backend -Dcodename1.platform=backend test +./run-e2e.sh +// end::ledge-sh-tests[] diff --git a/docs/developer-guide/Ledge-Implementors-Guide.asciidoc b/docs/developer-guide/Ledge-Implementors-Guide.asciidoc new file mode 100644 index 00000000000..b2a0a28cd1b --- /dev/null +++ b/docs/developer-guide/Ledge-Implementors-Guide.asciidoc @@ -0,0 +1,301 @@ +[[ledge-implementors-guide]] +== Ledge: Making the platformer your own + +Ledge is a side-scrolling platformer. A small hooded hero runs, jumps twice, +clings to walls and dashes through thirteen levels in five worlds: a meadow, a +cavern, a foundry, a skyway drawn in 2.5D and the forge, where a golem waits at +the end. Slimes, beetles, brutes, turrets, frogs and bats stand in the way, and +coins, gems, keys, levers and crumbling floors fill the levels between them. + +What sets it apart from a platformer you would write from scratch is that every +run is recorded as the player's input, one entry per tick, and the server plays +that input back through the same engine to check the time and the score. That one +property is what the leaderboards, the ghosts you race, the death heat map in the +console and the level editor's "can it be finished" check are all built on. + +It shares the module layout and the accounts with <> +and <>. This chapter shows where each part +lives and what to change to make the game yours. + +[[ledge-launch]] +=== Running it + +The project is in `scripts/ledge`, and the Initializr generates it under your own +package and name. Start the server on the development profile, which keeps its +database in memory, seeds the demo accounts and simulates purchases: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/ledge.sh[tag=ledge-sh-server,indent=0] +---- + +Then run the app in the simulator, from the project's directory: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/ledge.sh[tag=ledge-sh-simulator,indent=0] +---- + +To build the native iOS app on a Mac, generate the Xcode project, which lands under +`ios/target`, then open it and run it on a simulator or a device from Xcode: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/ledge.sh[tag=ledge-sh-ios,indent=0] +---- + +The game plays without a server, and so does the editor; you only need one to sign +in, put runs on the boards, race other players and shop. Four demo accounts exist on +the development profile, each with the password `ledge-demo`: + +[cols="1,3"] +|=== +| Account | What it's for + +| `player@ledge.example` +| A player with five levels cleared and coins to spend. + +| `rival@ledge.example` +| A friend of the player, further ahead. + +| `trouble@ledge.example` +| A player with a flagged run, so the console has something to review. + +| `admin@ledge.example` +| The administrator. +|=== + +A field of rivals with runs spread over this week and today is seeded too, along +with a set of runs that died on the way, so every board and the death heat map +have something on them. Outside the development profile only the admin is made, +and only when the `ledge.admin.email` and `ledge.admin.password` properties say +who. + +[[ledge-what]] +=== What the sample does + +.The first level of the meadow +image::img/ledge-run.png[A run in Ledge,scaledwidth=45%] +image::img/ledge-depth.png[The skyway drawn in 2.5D,scaledwidth=45%] + +The home screen plays a level by itself behind the menu, driven by the level's +recorded route. From there the world map leads to the levels, each unlocked by the +one before it and scored with up to three stars for finishing, for beating the par +time and for finding its gem. Today's challenge is one level on the day's seed, +the same for every player, with a board of its own. + +On a touch screen a joystick on the left moves and buttons on the right jump and +dash; on a desktop the arrow keys or WASD move, Space jumps and Z dashes, and a +gamepad works too. The skyway levels are drawn in 2.5D: the same level and the same +simulation, rendered as blocks under a perspective camera that leans into the +climb. + +.The home screen and the world map +image::img/ledge-home.png[The Ledge home screen,scaledwidth=45%] +image::img/ledge-worlds.png[The world map,scaledwidth=45%] + +The boards show every level's best runs for all time, the week, today and your +friends. Every run on a board has two buttons: one plays it back, the other starts +the level with that run beside you as a translucent ghost, and the HUD says how far +ahead of you it is. + +.A board, and a race against its best run +image::img/ledge-boards.png[A leaderboard,scaledwidth=45%] +image::img/ledge-race.png[Racing a ghost,scaledwidth=45%] + +[[ledge-modules]] +=== The modules + +[cols="1,3"] +|=== +| Module | What it holds + +| `shared` | The data transfer objects, the `@RestClient` interfaces, and + everything both sides compute: the level pack, the sketch format, scoring, the + solver, the level generator and the death map. +| `common` | The app: the level view and HUD, the touch controls, the menus and + world map, the boards and races, the editor, the shop and the admin console. +| `backend` | The server: accounts, run tickets and replay verification, boards + and ghosts, the daily seed, the shop, achievements, AI levels and + administration. +| `ios` | The iOS build, for generating the Xcode project. +|=== + +The engine isn't in the project. It's Codename One's own, +`com.codename1.gaming.platformer`, and the project depends on it like any other +part of the framework. + +[[ledge-engine]] +=== The engine: A simulation that replays + +`com.codename1.gaming.platformer` is a character controller, a set of abilities +and a level model, in the spirit of the platformer kits other engines offer. Its +simulation half has no user interface at all and uses no floating point: positions +and speeds are 16.16 fixed point integers (`Fx`), the world steps exactly 60 times a +second, and its only randomness is a seeded generator (`Rng`). Given the same level, +the same seed and the same input, two runs end in the same state on every platform, +down to the last bit, and `PlatformWorld.hash()` proves it. + +The pieces you work with: + +- `TileGrid` and `Tile`: the level's collision map, written as rows of characters + -- `#` solid, `=` a one-way ledge, `/` and `\` slopes, `H` a ladder, `^` spikes, + `~` water. +- `Actor`, driven by an ordered list of `Ability` objects: `MoveAbility`, + `JumpAbility` (coyote time, a buffered press, variable height, double jumps), + `CrouchAbility`, `LadderAbility`, `WallJumpAbility`, `DashAbility`, and + `JetpackAbility`, `GlideAbility`, `SwimAbility` and `WeaponAbility` for + power-ups. A level names the hero's abilities and tunes them. +- `Health`, `Checkpoint`, `Pickup`, `Door`, `Gate`, `Switch`, `Spring`, + `CrumbleBlock` and `MovingPlatform`: what a level is built of. +- `AIBrain`: the enemies' patrol, chase, shoot and jump behaviours. +- `PlatformWorld`: steps all that one tick from `Input` bits. +- `LevelData`: reads a level from JSON and builds a world from it. +- `InputLog` and `Replay`: record a run's input and replay it. + +The presentation half is `com.codename1.gaming.platformer.view`: `PlatformView` +draws a world with parallax backgrounds, sprite animation, particles and screen +shake, interpolating between ticks; `setDepth(true)` draws it in 2.5D. +`PlatformArt` is the art it asks for, and Ledge's `LedgeArt` is the one class in the +project that knows file names. + +The engine's simulation classes are marked to be shared with the backend, so the +server compiles the identical code. That's the whole trick behind the next +section. + +[[ledge-honest]] +=== Scores the server can check + +When a signed-in player starts a level, the server hands out a single-use ticket +with a seed. The app records every tick's input in an `InputLog` while the player +plays, and sends the log, compressed as runs of equal input, when the level ends. +The server doesn't trust the time or the score in that request: `Scoring.replay` +plays the log through a fresh world built from the same level and seed, and the +time, coins, deaths and score it stores are the replay's. A run the replay doesn't +finish is refused. A run too fast to be true, compared with the level's own par +time, is stored and flagged for the console. + +Because a stored run is only its seed and its input, it's also a recording. +Playing it back, racing it, and drawing where it died are all the same replay. + +[[ledge-levels]] +=== Writing levels + +A level starts as a sketch in `levels/src`: a JSON header with its name, world, par +time and the hero's abilities, a line holding only `---`, then the level's sixteen +rows of tiles with its things drawn in as letters: + +[source,text] +---- +include::../../scripts/ledge/levels/src/1-1.sketch[lines=1-3] +---- + +`S` is the spawn and `X` the exit; `o` is a coin, `*` the gem, `e` a slime and +`k` a key. `LevelSketch` lists every letter. To add a level, compile its sketch, +have the solver prove it can be finished, and pack it: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/ledge.sh[tag=ledge-sh-level,indent=0] +---- + +The solver (`Solver`, in `shared`) is a search over the real simulation: it tries +input patterns from the spawn, keeps the positions that got furthest, and stops +when the hero reaches the exit. The route it finds is written to +`levels/demo/2-4.log` only if it finishes the level on every test seed. That route is +what the home screen plays, what the tests replay to prove a level still works +after an engine change, and the first ghost a player races. `tools/pack-levels.py` +then writes every level and route into the `LevelPack` class, so the app and the +server replay the same bytes. + +[[ledge-editor]] +=== The level editor + +.The editor, and a level it proved can be finished +image::img/ledge-editor.png[The level editor,scaledwidth=45%] +image::img/ledge-editor-proven.png[A proven level,scaledwidth=45%] + +The editor (`EditorForm`) edits the same sketch format on the device. Pick a tile or +a thing from the palette and paint; switch to pan to move around; change the world +or widen the level. Check runs the solver on a background thread and says whether +the level can be finished; Watch plays the solver's route; Play tests the level +yourself. The level being edited is kept in storage between sessions. + +Ask AI takes a description in words. Signed in, it goes to the server, which hands +it to a language model with a description of the sketch format, and runs the +solver on what comes back before returning it. A level the model drew badly, or +one the solver can't finish, is replaced by one the built-in `LevelGenerator` +assembles from proven pieces, and a note says so. Offline, or with no model set +up, the generator answers directly. To set up a model, give the server a provider +and a key: + +[source,properties] +---- +include::../demos/common/src/main/snippets/developer-guide/ledge.sh[tag=ledge-sh-ai,indent=0] +---- + +The key stays on the server; the app never sees it. Requests are limited per +player, and a description has a length limit. + +[[ledge-server]] +=== The server + +.The shop, and the death heat map in the console +image::img/ledge-shop.png[The shop,scaledwidth=45%] +image::img/ledge-deaths.png[Where players die,scaledwidth=45%] + +The backend is a Codename One backend application, and each area is a package: +`account` (sign-in, profiles, the demo accounts), `run` (tickets, replay +verification, boards, ghosts and the daily seed), `shop` (scarves, rewarded ads and +store receipts), `progress` (stars and achievements), `friends`, `push`, `ai` +and `admin`. + +The console is part of the app, shown only to administrators, and the server limits every route +behind it to the `ADMIN` role in `SecurityConfig`. It shows today's +numbers, finds players, reviews flagged runs, sets the daily seed, sends +broadcasts and keeps an audit of every action. Its Deaths tab is the heat map: the +server replays a level's recent runs, those that finished and those that died on +the way, and counts the tile each death happened on. The place a level is too hard +shows up as a bright spot. + +[[ledge-art]] +=== The art pipeline + +Every picture and sound is made by `tools/make-art.py`, from shapes and synthesis: +five tile sets, the hero's poses, seven enemies, items, three parallax layers per +world and nineteen sound effects. Nothing is downloaded or traced. Run it again +after changing a palette, a pose or an envelope: + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/ledge.sh[tag=ledge-sh-art,indent=0] +---- + +To use hand-drawn art instead, keep the file names and sizes that `ART.md` lists. + +[[ledge-reskin]] +=== Making it yours + +- **Levels**: edit or add sketches, as in <>. +- **The hero**: a level's header lists its abilities and tunes them (`maxJumps`, + `jumpSpeed`, run speed and the rest, on `LevelData.applyTuning`). +- **A new enemy**: a letter in `LevelSketch`, a kind the engine's brains can drive, + and a sheet in `make-art.py`. +- **The look**: `make-art.py` for the art, `common/src/main/css/theme.css` for the + menus. +- **The shop**: the scarves are a catalog in the backend's `shop` package. + +[[ledge-tests]] +=== Tests + +[source,bash] +---- +include::../demos/common/src/main/snippets/developer-guide/ledge.sh[tag=ledge-sh-tests,indent=0] +---- + +The server's tests replay every level's route on several seeds, have the solver +finish every level from nothing, and check that each sketch still compiles to the +level that ships, besides covering accounts, boards, the shop and the console. The +end-to-end tests start the server and drive the app in the simulator: they play +real levels by their routes, use the editor, race a ghost and open the console, +and save a screenshot of each screen. diff --git a/docs/developer-guide/developer-guide.asciidoc b/docs/developer-guide/developer-guide.asciidoc index 5bc5918306f..4d3748457de 100644 --- a/docs/developer-guide/developer-guide.asciidoc +++ b/docs/developer-guide/developer-guide.asciidoc @@ -198,6 +198,8 @@ include::Splat-Implementors-Guide.asciidoc[] include::Papercut-Implementors-Guide.asciidoc[] +include::Ledge-Implementors-Guide.asciidoc[] + include::Brickyard-Implementors-Guide.asciidoc[] include::Parley-Users-Guide.asciidoc[] diff --git a/docs/developer-guide/img/ledge-boards.png b/docs/developer-guide/img/ledge-boards.png new file mode 100644 index 00000000000..b34cceb555f Binary files /dev/null and b/docs/developer-guide/img/ledge-boards.png differ diff --git a/docs/developer-guide/img/ledge-deaths.png b/docs/developer-guide/img/ledge-deaths.png new file mode 100644 index 00000000000..17752948049 Binary files /dev/null and b/docs/developer-guide/img/ledge-deaths.png differ diff --git a/docs/developer-guide/img/ledge-depth.png b/docs/developer-guide/img/ledge-depth.png new file mode 100644 index 00000000000..f9961761243 Binary files /dev/null and b/docs/developer-guide/img/ledge-depth.png differ diff --git a/docs/developer-guide/img/ledge-editor-proven.png b/docs/developer-guide/img/ledge-editor-proven.png new file mode 100644 index 00000000000..21afcee1e52 Binary files /dev/null and b/docs/developer-guide/img/ledge-editor-proven.png differ diff --git a/docs/developer-guide/img/ledge-editor.png b/docs/developer-guide/img/ledge-editor.png new file mode 100644 index 00000000000..ac6602b2082 Binary files /dev/null and b/docs/developer-guide/img/ledge-editor.png differ diff --git a/docs/developer-guide/img/ledge-home.png b/docs/developer-guide/img/ledge-home.png new file mode 100644 index 00000000000..e357da2d17c Binary files /dev/null and b/docs/developer-guide/img/ledge-home.png differ diff --git a/docs/developer-guide/img/ledge-race.png b/docs/developer-guide/img/ledge-race.png new file mode 100644 index 00000000000..47b93561b43 Binary files /dev/null and b/docs/developer-guide/img/ledge-race.png differ diff --git a/docs/developer-guide/img/ledge-run.png b/docs/developer-guide/img/ledge-run.png new file mode 100644 index 00000000000..69f8a6f2b0b Binary files /dev/null and b/docs/developer-guide/img/ledge-run.png differ diff --git a/docs/developer-guide/img/ledge-shop.png b/docs/developer-guide/img/ledge-shop.png new file mode 100644 index 00000000000..11f6c7c8c48 Binary files /dev/null and b/docs/developer-guide/img/ledge-shop.png differ diff --git a/docs/developer-guide/img/ledge-worlds.png b/docs/developer-guide/img/ledge-worlds.png new file mode 100644 index 00000000000..a963b769db2 Binary files /dev/null and b/docs/developer-guide/img/ledge-worlds.png differ diff --git a/docs/developer-guide/languagetool-accept.txt b/docs/developer-guide/languagetool-accept.txt index b2b40be4511..9386b3f3ab2 100644 --- a/docs/developer-guide/languagetool-accept.txt +++ b/docs/developer-guide/languagetool-accept.txt @@ -938,6 +938,7 @@ artboard artboards leaderstat Papercut +Ledge Gochi Pillow ffmpeg diff --git a/maven/core-unittests/src/test/java/com/codename1/gaming/physics/PhysicsWorldTest.java b/maven/core-unittests/src/test/java/com/codename1/gaming/physics/PhysicsWorldTest.java index 6e5d2b5aeae..7b0c124241b 100644 --- a/maven/core-unittests/src/test/java/com/codename1/gaming/physics/PhysicsWorldTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/gaming/physics/PhysicsWorldTest.java @@ -1,3 +1,25 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ package com.codename1.gaming.physics; import com.codename1.gaming.Sprite; @@ -221,4 +243,39 @@ void setDebugFillAlphaIsSafeBeforeFirstDraw() { w.setDebugFillAlpha(40); // before any debugDraw() -> must not throw assertNotNull(w.getDebugDraw()); // renderer created lazily, package-private accessor } + + @Test + void oneWayPlatformHoldsFromAboveAndLetsThroughFromBelow() { + PhysicsWorld w = new PhysicsWorld(0, 600); + PhysicsBody ledge = w.createBox(160, 300, 200, 10, BodyType.STATIC); + w.setOneWay(ledge, true); + PhysicsBody falling = w.createBox(100, 200, 20, 20, BodyType.DYNAMIC); + PhysicsBody rising = w.createBox(220, 400, 20, 20, BodyType.DYNAMIC); + rising.setLinearVelocity(0, -900); + steps(w, 90); + assertEquals(285, falling.getY(), 2, "landed on top"); + assertTrue(rising.getY() < 285, "jumped up through it"); + + w.setOneWay(ledge, false); + PhysicsBody blocked = w.createBox(160, 400, 20, 20, BodyType.DYNAMIC); + blocked.setLinearVelocity(0, -900); + steps(w, 20); + assertTrue(blocked.getY() > 300, "solid again"); + } + + @Test + void contactFilterLetsBodiesPassThrough() { + PhysicsWorld w = new PhysicsWorld(0, 600); + final PhysicsBody floor = w.createBox(160, 400, 320, 40, BodyType.STATIC); + PhysicsBody ghost = w.createBox(160, 300, 20, 20, BodyType.DYNAMIC); + final PhysicsBody[] passer = {ghost}; + w.setContactFilter(new ContactFilter() { + @Override + public boolean shouldCollide(PhysicsBody a, PhysicsBody b, float nx, float ny) { + return a != passer[0] && b != passer[0]; + } + }); + steps(w, 60); + assertTrue(ghost.getY() > 420, "fell through the floor"); + } } diff --git a/maven/core-unittests/src/test/java/com/codename1/gaming/platformer/PlatformWorldTest.java b/maven/core-unittests/src/test/java/com/codename1/gaming/platformer/PlatformWorldTest.java new file mode 100644 index 00000000000..a29d218cea7 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/gaming/platformer/PlatformWorldTest.java @@ -0,0 +1,497 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.gaming.platformer; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/// Behaviour of the deterministic platformer simulation: the collision controller, +/// the stock abilities and replay. Pure model tests, no `Display`. +class PlatformWorldTest { + + private static PlatformWorld world(String extra, String... rows) { + StringBuilder sb = new StringBuilder("{\"tileSize\":16,\"tiles\":["); + for (int i = 0; i < rows.length; i++) { + if (i > 0) { + sb.append(','); + } + LevelJson.quote(sb, rows[i]); + } + sb.append("],\"spawn\":[1,1]").append(extra).append('}'); + return LevelData.parse(sb.toString()).createWorld(1); + } + + private static final String ROW = ".............................."; + private static final String FLOOR = "##############################"; + + /// A flat 30 x 5 level with the hero spawned on the floor at column 1 and the + /// given extra JSON (entities, abilities, health). + private static PlatformWorld flat(String extra) { + StringBuilder sb = new StringBuilder("{\"tileSize\":16,\"tiles\":["); + for (int i = 0; i < 4; i++) { + LevelJson.quote(sb, ROW); + sb.append(','); + } + LevelJson.quote(sb, FLOOR); + sb.append("],\"spawn\":[1,3]").append(extra).append('}'); + PlatformWorld w = LevelData.parse(sb.toString()).createWorld(1); + run(w, 20, 0); + return w; + } + + private static boolean sawEvent(PlatformWorld w, int ticks, int input, int type) { + boolean seen = false; + for (int i = 0; i < ticks; i++) { + w.step(input); + for (int k = 0; k < w.getEvents().size(); k++) { + seen |= w.getEvents().get(k).getType() == type; + } + } + return seen; + } + + private static void run(PlatformWorld w, int ticks, int input) { + for (int i = 0; i < ticks; i++) { + w.step(input); + } + } + + private static Body hero(PlatformWorld w) { + return w.getPlayer().getBody(); + } + + @Test + void walksUpAndDownSlopesWithoutLeavingTheGround() { + PlatformWorld w = world("", + "....................", + "....................", + "....................", + "....../#\\...........", + "....ab###cd.........", + "####################"); + run(w, 40, 0); + assertTrue(hero(w).isGrounded()); + int startBottom = hero(w).y + hero(w).h; + int airborne = 0; + int highest = startBottom; + for (int i = 0; i < 150; i++) { + w.step(Input.RIGHT); + if (!hero(w).isGrounded()) { + airborne++; + } + highest = Math.min(highest, hero(w).y + hero(w).h); + } + assertEquals(0, airborne, "a walk over a hill never leaves the ground"); + assertTrue(highest <= startBottom - Fx.of(30), "the walk went up the hill"); + assertEquals(startBottom, hero(w).y + hero(w).h, "and back down to the plain"); + } + + @Test + void oneWayPlatformCatchesFromAboveAndDropsThrough() { + PlatformWorld w = world("", + "..........", "..........", "..........", "..====....", "..........", "##########"); + run(w, 30, 0); + run(w, 8, Input.RIGHT); + run(w, 20, 0); + int floor = hero(w).y; + run(w, 15, Input.JUMP); + run(w, 40, 0); + assertTrue(hero(w).isGrounded()); + assertTrue(hero(w).isOnOneWay(), "jumped up through and landed on top"); + assertEquals(Fx.of(48), hero(w).y + hero(w).h); + run(w, 2, Input.JUMP | Input.DOWN); + run(w, 30, 0); + assertEquals(floor, hero(w).y, "down + jump dropped back to the floor"); + } + + @Test + void climbsALadderAndStandsOnItsTop() { + PlatformWorld w = world("", + "..........", "..........", "..====H...", "......H...", "......H...", "##########"); + run(w, 30, 0); + for (int i = 0; i < 200 && hero(w).x < Fx.of(92); i++) { + w.step(Input.RIGHT); + } + run(w, 20, 0); + run(w, 90, Input.UP); + run(w, 20, 0); + assertTrue(hero(w).isGrounded()); + assertEquals(Fx.of(32), hero(w).y + hero(w).h, "standing on the top rung"); + assertEquals(MovementState.IDLE, w.getPlayer().getState()); + run(w, 90, Input.DOWN); + run(w, 5, 0); + assertEquals(Fx.of(80), hero(w).y + hero(w).h, "climbed back down"); + assertEquals(MovementState.IDLE, w.getPlayer().getState(), "let go at the bottom"); + } + + @Test + void movingPlatformCarriesItsRider() { + PlatformWorld w = world(",\"platforms\":[{\"path\":[[0,4],[6,4]],\"w\":4,\"speed\":1}]", + "..........", "..........", "..........", "..........", "..........", + "..........", "..........", ".........."); + run(w, 30, 0); + assertTrue(hero(w).isGrounded()); + assertNotNull(hero(w).getRiding()); + int offset = hero(w).x - w.getPlatforms().get(0).getX(); + run(w, 40, 0); + assertEquals(offset, hero(w).x - w.getPlatforms().get(0).getX(), "no sliding on the platform"); + assertEquals(w.getPlatforms().get(0).getY(), hero(w).y + hero(w).h); + } + + @Test + void clingsToAWallAndJumpsAwayFromIt() { + PlatformWorld w = world("", + "#........#", "#........#", "#........#", "#....#...#", "#....#...#", "#....#...#", + "##########"); + run(w, 30, 0); + run(w, 40, Input.RIGHT); + run(w, 8, Input.RIGHT | Input.JUMP); + run(w, 20, Input.RIGHT); + assertEquals(MovementState.WALL_CLINGING, w.getPlayer().getState()); + assertTrue(hero(w).vy <= Fx.of(1), "a cling slides slowly"); + w.step(Input.RIGHT); + w.step(Input.RIGHT | Input.JUMP); + assertTrue(hero(w).vy < 0); + assertTrue(hero(w).vx < 0, "kicked away from the wall although right is held"); + assertEquals(-1, w.getPlayer().getFacing()); + } + + @Test + void crouchesUnderALowCeilingAndStaysCrouched() { + PlatformWorld w = world("", + "..........", "..........", "...#######", "..........", "##########"); + run(w, 30, 0); + int stand = hero(w).h; + run(w, 80, Input.RIGHT | Input.DOWN); + assertEquals(MovementState.CRAWLING, w.getPlayer().getState()); + assertTrue(hero(w).h < stand); + run(w, 5, Input.RIGHT); + assertTrue(hero(w).h < stand, "cannot stand up under the ceiling"); + } + + @Test + void coyoteTimeAllowsALateJump() { + PlatformWorld w = world("", + "..........", "..........", "####......", "..........", "..........", "##########"); + run(w, 30, 0); + for (int i = 0; i < 200 && hero(w).isGrounded(); i++) { + w.step(Input.RIGHT); + } + run(w, 3, Input.RIGHT); + w.step(Input.RIGHT | Input.JUMP); + assertTrue(hero(w).vy < -Fx.of(4), "jumped four ticks after leaving the ledge"); + } + + @Test + void bufferedJumpFiresOnLanding() { + PlatformWorld w = world("", "..........", "..........", "..........", "..........", "##########"); + for (int i = 0; i < 200 && hero(w).y + hero(w).h < Fx.of(56); i++) { + w.step(0); + } + assertFalse(hero(w).isGrounded()); + w.step(Input.JUMP); + boolean jumped = false; + for (int i = 0; i < 6 && !jumped; i++) { + w.step(Input.JUMP); + jumped = hero(w).vy < 0; + } + assertTrue(jumped, "the press before landing jumped on landing"); + } + + @Test + void dashMovesFastWithoutFalling() { + PlatformWorld w = world("", "....................", "....................", "....................", + "....................", "####################"); + run(w, 30, 0); + run(w, 10, Input.JUMP); + int y = hero(w).y; + int x = hero(w).x; + w.step(Input.RIGHT | Input.DASH); + run(w, 5, Input.RIGHT | Input.DASH); + assertEquals(MovementState.DASHING, w.getPlayer().getState()); + assertEquals(y, hero(w).y, "no gravity mid dash"); + assertEquals(x + Fx.of(30), hero(w).x); + } + + @Test + void hazardsAndFallsRespawnThePlayer() { + PlatformWorld w = world("", "..........", "..........", "..........", "##^^######"); + run(w, 30, 0); + for (int i = 0; i < 60 && w.getDeaths() == 0; i++) { + w.step(Input.RIGHT); + } + assertEquals(1, w.getDeaths()); + assertEquals(w.getSpawnX(), hero(w).x, "back at the spawn point"); + } + + @Test + void replayReproducesTheLiveRunExactly() { + String lvl = "{\"tileSize\":16,\"tiles\":[\"#..........#\",\"#....====..#\",\"#...........#\"," + + "\"#..H.......#\",\"############\"],\"spawn\":[1,3],\"goal\":[10,1,1,1]," + + "\"platforms\":[{\"path\":[[5,3],[8,3]],\"w\":1,\"speed\":0.5,\"pause\":20}]}"; + LevelData ld = LevelData.parse(lvl); + PlatformWorld live = ld.createWorld(7); + InputLog log = new InputLog(); + for (int i = 0; i < 600 && !live.isComplete(); i++) { + int phase = (i / 37) % 3; + int in = phase == 0 ? Input.RIGHT : phase == 1 ? Input.LEFT | Input.RUN : Input.RIGHT | Input.DASH; + if (i % 23 < 5) { + in |= Input.JUMP; + } + log.add(in); + live.step(in); + } + assertTrue(live.isComplete()); + Replay.Result r = Replay.run(ld, 7, InputLog.decode(log.encode(), 100000)); + assertTrue(r.isComplete()); + assertEquals(live.getTick(), r.getTicks()); + assertEquals(live.hash(), r.getHash()); + // Golden: a change to this number is a change to how every recorded run plays. + // Bump the rules version of any game that stores runs when it moves. + assertEquals(0x7f68405691d581e0L, r.getHash()); + } + + @Test + void coinsScoreAndDisappear() { + PlatformWorld w = flat(",\"entities\":[{\"type\":\"coin\",\"at\":[3,3]}," + + "{\"type\":\"gem\",\"at\":[5,3]}]"); + assertTrue(sawEvent(w, 60, Input.RIGHT, WorldEvent.PICKUP)); + assertEquals(1, w.getCoins()); + assertEquals(110, w.getScore()); + assertEquals(1, w.getSecrets()); + assertTrue(w.getEntities().isEmpty()); + } + + @Test + void touchingAnEnemyHurtsButStompingKillsIt() { + PlatformWorld w = flat(",\"entities\":[{\"type\":\"enemy\",\"at\":[12,3]}]"); + run(w, 150, Input.RIGHT); + assertTrue(w.getDeaths() >= 1, "walking into a slime kills a hero with no health"); + + w = flat(",\"entities\":[{\"type\":\"enemy\",\"kind\":\"slime\",\"at\":[6,3],\"brain\":\"walker\"}]"); + Actor slime = w.getActors().get(1); + boolean stomped = false; + for (int i = 0; i < 200 && slime.isAlive(); i++) { + Body s = slime.getBody(); + Body h = hero(w); + int dx = s.x - h.x; + int in = dx > Fx.of(20) ? Input.RIGHT : dx < -Fx.of(20) ? Input.LEFT : 0; + if (Math.abs(dx) < Fx.of(40) && h.isGrounded()) { + in |= Input.JUMP; + } + w.step(in); + for (int k = 0; k < w.getEvents().size(); k++) { + stomped |= w.getEvents().get(k).getType() == WorldEvent.STOMP; + } + } + assertTrue(stomped); + assertFalse(slime.isAlive()); + assertEquals(0, w.getDeaths()); + } + + @Test + void aKeyOpensItsDoor() { + PlatformWorld w = flat(",\"entities\":[{\"type\":\"door\",\"at\":[8,2],\"key\":\"red\"}]"); + run(w, 120, Input.RIGHT); + assertTrue(hero(w).x < Fx.of(8 * 16), "a locked door blocks"); + w = flat(",\"entities\":[{\"type\":\"key\",\"at\":[3,3],\"name\":\"red\"}," + + "{\"type\":\"door\",\"at\":[8,2],\"key\":\"red\"}]"); + run(w, 120, Input.RIGHT); + assertTrue(hero(w).x > Fx.of(9 * 16), "the key opened it"); + assertTrue(w.getKeys().isEmpty(), "and was used up"); + } + + @Test + void springsLaunchHigherThanAJump() { + PlatformWorld w = flat(",\"entities\":[{\"type\":\"spring\",\"at\":[4,3]}]"); + int top = Integer.MAX_VALUE; + for (int i = 0; i < 60; i++) { + w.step(Input.RIGHT); + top = Math.min(top, hero(w).y); + } + assertTrue(top < 0, "launched off the top of the screen"); + } + + @Test + void crumblingFloorGivesWay() { + PlatformWorld w = world(",\"entities\":[{\"type\":\"crumble\",\"at\":[2,4],\"w\":3,\"delay\":20," + + "\"respawn\":0}]", "..........", "..........", "..........", "..........", "##......##", + "##########"); + run(w, 20, 0); + assertTrue(sawEvent(w, 30, Input.RIGHT, WorldEvent.CRUMBLE) || sawEvent(w, 40, 0, WorldEvent.CRUMBLE)); + run(w, 30, 0); + assertEquals(Fx.of(80), hero(w).y + hero(w).h, "fell to the floor below"); + } + + @Test + void aLeverOpensItsGate() { + String gate = "{\"type\":\"gate\",\"at\":[7,2],\"h\":2,\"channel\":2}"; + PlatformWorld w = flat(",\"entities\":[" + gate + "]"); + run(w, 90, Input.RIGHT); + assertTrue(hero(w).x < Fx.of(7 * 16)); + w = flat(",\"entities\":[{\"type\":\"lever\",\"at\":[2,3],\"channel\":2}," + gate + "]"); + run(w, 8, Input.RIGHT); + w.step(Input.ACTIVATE); + assertTrue(w.isChannelOn(2)); + run(w, 90, Input.RIGHT); + assertTrue(hero(w).x > Fx.of(8 * 16)); + } + + @Test + void shotsKillAnEnemyWithHitPoints() { + PlatformWorld w = flat(",\"abilities\":[\"move\",\"jump\",\"weapon\"]," + + "\"entities\":[{\"type\":\"enemy\",\"at\":[10,3],\"brain\":\"turret\",\"hp\":2,\"range\":3}]"); + Actor turret = w.getActors().get(1); + for (int i = 0; i < 120 && turret.isAlive(); i++) { + w.step(i % 16 == 0 ? Input.FIRE : 0); + } + assertFalse(turret.isAlive()); + } + + @Test + void healthAbsorbsHitsWithInvulnerability() { + PlatformWorld w = flat(",\"health\":3,\"entities\":[{\"type\":\"enemy\",\"at\":[8,3]," + + "\"brain\":\"turret\",\"range\":10,\"interval\":40}]"); + assertTrue(sawEvent(w, 80, 0, WorldEvent.HURT)); + assertEquals(2, w.getPlayer().getHealth().getCurrent()); + assertTrue(w.getPlayer().getHealth().isInvulnerable() || w.getPlayer().getHealth().getCurrent() < 3); + } + + @Test + void runningOutOfLivesEndsTheGame() { + PlatformWorld w = world(",\"lives\":2", ROW, ROW, ROW, "##^^^^^^^^^^^^^^^^^^^^^^^^^^##"); + run(w, 300, Input.RIGHT); + assertTrue(w.isGameOver()); + assertEquals(0, w.getLives()); + assertEquals(2, w.getDeaths()); + } + + @Test + void jetpackSwimAndPowerUps() { + PlatformWorld w = world(",\"abilities\":[\"move\",\"jump\",\"jetpack\"]", ROW, ROW, ROW, ROW, ROW, FLOOR); + run(w, 30, 0); + int floorY = hero(w).y; + w.step(Input.JUMP); + run(w, 40, Input.JUMP | Input.ALT); + assertEquals(MovementState.JETPACKING, w.getPlayer().getState()); + assertTrue(hero(w).y < floorY - Fx.of(48)); + + w = world(",\"abilities\":[\"move\",\"swim\",\"jump\"]", ROW, ROW, ROW, + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", FLOOR); + run(w, 60, 0); + assertEquals(MovementState.SWIMMING, w.getPlayer().getState()); + + w = flat(",\"abilities\":[\"move\",\"jump\"],\"entities\":[{\"type\":\"powerup\",\"at\":[3,3]," + + "\"name\":\"dash\"}]"); + assertNull(w.getPlayer().getAbility(DashAbility.class)); + run(w, 40, Input.RIGHT); + assertNotNull(w.getPlayer().getAbility(DashAbility.class), "the power-up granted the dash"); + } + + @Test + void enemiesAndBossesReplayDeterministically() { + String lvl = "{\"tileSize\":16,\"tiles\":[\"" + ROW + "\",\"" + ROW + "\",\"" + ROW + "\",\"" + ROW + + "\",\"" + FLOOR + "\"],\"spawn\":[1,3],\"health\":3,\"entities\":[" + + "{\"type\":\"enemy\",\"at\":[12,3],\"brain\":\"boss\",\"hp\":4}," + + "{\"type\":\"enemy\",\"at\":[20,1],\"brain\":\"flyer\"}," + + "{\"type\":\"coin\",\"at\":[5,3]}],\"abilities\":[\"move\",\"jump\",\"weapon\"]}"; + PlatformWorld a = LevelData.parse(lvl).createWorld(3); + PlatformWorld b = LevelData.parse(lvl).createWorld(3); + for (int i = 0; i < 900; i++) { + int in = (i % 30 < 4 ? Input.FIRE : 0) | ((i / 60) % 2 == 0 ? Input.RIGHT : Input.LEFT) + | (i % 45 == 0 ? Input.JUMP : 0); + a.step(in); + b.step(in); + } + assertEquals(a.hash(), b.hash()); + assertFalse(a.getActors().get(1).isAlive(), "the boss went down"); + } + + @Test + void levelsOutsideTheLimitsAreRejected() { + String[] bad = { + "{\"tileSize\":0,\"tiles\":[\"..\"]}", + "{\"tileSize\":1000,\"tiles\":[\"..\"]}", + "{\"tiles\":[]}", + "{\"tiles\":[\"..\", 3]}", + "{\"tiles\":[\"" + repeat('.', 5000) + "\"]}", + "{\"tiles\":[\"..\"],\"entities\":[{\"type\":\"coin\",\"at\":[99,0]}]}", + "{\"tiles\":[\"..\"],\"entities\":[{\"type\":\"coin\",\"at\":[-1,0]}]}", + "{\"tiles\":[\"..\"],\"entities\":[{\"type\":\"crumble\",\"at\":[0,0],\"delay\":-5}]}", + "{\"tiles\":[\"..\"],\"platforms\":[{\"path\":[[0,0],[1,0]],\"speed\":0}]}", + "{\"tiles\":[\"..\"],\"platforms\":[{\"path\":[[0,0],[1,0]],\"speed\":-1}]}", + "{\"tiles\":[\"..\"],\"platforms\":[{\"path\":[[0,0],[50,0]]}]}", + "[1,2]", + }; + for (int i = 0; i < bad.length; i++) { + try { + LevelData.parse(bad[i]).createWorld(1); + fail("accepted " + bad[i]); + } catch (IllegalArgumentException expected) { + // rejected as it should be + } + } + } + + @Test + void zeroDivisorsThrowInsteadOfCrashing() { + assertThrows(ArithmeticException.class, () -> Fx.div(Fx.ONE, 0)); + assertThrows(ArithmeticException.class, () -> Fx.ratio(1, 0)); + assertThrows(ArithmeticException.class, () -> Fx.floorDiv(1, 0)); + assertThrows(IllegalArgumentException.class, () -> new Rng(1).nextInt(0)); + } + + private static String repeat(char c, int n) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + sb.append(c); + } + return sb.toString(); + } + + @Test + void inputLogRejectsHostileText() { + assertThrows(IllegalArgumentException.class, () -> InputLog.decode("1*ffffff", 1000)); + assertThrows(IllegalArgumentException.class, () -> InputLog.decode("ffff*1", 1000)); + assertThrows(IllegalArgumentException.class, () -> InputLog.decode("1*", 1000)); + assertEquals(3, InputLog.decode("1*2,0*1", 1000).length()); + } + + @Test + void fixedPointParsesExactly() { + assertEquals(Fx.of(1) + Fx.HALF, Fx.parse("1.5")); + assertEquals(-Fx.ratio(1, 4), Fx.parse("-0.25")); + assertEquals("2.75", Fx.format(Fx.parse("2.75"))); + assertEquals(-1, Fx.floorDiv(-1, 16)); + assertEquals(0, Fx.floorDiv(15, 16)); + assertThrows(IllegalArgumentException.class, () -> Fx.parse("1e3")); + } + + @Test + void tileGridRoundTripsItsText() { + String[] rows = {"#./\\abcd#", "=H^~....#"}; + assertArrayEquals(rows, TileGrid.parse(rows, 16).toLines()); + assertThrows(IllegalArgumentException.class, () -> TileGrid.parse(new String[] {"#X#"}, 16)); + } +} diff --git a/maven/core-unittests/src/test/java/com/codename1/gaming/platformer/view/PlatformViewLogicTest.java b/maven/core-unittests/src/test/java/com/codename1/gaming/platformer/view/PlatformViewLogicTest.java new file mode 100644 index 00000000000..c50207b8c87 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/gaming/platformer/view/PlatformViewLogicTest.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2012, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codename1.gaming.platformer.view; + +import com.codename1.gaming.platformer.MovementState; +import com.codename1.gaming.platformer.WorldEvent; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class PlatformViewLogicTest { + + @Test + void cameraStaysStillInsideTheDeadZoneAndFollowsOutsideIt() { + PlatformCamera cam = new PlatformCamera(); + cam.setViewSize(200, 100); + cam.setBounds(0, 0, 2000, 500); + cam.setLookAhead(0); + cam.setSmoothing(0); + cam.snapTo(500, 250); + double x0 = cam.getX(); + cam.update(505, 250, 1, 1 / 60.0); + assertEquals(x0, cam.getX(), 1e-9, "inside the dead zone"); + cam.update(700, 250, 1, 1 / 60.0); + assertTrue(cam.getX() > x0 + 150, "followed out of the dead zone"); + } + + @Test + void cameraNeverLeavesTheLevel() { + PlatformCamera cam = new PlatformCamera(); + cam.setViewSize(200, 100); + cam.setBounds(0, 0, 1000, 300); + cam.snapTo(5, 5); + assertEquals(0, cam.getX(), 1e-9); + assertEquals(0, cam.getY(), 1e-9); + cam.snapTo(5000, 5000); + assertEquals(800, cam.getX(), 1e-9); + assertEquals(200, cam.getY(), 1e-9); + cam.setBounds(0, 0, 100, 50); + cam.snapTo(0, 0); + assertEquals(-50, cam.getX(), 1e-9, "a level smaller than the view is centered"); + } + + @Test + void shakeFadesOut() { + PlatformCamera cam = new PlatformCamera(); + cam.setViewSize(200, 100); + cam.setBounds(-10000, -10000, 10000, 10000); + cam.setSmoothing(0); + cam.setLookAhead(0); + cam.snapTo(0, 0); + double base = cam.getX(); + cam.shake(10, 0.5); + boolean moved = false; + for (int i = 0; i < 10; i++) { + cam.update(0, 0, 1, 1 / 60.0); + moved |= Math.abs(cam.getX() - base) > 0.01; + } + assertTrue(moved); + for (int i = 0; i < 60; i++) { + cam.update(0, 0, 1, 1 / 60.0); + } + assertEquals(base, cam.getX(), 1e-9); + } + + @Test + void animatorBorrowsRelatedClips() { + ActorAnimator a = new ActorAnimator() + .set(MovementState.IDLE, 10, true, 0, 1) + .set(MovementState.WALKING, 5, true, 2, 3, 4) + .set(MovementState.JUMPING, 1, false, 7); + ActorAnimator.Track t = new ActorAnimator.Track(); + t.tick(MovementState.RUNNING); + assertEquals(2, a.frameFor(t), "running borrows walking"); + for (int i = 0; i < 5; i++) { + t.tick(MovementState.RUNNING); + } + assertEquals(3, a.frameFor(t)); + t.tick(MovementState.GLIDING); + assertEquals(7, a.frameFor(t), "gliding borrows jumping"); + t.tick(MovementState.SWIMMING); + assertEquals(7, a.frameFor(t), "swimming -> falling -> jumping"); + t.tick(MovementState.CROUCHING); + assertEquals(0, a.frameFor(t), "crouching falls back to idle"); + for (MovementState s : MovementState.values()) { + assertNotNull(a.clipFor(s), s.name()); + } + } + + @Test + void nonLoopingClipsHoldTheLastFrame() { + ActorAnimator.Clip c = new ActorAnimator.Clip(new int[] {4, 5, 6}, 2, false); + assertEquals(4, c.frameAt(0)); + assertEquals(6, c.frameAt(100)); + ActorAnimator.Clip l = new ActorAnimator.Clip(new int[] {4, 5, 6}, 2, true); + assertEquals(4, l.frameAt(6)); + } + + @Test + void feedbackPlaysSoundsAndShakesOnlyForThePlayer() { + final List played = new ArrayList(); + Feedback.Sink sink = new Feedback.Sink() { + @Override + public void sound(String name, double x, double y) { + played.add(name); + } + + @Override + public void burst(double x, double y, int count, int color) { + played.add("burst" + count); + } + }; + Feedback f = new Feedback(); + PlatformCamera cam = new PlatformCamera(); + cam.setViewSize(100, 100); + cam.setBounds(-1000, -1000, 1000, 1000); + cam.setSmoothing(0); + cam.snapTo(0, 0); + f.react(new WorldEvent(WorldEvent.HURT, 0, 0, "slime", null), false, cam, sink); + assertEquals(0, f.getFlash(), "an enemy's hurt does not flash"); + f.react(new WorldEvent(WorldEvent.HURT, 0, 0, "hero", null), true, cam, sink); + assertTrue(played.contains("hurt")); + assertNotEquals(0, f.getFlash()); + f.update(1); + assertEquals(0, f.getFlash(), "faded"); + f.setIntensity(0); + f.react(new WorldEvent(WorldEvent.COMPLETE, 0, 0, "hero", null), true, cam, sink); + assertEquals(0, f.getFlash(), "reduce motion"); + assertTrue(played.contains("complete"), "sound still plays"); + } +} diff --git a/scripts/check-copyright-headers.sh b/scripts/check-copyright-headers.sh index be32b90b0bf..269de6ec048 100755 --- a/scripts/check-copyright-headers.sh +++ b/scripts/check-copyright-headers.sh @@ -38,11 +38,11 @@ is_excluded() { local candidate="$1" # What Initializr puts into a generated project is the developer's, not # Codename One's GPLv2 + Classpath Exception source: these trees are released - # under MIT No Attribution (scripts/wayline/LICENSE, scripts/savor/LICENSE, scripts/bazaar/LICENSE, scripts/skirmish/LICENSE, scripts/dash/LICENSE, scripts/parley/LICENSE, scripts/pulse/LICENSE, scripts/slate/LICENSE, scripts/splat/LICENSE, scripts/papercut/LICENSE, scripts/fieldline/LICENSE, scripts/brickyard/LICENSE, + # under MIT No Attribution (scripts/wayline/LICENSE, scripts/savor/LICENSE, scripts/bazaar/LICENSE, scripts/skirmish/LICENSE, scripts/dash/LICENSE, scripts/parley/LICENSE, scripts/pulse/LICENSE, scripts/slate/LICENSE, scripts/splat/LICENSE, scripts/papercut/LICENSE, scripts/ledge/LICENSE, scripts/fieldline/LICENSE, scripts/brickyard/LICENSE, # scripts/bastion/LICENSE, scripts/reel/LICENSE), and carry that header # or none. case "$candidate" in - scripts/wayline/*|scripts/savor/*|scripts/bazaar/*|scripts/skirmish/*|scripts/dash/*|scripts/parley/*|scripts/bastion/*|scripts/reel/*|scripts/pulse/*|scripts/slate/*|scripts/splat/*|scripts/papercut/*|scripts/fieldline/*|scripts/brickyard/*|maven/cn1app-archetype/src/main/resources/archetype-resources/*|scripts/initializr/common/src/main/resources/skill/*) return 0 ;; + scripts/wayline/*|scripts/savor/*|scripts/bazaar/*|scripts/skirmish/*|scripts/dash/*|scripts/parley/*|scripts/bastion/*|scripts/reel/*|scripts/pulse/*|scripts/slate/*|scripts/splat/*|scripts/papercut/*|scripts/ledge/*|scripts/fieldline/*|scripts/brickyard/*|maven/cn1app-archetype/src/main/resources/archetype-resources/*|scripts/initializr/common/src/main/resources/skill/*) return 0 ;; esac # Design Import's gallery is the tool's own output, regenerated by ExamplesTest: a form, # a stylesheet and a test written for whoever runs the tool, which carry no header by diff --git a/scripts/developer-guide/check-guide-api-names.py b/scripts/developer-guide/check-guide-api-names.py index cc6eb47317a..06703210ca6 100755 --- a/scripts/developer-guide/check-guide-api-names.py +++ b/scripts/developer-guide/check-guide-api-names.py @@ -92,6 +92,7 @@ os.path.join('scripts', 'dash'), os.path.join('scripts', 'splat'), os.path.join('scripts', 'papercut'), + os.path.join('scripts', 'ledge'), os.path.join('scripts', 'fieldline'), os.path.join('scripts', 'bazaar'))] # '.py' because the Python support ships real Python packages under maven/ diff --git a/scripts/developer-guide/validate-guide-snippets.py b/scripts/developer-guide/validate-guide-snippets.py index 84c9e5d6d36..263a851c547 100755 --- a/scripts/developer-guide/validate-guide-snippets.py +++ b/scripts/developer-guide/validate-guide-snippets.py @@ -15,7 +15,7 @@ LISTING_DELIMITER_RE = re.compile(r"^-{4,}\s*$") TAG_BLOCK_RE = re.compile(r"// tag::([^\[]+)\[\]\n(.*?)\n// end::\1\[\]", re.S) JAVA_IDENTIFIER_RE = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]*\.java$") -INCLUDE_ROOTS = ("../demos/", "../../scripts/wayline/", "../../scripts/savor/", "../../scripts/bazaar/", "../../scripts/skirmish/", "../../scripts/dash/", "../../scripts/parley/", "../../scripts/reel/", "../../scripts/slate/", "../../scripts/splat/", "../../scripts/papercut/", "../../scripts/hellocodenameone/", "../../maven/cn1-app-kit/") +INCLUDE_ROOTS = ("../demos/", "../../scripts/wayline/", "../../scripts/savor/", "../../scripts/bazaar/", "../../scripts/skirmish/", "../../scripts/ledge/", "../../scripts/dash/", "../../scripts/parley/", "../../scripts/reel/", "../../scripts/slate/", "../../scripts/splat/", "../../scripts/papercut/", "../../scripts/hellocodenameone/", "../../maven/cn1-app-kit/") def parse_args(): diff --git a/scripts/initializr/agent-cli/src/com/codename1/initializr/model/CreateProject.java b/scripts/initializr/agent-cli/src/com/codename1/initializr/model/CreateProject.java index 9af43197024..68ca709f578 100644 --- a/scripts/initializr/agent-cli/src/com/codename1/initializr/model/CreateProject.java +++ b/scripts/initializr/agent-cli/src/com/codename1/initializr/model/CreateProject.java @@ -72,6 +72,7 @@ private static String describe(Template t) { case DASH: return "Endless runner game."; case SPLAT: return "3D first-person team paintball shooter with authoritative server, voice and replays."; case PAPERCUT: return "Twin-stick arena shooter in cut paper and ink, with leaderboards, daily seed and shop."; + case LEDGE: return "2D/2.5D platformer with replay-verified leaderboards, ghosts, a level editor and AI-generated levels."; case PARLEY: return "End-to-end encrypted messaging: chats, groups, WebRTC calls, Java backend."; case BASTION: return "Mobile banking: accounts, transfers, cards, biometric sign-in, security showcase, Java backend."; case REEL: return "Video streaming: catalogue, player, downloads, DRM, profiles, Java backend."; diff --git a/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java b/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java index e6bf43d9d3d..5a472a5a5d8 100644 --- a/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java +++ b/scripts/initializr/common/src/main/java/com/codename1/initializr/Initializr.java @@ -467,7 +467,7 @@ private Container createLanguageSelector(Template[] selectedTemplate, Runnable o if (!GeneratorModel.isTemplateOffered(Template.WAYLINE)) { return empty; } - Template[] apps = {Template.WAYLINE, Template.SAVOR, Template.BAZAAR, Template.SKIRMISH, Template.DASH, Template.SPLAT, Template.PAPERCUT, Template.PARLEY, + Template[] apps = {Template.WAYLINE, Template.SAVOR, Template.BAZAAR, Template.SKIRMISH, Template.DASH, Template.SPLAT, Template.PAPERCUT, Template.LEDGE, Template.PARLEY, Template.BASTION, Template.REEL, Template.PULSE, Template.SLATE, Template.FIELDLINE}; int offered = 0; @@ -514,6 +514,7 @@ static String templateTitle(Template template) { : template == Template.DASH ? "Endless runner" : template == Template.SPLAT ? "Paintball shooter" : template == Template.PAPERCUT ? "Arena shooter" + : template == Template.LEDGE ? "Platformer" : template == Template.PARLEY ? "Messaging" : template == Template.WAYLINE ? "Ride hailing" : template == Template.BASTION ? "Banking" : template == Template.REEL ? "Video streaming" diff --git a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java index f45a7215cec..019ca217585 100644 --- a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java +++ b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/GeneratorModel.java @@ -96,6 +96,11 @@ public static boolean isMavenLayoutChoiceOffered() { /// addition, so it is neither offered nor generated before then. static final String PAPERCUT_SINCE = "7.0.284"; + /// The first release whose build plugin and core carry everything the platformer + /// template is built on. It is gated on the release that follows its addition, so it + /// is neither offered nor generated before then. + static final String LEDGE_SINCE = "7.0.286"; + /// The first release whose framework has what the banking template's app calls: /// timed clipboard clearing, the P-256 key and signature API it signs requests /// with, and the `BigDecimal` arithmetic its ledger rounds with. Against an @@ -134,6 +139,7 @@ static String templateSince(Template template) { : template == Template.REEL ? REEL_SINCE : template == Template.SPLAT ? SPLAT_SINCE : template == Template.PAPERCUT ? PAPERCUT_SINCE + : template == Template.LEDGE ? LEDGE_SINCE : template == Template.SLATE ? SLATE_SINCE : template == Template.FIELDLINE ? FIELDLINE_SINCE : template == Template.BAZAAR ? BAZAAR_SINCE : JAVA_TIME_ENTITIES_SINCE; @@ -162,6 +168,9 @@ static String templateSince(Template template) { /// The arena shooter template's accent, used for its icon: it has no `--brand`. public static final int PAPERCUT_BRAND = 0x2b3a67; + /// The platformer template's accent, used for its icon: it has no `--brand`. + public static final int LEDGE_BRAND = 0xff7648; + /// The messaging template's `--brand`, held to its theme.css the same way. public static final int PARLEY_BRAND = 0x0a7d6b; @@ -208,7 +217,8 @@ public static int brandOf(Template template) { : template == Template.SKIRMISH ? SKIRMISH_BRAND : template == Template.DASH ? DASH_BRAND : template == Template.SPLAT ? SPLAT_BRAND - : template == Template.PAPERCUT ? PAPERCUT_BRAND : FULL_STACK_BRAND; + : template == Template.PAPERCUT ? PAPERCUT_BRAND + : template == Template.LEDGE ? LEDGE_BRAND : FULL_STACK_BRAND; } /// Whether `template` can be generated at [CN1_PLUGIN_VERSION]: the UI offers @@ -2181,6 +2191,21 @@ private String buildReadmeMarkdown() { .append("On Windows: `run-server.bat`, then `run.bat`. Your IDE's run menu has both: ") .append("\"Run Server\" and the simulator.\n\n") .append("`./mvnw -pl backend -am -Dcodename1.platform=backend test` runs the server's tests.\n\n"); + } else if (template == Template.LEDGE) { + out.append("## The game and its server\n\n") + .append("This project is a working platformer: hand-made and AI-generated levels, a level editor, ") + .append("leaderboards whose runs the server replays to verify, ghosts, daily seeds, a shop, ") + .append("achievements and an admin console, and the server they talk to.\n\n") + .append("- `shared/` is the contract and the levels: the REST interfaces, the objects they carry, ") + .append("and the level format the app plays and the server replays.\n") + .append("- `backend/` is the server.\n") + .append("- `common/` is the app, and the game.\n\n") + .append("Start the server, then, in a second terminal, the app:\n\n```\n") + .append("./run-server.sh\n") + .append("./run.sh\n```\n\n") + .append("On Windows: `run-server.bat`, then `run.bat`. Your IDE's run menu has both: ") + .append("\"Run Server\" and the simulator.\n\n") + .append("`./mvnw -pl backend -am -Dcodename1.platform=backend test` runs the server's tests.\n\n"); } else if (template == Template.SKIRMISH) { out.append("## The game and its server\n\n") .append("This project is a working real-time card battler: a 3D arena, matchmaking, replays, ") diff --git a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java index e393a777625..c61ddc040e7 100644 --- a/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java +++ b/scripts/initializr/common/src/main/java/com/codename1/initializr/model/Template.java @@ -111,6 +111,16 @@ public enum Template { "The arena shooter template is an app, a server and the contract module they share; " + "an Initializr Gradle project is a single project.", new String[0], "/papercut-modules.zip", "/papercut-settings.properties"), + // A platformer with a level editor, AI-generated and solver-proven levels, ghosts + // and leaderboards whose runs the server replays. It is the project in + // scripts/ledge; its resources come from + // `scripts/sync-initializr-template.py ledge`. Its look is drawn art, so it has + // no colour scheme to choose. + LEDGE(false, "/ledge-src.zip", "/ledge-css.zip", "/ledge-pom.xml", + "com.codenameone.examples.ledge", "Ledge", "/ledge-preview.jpg", + "The platformer template is an app, a server and the contract module they share; " + + "an Initializr Gradle project is a single project.", + new String[0], "/ledge-modules.zip", "/ledge-settings.properties"), // The same kind of template as WAYLINE: an end-to-end encrypted messaging app // (chats, groups, media, calls) and its server. It is the project in // scripts/parley, and its resources come from @@ -220,7 +230,7 @@ public boolean isFullStack() { /// Whether the developer can choose a colour scheme for the template: false for /// one whose look is art and not a palette its stylesheet declares. public boolean hasColorScheme() { - return this != SKIRMISH && this != DASH && this != SPLAT && this != PAPERCUT; + return this != SKIRMISH && this != DASH && this != SPLAT && this != PAPERCUT && this != LEDGE; } public boolean supportsGradle() { diff --git a/scripts/initializr/common/src/main/resources/ledge-css.zip b/scripts/initializr/common/src/main/resources/ledge-css.zip new file mode 100644 index 00000000000..51b5fb73864 Binary files /dev/null and b/scripts/initializr/common/src/main/resources/ledge-css.zip differ diff --git a/scripts/initializr/common/src/main/resources/ledge-modules.zip b/scripts/initializr/common/src/main/resources/ledge-modules.zip new file mode 100644 index 00000000000..11f4e352988 Binary files /dev/null and b/scripts/initializr/common/src/main/resources/ledge-modules.zip differ diff --git a/scripts/initializr/common/src/main/resources/ledge-pom.xml b/scripts/initializr/common/src/main/resources/ledge-pom.xml new file mode 100644 index 00000000000..aef41e0be1f --- /dev/null +++ b/scripts/initializr/common/src/main/resources/ledge-pom.xml @@ -0,0 +1,422 @@ + + + 4.0.0 + + com.example.myapp + myappname + 1.0-SNAPSHOT + + com.example.myapp + myappname-common + 1.0-SNAPSHOT + jar + + + + + + ${project.groupId} + myappname-shared + ${project.version} + + + + com.codenameone + cn1-app-kit-lib + ${cn1.version} + pom + + + com.codenameone + codenameone-core + + + com.codenameone + codenameone-javase + test + + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + + + + + + + + + install-codenameone + ${user.home}/.codenameone/guibuilder.jar + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + validate + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + kotlin + + + + ${basedir}/src/main/kotlin + + + + 2.2.10 + true + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + + + + org.jetbrains + annotations + 13.0 + + + com.codenameone + java-runtime + provided + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + + -no-reflect + -no-jdk + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + + -no-reflect + -no-jdk + + + + + + + + + + + + + javase + + + codename1.platform + javase + + + + javase + + + + + org.codehaus.mojo + exec-maven-plugin + + java + true + + -Xmx1024M + + -classpath + + ${exec.mainClass} + ${cn1.mainClass} + + + + + + + + + + simulator + + javase + + + + + + ios-debug + + + iphone + + + ios + + + + + ios-release + + + iphone + true + + + ios + true + + + + + javascript + + javascript + javascript + + + + + android + + android + android + + + + + windows + + desktop_windows + javase + + + + + mac + + desktop_macosx + javase + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + + com.codenameone + codenameone-maven-plugin + + + xalan + serializer + 2.7.3 + + + + + + generate-gui-sources + process-sources + + generate-gui-sources + + + + cn1-process-classes + process-classes + + bytecode-compliance + css + + process-annotations + + + + + attach-test-artifact + test + + attach-test-artifact + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + + + + diff --git a/scripts/initializr/common/src/main/resources/ledge-preview.jpg b/scripts/initializr/common/src/main/resources/ledge-preview.jpg new file mode 100644 index 00000000000..dfd99179a85 Binary files /dev/null and b/scripts/initializr/common/src/main/resources/ledge-preview.jpg differ diff --git a/scripts/initializr/common/src/main/resources/ledge-settings.properties b/scripts/initializr/common/src/main/resources/ledge-settings.properties new file mode 100644 index 00000000000..4b769069794 --- /dev/null +++ b/scripts/initializr/common/src/main/resources/ledge-settings.properties @@ -0,0 +1,21 @@ +# A server started on this machine is reached over plain HTTP, which Android +# refuses by default. Remove this once the game talks to a server with a +# certificate. +codename1.arg.android.xapplication_attr=android\:usesCleartextTraffic\="true" +# Push notifications: the daily sheet, a beaten score, flags for an admin. +codename1.arg.ios.includePush=true +# myappname://daily opens today's sheet. +codename1.arg.ios.urlScheme=myappname +codename1.arg.android.xintent_filter= +# Android push is off until the game has its Firebase file: a build that +# uses PushClient without google-services.json stops with an error. Once +# native/android/google-services.json is in place, delete this line. +codename1.arg.android.messagingService=none +# The shop sells through Google Play, and an Android build that uses in-app +# purchase needs the app's licensing key. This is a placeholder that builds +# but verifies nothing: paste the Base64 RSA public key from the Play +# Console's "Monetization setup" before release. +codename1.arg.android.licenseKey=CN1TESTPLACEHOLDERKEYNOTFORPRODUCTIONxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxIDAQAB +# A twin-stick arena is played in landscape, a thumb on each side. +codename1.arg.android.xactivity=android:screenOrientation="sensorLandscape" +codename1.arg.ios.interface_orientation=UIInterfaceOrientationLandscapeLeft:UIInterfaceOrientationLandscapeRight diff --git a/scripts/initializr/common/src/main/resources/ledge-src.zip b/scripts/initializr/common/src/main/resources/ledge-src.zip new file mode 100644 index 00000000000..7095db27dec Binary files /dev/null and b/scripts/initializr/common/src/main/resources/ledge-src.zip differ diff --git a/scripts/initializr/common/src/main/resources/skill/SKILL.md b/scripts/initializr/common/src/main/resources/skill/SKILL.md index 779c4444eb7..1cc38dafd91 100644 --- a/scripts/initializr/common/src/main/resources/skill/SKILL.md +++ b/scripts/initializr/common/src/main/resources/skill/SKILL.md @@ -47,6 +47,9 @@ This skill teaches you how to write code for a Codename One (CN1) cross-platform - `references/ai-and-speech.md` — LLM client (`com.codename1.ai`), built-in vision/LiteRT/language APIs, `ChatView`, `SpeechRecognizer`, `TextToSpeech`, non-prompting `SecureStorage` overloads, and the simulator's offline Ollama redirect. Read this when the user asks for chat, voice, embeddings, image generation, barcode/document/face detection, or wants to store an LLM API key. - `references/printing.md` — Cross-platform printing (`com.codename1.printing`): `Printer.printPDF` / `printImage` / `print`, the `PrintResult` outcome, and per-platform caveats (iOS AirPrint, Android, desktop, native Windows, web). Read this when the user wants to print a document, report, image, or the current screen. - `references/games.md` — Game development (`com.codename1.gaming`): the `GameView` update loop, `Sprite` / `AnimatedSprite` / `SpriteSheet`, pollable `GameInput`, `TouchControls`, `SoundPool`, and 2D `com.codename1.gaming.physics` (Box2D). Read this for arcade/casual/scroller/board games or any real-time animated canvas. +- `references/platformer.md` — The deterministic platformer engine (`com.codename1.gaming.platformer`): actors and abilities, `PlatformView`, input recording and server-verified replay, ghosts. Read this for any platformer or side-scroller. +- `references/platformer-levels.md` — Platformer level JSON and the Ledge sketch format, level design rules, and proving a level can be finished with the solver. Read before writing or generating a level. +- `references/platformer-art.md` — The Ledge art pipeline (`tools/make-art.py`): sheet and atlas conventions, re-skinning, new enemies and worlds. - `references/3d-graphics.md` — Portable GPU 3D (`com.codename1.gpu`): the `RenderView` + `Renderer` loop, declarative `Material` / `VertexFormat` (engine-generated shaders — no GLSL), `Primitives`, `GltfLoader` for glTF models, `Camera` / `Light` / `Matrix4`, and platform backends. Read this for product viewers, 3D scenes, or custom GPU rendering. - `references/snapshot-builds.md` — Edge case: compiling against a Codename One SNAPSHOT from git. - `references/debugging.md` — `jdb`-attach workflow for an agent: start the simulator paused, set breakpoints, dump locals, drive the session non-interactively from a script. @@ -407,6 +410,7 @@ Report "could not verify" only after one of these steps actually failed, and quo | "Read voice input" / "Speak text aloud" / "Add a voice button to my chat" | `references/ai-and-speech.md` | | "Print a document / report / image" / "print the current screen" / AirPrint | `references/printing.md` | | "Build a game" / sprites, game loop, joystick, collisions / `GameView` | `references/games.md` | +| Platformer, side-scroller, level editor, replays/ghosts | `references/platformer.md`, `references/platformer-levels.md`, `references/platformer-art.md` | | "Render 3D" / "show a 3D model" / glTF / `RenderView` / custom GPU drawing | `references/3d-graphics.md` | | "Scan a barcode" / "Detect a face" / "Crop a document photo" via ML Kit | `references/ai-and-speech.md` | | "Store an LLM API key" / non-prompting SecureStorage | `references/ai-and-speech.md` | diff --git a/scripts/initializr/common/src/main/resources/skill/references/demos.md b/scripts/initializr/common/src/main/resources/skill/references/demos.md index 99a393eae38..648c48daab2 100644 --- a/scripts/initializr/common/src/main/resources/skill/references/demos.md +++ b/scripts/initializr/common/src/main/resources/skill/references/demos.md @@ -51,6 +51,7 @@ README of each lists the demo accounts. | `scripts/skirmish` | Real-time 3D card battler | Games: `GameView`/3D rendering (`battle/`), a deterministic simulation in `shared` run by app, server and tests, replays, in-app purchases and rewarded ads (`engage/`), matchmaking over sockets, in-app editors (`forge/`) | | `scripts/splat` | Team paintball first-person shooter: player, admin console | Games: 3D first-person rendering with `GameView` (`play/`), a deterministic simulation in `shared` that the server runs as the authority while the app predicts and reconciles (`play/OnlineDriver`), lag-compensated hits, bots inside the rules, parties with voice, crews and replays over sockets (`net/`, `game/`), in-app purchases and rewarded ads (`engage/`) | | `scripts/papercut` | Twin-stick arena shooter on a sheet of paper: player, admin console | Games: 2D `GameView` with twin sticks, keys and gamepad (`play/`), the whole simulation in one class with no UI (`play/Arena`), score plausibility checked on the server with no rules module (`ScoreBounds`), daily seeded sheet, boards, in-app purchases and rewarded ads (`engage/`) | +| `scripts/ledge` | 2D/2.5D platformer: player, level editor, admin console | Games: `com.codename1.gaming.platformer` (deterministic sim shared with the server, `PlatformView`, 2.5D), runs verified by server replay, ghosts and races, solver-proven levels, on-device editor, AI level generation with fallback, death heat map, boards, shop, push | | `scripts/dash` | Endless runner with a 2D-to-3D camera swing: player, track editor, admin console | Games: a deterministic simulation in `shared` run by app, server and tests, with the server re-simulating every submitted run to verify leaderboard scores (`game/`, `progress/`), live races with voice over sockets (`net/`), crews, friends and level packs (`social/`), a track editor (`forge/`), in-app purchases and rewarded ads (`engage/`, `shop/`) | ## Patterns the app demos share (copy these) diff --git a/scripts/initializr/common/src/main/resources/skill/references/games.md b/scripts/initializr/common/src/main/resources/skill/references/games.md index 0e815b86cc9..19f08de2330 100644 --- a/scripts/initializr/common/src/main/resources/skill/references/games.md +++ b/scripts/initializr/common/src/main/resources/skill/references/games.md @@ -183,6 +183,12 @@ Scaffold a scene with `mvn cn1:create-game-scene -DclassName=com.example.Level1 `mvn cn1:gamebuilder` (the standalone level/map editor; Java-17 CN1 projects only). In a Gradle project the editor is `./gradlew gameBuilder`; the scene scaffold is a Maven goal only for now. +## Platformers + +For a platformer use the engine in `com.codename1.gaming.platformer` instead of +building one on `GameView`: see `platformer.md`, `platformer-levels.md` and +`platformer-art.md`, and the Ledge template (`scripts/ledge`). + ## Platform support The gaming API is part of `codenameone-core` — no extra dependency, no build hint. Rendering uses the platform GPU backend (OpenGL ES on Android, Metal on iOS, WebGL on web, OpenGL/software on the simulator) and degrades gracefully where 3D is unavailable. Box2D physics is pure Java and identical everywhere. diff --git a/scripts/initializr/common/src/main/resources/skill/references/platformer-art.md b/scripts/initializr/common/src/main/resources/skill/references/platformer-art.md new file mode 100644 index 00000000000..0333501a0bb --- /dev/null +++ b/scripts/initializr/common/src/main/resources/skill/references/platformer-art.md @@ -0,0 +1,51 @@ +# Platformer Art Reference + +How the Ledge template's art is made and how to change it. Engine: `platformer.md`. + +## Everything comes from one script + +`tools/make-art.py` draws every image and synthesises every sound from shapes and +envelopes (Pillow only). It is the template's stand-in for an asset store: to change +the look, edit a palette, a pose or an envelope and run it again. + +```bash +python3 tools/make-art.py # everything, about a second +python3 tools/make-art.py actors # one group: tiles, actors, items, backdrops, ui, sfx +``` + +Output goes to `common/src/main/resources`. `play/LedgeArt.java` is the only class +that knows file names; the engine asks it through `PlatformArt`. + +## Conventions the game relies on + +- 4 art pixels per world pixel: a 16 px tile is a 64 px cell. +- `tiles_.png`: an 8 x 4 atlas of 64 px cells. 0-15 solid ground chosen by + which sides are open (bit 1 top, 2 right, 4 bottom, 8 left), 16-21 the six slopes + in `Tile` order, 22-25 one-way ledges (middle, left end, right end, both), 26 + ladder, 27 spikes, 28 water surface, 29 water. +- Actor sheets (`hero.png`, `enemy_.png`): one row of equal frames, facing + right, feet on the bottom edge, centred. The hero's frame order is + `HERO_FRAMES` in the script; `PlatformView` flips for left. +- Items (`item_*.png`, `shot_*.png`) are centred on the item's rectangle. +- `bg__.png`: parallax backdrops, 0 farthest, tiling horizontally; the + top-left pixel of layer 0 is also the sky colour the view clears to. + +## Common edits + +- **Recolour a world**: change its entry in `THEMES`. +- **New world**: a `THEMES` entry plus a branch in `make_backdrops`; use the theme + name in level headers. +- **New enemy**: a `draw_` function and a line in `make_actors`, a sketch + letter in `LevelSketch`, and a brain (`walker`, `chase`, `hopper`, `flyer`, + `turret`, `boss`). +- **Hand-drawn art**: keep file names and sizes above and drop the files in. +- **Sounds**: `make_sfx` builds each `sfx_*.wav` from oscillators and envelopes; + the game plays them by name (`Sfx.play("jump")`). + +## Image-model prompts (if replacing the procedural art) + +Ask for a transparent PNG, side view, flat shading with a dark outline, the subject +facing right, standing on the bottom edge, on a canvas that is a multiple of 64 px. +For tiles ask for a seamless 64 px square and cut the 16 edge variants from one +base texture. Run the game and look at a level after every change; the e2e test +(`./run-e2e.sh`) saves screenshots to `target/e2e-shots`. diff --git a/scripts/initializr/common/src/main/resources/skill/references/platformer-levels.md b/scripts/initializr/common/src/main/resources/skill/references/platformer-levels.md new file mode 100644 index 00000000000..3d23d6f39be --- /dev/null +++ b/scripts/initializr/common/src/main/resources/skill/references/platformer-levels.md @@ -0,0 +1,104 @@ +# Platformer Levels Reference + +How to write, generate and prove levels for `com.codename1.gaming.platformer` +(`LevelData`), and the sketch format the Ledge template uses. Engine API: +`platformer.md`. + +## Level JSON + +```json +{ + "name": "First steps", "tileSize": 16, + "tiles": ["#..............#", "#.........====.#", "#.....H........#", "#.....H..../####", "################"], + "spawn": [1, 3], "goal": [14, 2, 1, 1], + "platforms": [{"path": [[3, 2], [8, 2]], "w": 2, "speed": 0.75, "pause": 30}], + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "tuning": {"maxJumps": 2}, + "health": 3, + "entities": [{"type": "coin", "at": [5, 1]}, {"type": "enemy", "kind": "slime", "brain": "walker", "at": [9, 3]}] +} +``` + +Positions and sizes are in tiles, speeds in pixels per tick; decimals are read +exactly (no float). Row 0 is the top. Without `health` one hit kills; without +`lives` retries are unlimited. + +| Tile | Meaning | +|---|---| +| `.` | empty | +| `#` | solid | +| `=` | one-way ledge (stand on top, jump up through, down+jump drops) | +| `/` `\` (or `r` `f`) | 45 degree slope up / down to the right | +| `a b` / `c d` | 22.5 degree rise / fall, two tiles each | +| `H` | ladder | +| `^` | hazard (spikes) | +| `~` | water | + +Entity `type`s: `coin`, `gem`, `heart`, `life`, `key`/`powerup` (`name`), `spring` +(`power`), `checkpoint`, `door` (`key`, `h`), `gate` (`channel`, `w`, `h`, +`inverted`), `lever`/`plate` (`channel`), `crumble` (`w`, `delay`, `respawn`), +`enemy` (`kind`, `brain`, `hp`, `damage`, `speed`, `range`, `stompable`, `opens`). + +Limits (`LevelData`): at most 4096 columns, 512 rows, 2048 entities, 256 platforms +-- a published level's replay cost on the server stays bounded. + +## Ledge sketches (`levels/src/*.sketch`) + +Easiest for people and models: a JSON header, a line `---`, then 16 rows of tiles +with things drawn as letters (each leaves an empty cell): + +``` +{"name": "Thornwood", "theme": "meadow", "par": 75, "health": 3, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], "tuning": {"maxJumps": 2}} +--- +.................... +.......ooo......X... +.S........=====.###. +#####..#######^^#### +``` + +``` +S spawn X goal C checkpoint o coin * gem h heart +1 life k key D door (2 tall, needs a key) s spring +% crumble L lever P plate | gate (channel 1, 3 tall) +e slime w beetle B brute T turret F frog V bat +Z boss J jetpack G glide +``` + +Themes: `meadow`, `cavern`, `foundry`, `sky` (drawn 2.5D), `forge`. Exactly one `S` +and one `X`. `LevelSketch.compile(text)` (shared, runs on device and server) and +`tools/sketch.py` produce the same JSON. + +## Design rules that make levels fair + +- Teach, then test: introduce a hazard where failing is cheap before combining it. +- With `maxJumps: 2`, a gap of up to 5 tiles is a jump; climbs of 3 tiles need a + double jump. Leave a solid tile to land on after every gap. +- Put a checkpoint (`C`) before each hard section and after every long climb. +- One gem per level, off the main path; coins in arcs that show the jump. +- Par (seconds) ~ 1.3 x the solver route's time. + +## Prove it can be finished (always do this) + +Never ship or publish a level a solver has not finished: + +```bash +python3 tools/sketch.py levels/src/2-4.sketch > levels/2-4.json +mvn -pl shared,backend -Dcodename1.platform=backend test -Dtest=LevelsTest -Dledge.record=2-4 +python3 tools/pack-levels.py # writes LevelPack.java; --check in CI +``` + +The recorder runs `Solver` (a search over the real simulation) and writes +`levels/demo/2-4.log` only if the route finishes on every test seed. That log is the +level's attract-mode demo, its regression test and its first ghost. If the solver +finds nothing, simplify the level (narrower gaps, a checkpoint, an extra ledge). + +In code: `LevelGenerator.check(sketch, budgetTicks)` returns the route or null; +`LevelGenerator.solvable(request, seed, budget)` builds a proven level from words. + +## Generating levels with a model + +Ledge's server (`ai/LevelAi`) asks a model for a sketch, runs `LevelGenerator.check` +on the reply, and falls back to `LevelGenerator.solvable` if the model's level fails. +When writing a sketch yourself, follow the format exactly: a JSON header, `---`, +16 rows of equal length, no code fences. diff --git a/scripts/initializr/common/src/main/resources/skill/references/platformer.md b/scripts/initializr/common/src/main/resources/skill/references/platformer.md new file mode 100644 index 00000000000..55852aa3b63 --- /dev/null +++ b/scripts/initializr/common/src/main/resources/skill/references/platformer.md @@ -0,0 +1,100 @@ +# Platformer Engine Reference (`com.codename1.gaming.platformer`) + +A deterministic 2D / 2.5D platformer engine in core: character controller, abilities, +enemies, interactables, a JSON level format, and input recording that replays +bit-for-bit on the server. The Ledge template (`scripts/ledge`) is the full game +built on it. Levels: `platformer-levels.md`. Art: `platformer-art.md`. + +## The two halves + +- **Simulation** (`com.codename1.gaming.platformer`): no UI, no float, no clock. + Positions/speeds are 16.16 fixed point ints (`Fx`), 60 ticks a second, randomness + only from the world's seeded `Rng`. The same level + seed + input gives the same + `PlatformWorld.hash()` on every device and on the backend. +- **Presentation** (`...platformer.view`): `PlatformView extends GameView` draws a + world (parallax, sprite animation, particles, shake, interpolation between ticks, + optional 2.5D) and feeds it input. + +Never put presentation state (floats, `System.currentTimeMillis`, `Math.random`) +into simulation code: it breaks server replay. + +## Minimal game + +```java +LevelData level = LevelData.parse(json); // throws IllegalArgumentException +PlatformWorld world = level.createWorld(seed); +PlatformView view = new PlatformView(world, new ProceduralArt(level.getTileSize())); // or your PlatformArt +view.setVisibleRows(11.5); +form.add(BorderLayout.CENTER, view); +view.start(); +``` + +`PlatformView` maps keys, gamepad and its `TouchControls` to `Input` bits via an +`InputMapper` (arrows/WASD, Space jump, Z dash, X fire). Override `onTick(int input)` +for HUD updates and `onEvent(WorldEvent e)` for sounds (`PICKUP`, `DEATH`, `JUMP`, ...). +`addBackground(image, factor, y)` adds a parallax layer; `setDepth(true)` draws 2.5D. + +## Input, recording, replay + +`Input` bits: `LEFT RIGHT UP DOWN JUMP RUN DASH FIRE ACTIVATE ALT`. One int per tick. + +```java +InputLog log = new InputLog(); // record: log.add(bits) every tick +String wire = log.encode(); // run-length text, small +Replay.Result r = Replay.run(level, seed, InputLog.decode(wire, maxTicks)); +r.isComplete(); r.getTicks(); r.getDeaths(); r.getHash(); +``` + +Use `PlatformView.setInputSource(...)` to record (Ledge's `LedgeView` does this) or +to drive the hero from a recorded log (attract mode, replays). `addGhost(world, +inputs, alpha)` races a recorded run beside the live one; `getGhostWorlds()` lets a +HUD compute the gap. + +**Server verification**: mark nothing yourself -- the simulation classes are +already shared with the backend. On the server, rebuild the world from the level +and the seed you issued and call `Replay.run`; store the replay's ticks/score, never +the client's. Bound the log length and tick count before decoding. + +## Actors and abilities + +An `Actor` has a `Body` (kinematic box: slopes, one-way ledges, steps, riding moving +platforms) and an ordered list of `Ability` objects processed each tick: + +| Name | Class | Notes | +|---|---|---| +| `move` | `MoveAbility` | walk/run, acceleration | +| `jump` | `JumpAbility` | coyote time, buffered press, variable height, multi-jump, drop through `=` with down+jump | +| `crouch` | `CrouchAbility` | | +| `ladder` | `LadderAbility` | `H` tiles | +| `walljump` | `WallJumpAbility` | wall slide + jump | +| `dash` | `DashAbility` | | +| `jetpack`, `glide`, `swim`, `fly`, `look` | ... | power-ups / special | +| `weapon`, `sword` | `WeaponAbility` | projectile or melee | + +A level lists the hero's abilities in processing order; `PlatformWorld.enableAbility` +turns one on at run time (a power-up). Custom ability: extend `Ability`, implement +`process(Actor, PlatformWorld)`, keep all state in ints, and include it in +`hashState` so replays detect divergence. + +Tuning keys (level `"tuning"`): `walkSpeed runSpeed jumpSpeed maxJumps gravity +maxFall coyoteTicks bufferTicks climbSpeed wallSlide dashSpeed dashTicks +fireCooldown automaticFire shotGravity`. + +## Enemies and things + +Entities come from the level's `entities` (see `platformer-levels.md`): pickups, +`Spring`, `Checkpoint`, `Door`/keys, `Gate` + `Switch` (lever/plate channels), +`CrumbleBlock`, `MovingPlatform`, and `enemy` with an `AIBrain` (`walker`, `chase`, +`hopper`, `flyer`, `turret`, `boss`). Unknown types go to an `EntityFactory` passed +to `createWorld(seed, factory)`. + +`Health` gives hit points and invulnerability frames; `world.setLives(n)` limits +retries. `WorldEvent`s (cleared every step) report jumps, pickups, damage, deaths +(`detail` is the actor kind, e.g. `"hero"`), checkpoints and the finish. + +## Rules that keep it working on every port + +- Java 5 / CLDC API only in core code; no reflection, no `clone()`. +- Simulation code: ints only, iterate lists by index (no iterator garbage per tick). +- Feed the same `seed` to client and server; Ledge caps seeds at 52 bits because a + seed travels as a JSON number. diff --git a/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java b/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java index bd32254ca52..2ff674bf58a 100644 --- a/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java +++ b/scripts/initializr/common/src/test/java/com/codename1/initializr/model/GeneratorModelMatrixTest.java @@ -422,10 +422,11 @@ private void assertFullStackProject(Template template, Map entri boolean rides = template == Template.WAYLINE; boolean bank = template == Template.BASTION; boolean game = template == Template.SKIRMISH || template == Template.DASH || template == Template.SPLAT - || template == Template.PAPERCUT; + || template == Template.PAPERCUT || template == Template.LEDGE; boolean runner = template == Template.DASH; boolean paintball = template == Template.SPLAT; boolean arena = template == Template.PAPERCUT; + boolean platformer = template == Template.LEDGE; boolean video = template == Template.REEL; boolean studio = template == Template.PULSE; boolean booking = template == Template.SLATE; @@ -445,7 +446,7 @@ private void assertFullStackProject(Template template, Map entri // project once got the ride-hailing accounts and chapters. String readme = getText(entries, "README.md"); boolean chat = template == Template.PARLEY; - assertContains(readme, game ? (runner ? "endless runner" : paintball ? "paintball shooter" : arena ? "arena shooter" : "card battler") : rides ? "ride-hailing app" : chat ? "messaging app" : bank ? "working bank" : studio ? "fitness studio app" : field ? "field service app" : shop ? "commerce platform" : booking ? "appointment booking app" : video ? "video streaming service" : "food-delivery app", + assertContains(readme, game ? (runner ? "endless runner" : paintball ? "paintball shooter" : arena ? "arena shooter" : platformer ? "platformer" : "card battler") : rides ? "ride-hailing app" : chat ? "messaging app" : bank ? "working bank" : studio ? "fitness studio app" : field ? "field service app" : shop ? "commerce platform" : booking ? "appointment booking app" : video ? "video streaming service" : "food-delivery app", label + "README names the app"); if (!game) { assertContains(readme, (rides ? "`rider@" : chat ? "`alice@" : bank ? "`customer2@" : studio ? "`member@" : field ? "`tech@" : shop ? "`shopper@" : booking ? "`client@" : video ? "`viewer@" : "`customer@") + artifact + ".example`", @@ -473,7 +474,7 @@ private void assertFullStackProject(Template template, Map entri "package " + packageName + ";", label + "the server moves to the project's package"); assertNotNull(entries.get("backend/src/main/resources/db/migration/" + (game ? "V1__game.sql" : bank ? "V4__accounts.sql" : studio || booking ? "V2__accounts.sql" : "V1__accounts.sql")), label + "the server keeps its migrations"); - assertNotNull(entries.get("backend/src/test/java/" + packagePath + (arena ? "/RunTest.java" : game ? "/GameSocketTest.java" : rides ? "/RideFlowTest.java" : chat ? "/MessagingTest.java" : bank ? "/LedgerTest.java" : video ? "/PlaybackTest.java" : studio ? "/StudioTest.java" : field ? "/FieldTest.java" : shop ? "/AccountTest.java" : booking ? "/booking/BookingFlowTest.java" : "/OrderFlowTest.java")), + assertNotNull(entries.get("backend/src/test/java/" + packagePath + (arena || platformer ? "/RunTest.java" : game ? "/GameSocketTest.java" : rides ? "/RideFlowTest.java" : chat ? "/MessagingTest.java" : bank ? "/LedgerTest.java" : video ? "/PlaybackTest.java" : studio ? "/StudioTest.java" : field ? "/FieldTest.java" : shop ? "/AccountTest.java" : booking ? "/booking/BookingFlowTest.java" : "/OrderFlowTest.java")), label + "the server keeps its tests"); assertNotNull(entries.get("common/src/main/java/" + packagePath + (game ? "/ui/HomeForm.java" : rides ? "/rider/RiderForm.java" : chat ? "/ui/ChatForm.java" : bank ? "/ui/HomeForm.java" : video ? "/ui/WelcomeForm.java" : studio ? "/member/MemberForm.java" : field ? "/field/TodayForm.java" : shop ? "/shop/CheckoutForm.java" : booking ? "/client/ClientForm.java" : "/customer/CustomerForm.java")), label + "the app's screens move to the project's package"); diff --git a/scripts/initializr/e2e-shipped.sh b/scripts/initializr/e2e-shipped.sh index 5de311aad36..3c83bb969c0 100755 --- a/scripts/initializr/e2e-shipped.sh +++ b/scripts/initializr/e2e-shipped.sh @@ -12,7 +12,7 @@ # # e2e-shipped.sh [--require-latest] [--no-ui] [TEMPLATE ...] # -# TEMPLATE is BAREBONES, KOTLIN, WAYLINE, SAVOR, SKIRMISH, DASH, SPLAT, PAPERCUT, PARLEY, BASTION, REEL, PULSE, SLATE, FIELDLINE or BAZAAR; all of them +# TEMPLATE is BAREBONES, KOTLIN, WAYLINE, SAVOR, SKIRMISH, DASH, SPLAT, PAPERCUT, LEDGE, PARLEY, BASTION, REEL, PULSE, SLATE, FIELDLINE or BAZAAR; all of them # by default. Every other check of the templates builds them against this # checkout's 8.0-SNAPSHOT, which no developer has: the generated pom names the # release the Initializr pins, and that is the only thing this script builds @@ -69,7 +69,7 @@ for arg in "$@"; do *) TEMPLATES+=("$arg") ;; esac done -[ ${#TEMPLATES[@]} -gt 0 ] || TEMPLATES=(BAREBONES KOTLIN WAYLINE SAVOR SKIRMISH DASH SPLAT PAPERCUT PARLEY BASTION REEL PULSE SLATE FIELDLINE BAZAAR) +[ ${#TEMPLATES[@]} -gt 0 ] || TEMPLATES=(BAREBONES KOTLIN WAYLINE SAVOR SKIRMISH DASH SPLAT PAPERCUT LEDGE PARLEY BASTION REEL PULSE SLATE FIELDLINE BAZAAR) log() { echo "[e2e-shipped] $*" >&2; } fail() { echo "[e2e-shipped] FAIL: $*" >&2; exit 1; } @@ -86,14 +86,15 @@ BASTION_SINCE="$(since BASTION_SINCE)" REEL_SINCE="$(since REEL_SINCE)" SPLAT_SINCE="$(since SPLAT_SINCE)" PAPERCUT_SINCE="$(since PAPERCUT_SINCE)" +LEDGE_SINCE="$(since LEDGE_SINCE)" SLATE_SINCE="$(since SLATE_SINCE)" FIELDLINE_SINCE="$(since FIELDLINE_SINCE)" BAZAAR_SINCE="$(since BAZAAR_SINCE)" -[ -n "$FULL_STACK_SINCE" ] && [ -n "$BASTION_SINCE" ] && [ -n "$REEL_SINCE" ] && [ -n "$SPLAT_SINCE" ] && [ -n "$PAPERCUT_SINCE" ] && [ -n "$SLATE_SINCE" ] && [ -n "$FIELDLINE_SINCE" ] && [ -n "$BAZAAR_SINCE" ] || fail "could not read the template floors from $GENERATOR" +[ -n "$FULL_STACK_SINCE" ] && [ -n "$BASTION_SINCE" ] && [ -n "$REEL_SINCE" ] && [ -n "$SPLAT_SINCE" ] && [ -n "$PAPERCUT_SINCE" ] && [ -n "$LEDGE_SINCE" ] && [ -n "$SLATE_SINCE" ] && [ -n "$FIELDLINE_SINCE" ] && [ -n "$BAZAAR_SINCE" ] || fail "could not read the template floors from $GENERATOR" # The oldest release a template's generated code compiles against: Bastion # calls framework API that first shipped in BASTION_SINCE, Reel the protected # playback API of REEL_SINCE, Splat the 3D engine of SPLAT_SINCE, Papercut -# the release that follows its addition (PAPERCUT_SINCE), +# the release that follows its addition (PAPERCUT_SINCE), Ledge likewise (LEDGE_SINCE), # Slate the scheduling views of SLATE_SINCE, Fieldline the resource timeline, # calendar and camera API of FIELDLINE_SINCE, Bazaar ships from BAZAAR_SINCE. template_since() { @@ -102,6 +103,7 @@ template_since() { REEL) echo "$REEL_SINCE" ;; SPLAT) echo "$SPLAT_SINCE" ;; PAPERCUT) echo "$PAPERCUT_SINCE" ;; + LEDGE) echo "$LEDGE_SINCE" ;; SLATE) echo "$SLATE_SINCE" ;; FIELDLINE) echo "$FIELDLINE_SINCE" ;; BAZAAR) echo "$BAZAAR_SINCE" ;; diff --git a/scripts/ledge/ART.md b/scripts/ledge/ART.md new file mode 100644 index 00000000000..83c98e7bbca --- /dev/null +++ b/scripts/ledge/ART.md @@ -0,0 +1,39 @@ +# Ledge art, sound and type + +Every picture and every sound in Ledge is made by one script, +`tools/make-art.py`, from shapes and synthesis. Nothing is downloaded, traced or +sampled, so the look is this project's own and it can be re-tuned by editing +a palette, a pose or an envelope and running the script again. + +| What | Files | Made by | +|---|---|---| +| Five tile sets, auto-tiled by which sides are open | `tiles_.png` | `make_tiles` | +| Moving platforms | `platform_.png` | `make_tiles` | +| The hero, 18 poses | `hero.png` | `make_actors` | +| Seven enemies, from slime to the forge golem | `enemy_*.png` | `make_actors` | +| Coins, gems, hearts, keys, springs, doors, gates, levers, plates, crumbling blocks, power-ups, the goal portal, shots | `item_*.png`, `shot_*.png` | `make_items` | +| Three parallax layers per world | `bg__.png` | `make_backdrops` | +| App icon and particle spark | `app_icon.png`, `fx_spark.png` | `make_ui` | +| Nineteen sound effects | `sfx_*.wav` | `make_sfx` | + +The one thing that came from somewhere else is the type: **Lilita One** by Juan +Montoreano, under the SIL Open Font License 1.1, from Google Fonts. Its licence +is beside the font in `common/src/main/css/fonts/OFL.txt`. + +## Re-making or re-skinning + +```bash +python3 tools/make-art.py # everything, about a second +python3 tools/make-art.py actors # one group: tiles, actors, items, backdrops, ui, sfx +``` + +It needs Pillow and nothing else. The conventions the game reads -- the atlas +layout, the frame order of `hero.png`, which way a sheet faces -- are listed at +the top of the script and in `play/LedgeArt.java`, which is the only class that +knows file names. A new theme is a new entry in `THEMES` plus a backdrop branch; +a new enemy is a `draw_` function and a line in `make_actors`. The +`platformer-art` skill walks a language model through the same edits. + +To drop in hand-drawn art instead, keep the file names and sizes: tiles are 64 +art pixels (4 per world pixel), actor frames stand on their bottom edge and face +right. diff --git a/scripts/ledge/LICENSE b/scripts/ledge/LICENSE new file mode 100644 index 00000000000..af5d69aaeb3 --- /dev/null +++ b/scripts/ledge/LICENSE @@ -0,0 +1,22 @@ +MIT No Attribution + +Copyright (c) 2026, Codename One and/or its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +This applies to the Skirmish sample and to everything Codename One Initializr +writes into a generated project: the application templates under +maven/cn1app-archetype/src/main/resources/archetype-resources, the agent skill +under scripts/initializr/common/src/main/resources/skill, and the Initializr +template archives built from them. diff --git a/scripts/ledge/README.adoc b/scripts/ledge/README.adoc new file mode 100644 index 00000000000..2934dd10e3a --- /dev/null +++ b/scripts/ledge/README.adoc @@ -0,0 +1,129 @@ += Ledge + +A platformer and its server, in one Maven project and one language. A small +hooded hero runs, double-jumps, wall-jumps and dashes through thirteen levels +across five worlds -- meadow, cavern, foundry, a 2.5D skyway and the forge -- +past slimes, beetles, turrets and bats to a forge golem at the end. Every run is +recorded as the player's input, tick by tick, and the server replays it to +verify the time and the score before it reaches the boards. + +That replay is what the rest is built on. Runs on the boards are ghosts any +player can race; the console draws a heat map of where players die, from the +server's own replays; and the on-device level editor proves a level can be +finished, by solving it, before it can be played. Describe a level in words and +a language model draws it, or the built-in generator does when no model is set +up; either way the solver checks it first. + +Around the game is what a live game needs: accounts, boards for all time, the +week, today and your friends, a daily challenge, a shop of scarves, +achievements, push broadcasts and a console for running it. + +The engine is Codename One's own, `com.codename1.gaming.platformer`: an +integer-only simulation that runs unchanged in the app and on the server. There +is no `rules` module; the levels, the scoring and the solver are in `shared`. + +It's a sample of what Codename One does for games, and the project the +Initializr generates when you start from the platformer template. + +== Start here + +One chapter of the developer guide covers this project: + +* https://www.codenameone.com/developer-guide/#ledge-implementors-guide[The Ledge chapter] + (link:../../docs/developer-guide/Ledge-Implementors-Guide.asciidoc[source]) + tours what the game does, with the demo accounts, then explains how it's + built and what to change to make it yours: levels, abilities, the look and + the server. + +== The modules + +[cols="1,3"] +|=== +| Module | What it holds + +| `shared` | The data transfer objects, the `@RestClient` interfaces, the level + pack, the sketch format, scoring, the solver, the level generator and the + death map. +| `common` | The app: the level view and HUD, touch controls, the world map, + the boards and races, the editor, the shop and the admin console. +| `backend` | The server: accounts, run tickets and replay verification, boards + and ghosts, the daily seed, the shop, achievements, AI levels and + administration. +| `ios` | The iOS build, for generating the Xcode project. +|=== + +`levels/src/*.sketch` are the levels as drawn; `levels/*.json` are what they +compile to and `levels/demo/*.log` the solver's route through each. `tools/` +turns them into `LevelPack` and makes the art. + +== Running it + +Start the server on the development profile. It needs nothing installed: the +database is in memory, purchases are simulated, and the demo accounts +`player@`, `rival@`, `trouble@` and `admin@ledge.example` exist, each with +the password `ledge-demo`. + +[source,bash] +---- +CN1_PROFILE=dev backend/server.sh run +---- + +Then run the app in the simulator: + +[source,bash] +---- +mvn verify -Psimulator -DskipTests -Dcodename1.platform=javase +---- + +On a touch screen a joystick on the left moves and buttons on the right jump +and dash; on a desktop it's the arrow keys or WASD, Space and Z, and a gamepad +works too. + +For the native iOS app, generate the Xcode project on a Mac, open it and run it +from Xcode: + +[source,bash] +---- +mvn package -DskipTests -Dcodename1.platform=ios -Dcodename1.buildTarget=ios-source -Dopen=false +---- + +To let a language model draw levels, set `ledge.ai.provider` (`openai`, +`anthropic`, `gemini`, or `url` for any OpenAI-compatible server) and +`ledge.ai.key` in the server's configuration. Without them the built-in +generator answers. + +== Tests + +[source,bash] +---- +mvn -pl shared,backend -Dcodename1.platform=backend test # <1> +./run-e2e.sh # <2> +./check-template.sh # <3> +---- +<1> The server's tests: accounts, run tickets and replay verification, boards + and ghosts, the shop, progression, the levels (every demo finishes, the + solver finishes every level), AI levels and administration. +<2> Starts the server on the `test` profile and runs the app's tests against it + in the simulator: real levels played by their demo runs, the editor, a race + and the console. Screenshots land in `target/e2e-shots`. +<3> Generates a project from the Initializr template, under another name and + package, and builds it. + +`.github/workflows/samples.yml` runs them, and builds the app for Android and +iOS. + +== The Initializr template + +`scripts/sync-initializr-template.py ledge --write` copies this project into +the Initializr's resources; without `--write` it fails when they differ, which is +what CI runs. Change the project here, never the copies. + +== Licence + +Ledge is released under MIT No Attribution (see `LICENSE`), not under the +GPLv2 with Classpath Exception that covers Codename One itself. Take any of it +into your own application, under any licence, with no notice to keep. + +Every picture and sound is made by `tools/make-art.py` from shapes and +synthesis; the type is Lilita One under the SIL Open Font License. `ART.md` +lists them and how to re-skin the game. diff --git a/scripts/ledge/backend/application-dev.properties b/scripts/ledge/backend/application-dev.properties new file mode 100644 index 00000000000..3f5573d0b9e --- /dev/null +++ b/scripts/ledge/backend/application-dev.properties @@ -0,0 +1,3 @@ +cn1.datasource.url=:memory: +ledge.iap.provider=simulated +ledge.push.provider=console diff --git a/scripts/ledge/backend/application-test.properties b/scripts/ledge/backend/application-test.properties new file mode 100644 index 00000000000..37da4918977 --- /dev/null +++ b/scripts/ledge/backend/application-test.properties @@ -0,0 +1,4 @@ +cn1.datasource.url=:memory: +ledge.signin.per-minute=1000 +ledge.iap.provider=simulated +ledge.push.provider=recording diff --git a/scripts/ledge/backend/application.properties b/scripts/ledge/backend/application.properties new file mode 100644 index 00000000000..b9e4c12b9c9 --- /dev/null +++ b/scripts/ledge/backend/application.properties @@ -0,0 +1,3 @@ +cn1.datasource.url=${DATABASE_URL} +cn1.server.port=8080 +cn1.security.schema.enabled=true diff --git a/scripts/ledge/backend/pom.xml b/scripts/ledge/backend/pom.xml new file mode 100644 index 00000000000..a830885d734 --- /dev/null +++ b/scripts/ledge/backend/pom.xml @@ -0,0 +1,166 @@ + + + 4.0.0 + + com.codenameone.examples.ledge + ledge + 1.0-SNAPSHOT + + com.codenameone.examples.ledge + ledge-backend + 1.0-SNAPSHOT + jar + + ledge-backend + + + + + com.codenameone + codenameone-backend + ${cn1.version} + + + + com.codenameone + cn1-app-kit-backend + ${cn1.version} + + + + ${project.groupId} + ledge-shared + ${project.version} + + + + org.xerial + sqlite-jdbc + 3.46.1.0 + runtime + + + + com.codenameone + codenameone-backend-test + ${cn1.version} + test + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + cn1-generate-annotation-stubs + generate-sources + + + generate-annotation-stubs + + + + cn1-process-annotations + process-classes + + + process-annotations + + + + cn1-process-test-annotations + process-test-classes + + + process-test-annotations + + + + cn1-compiled-tests + test + + + backend-test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + false + + + + + diff --git a/scripts/ledge/backend/server.sh b/scripts/ledge/backend/server.sh new file mode 100755 index 00000000000..e271136173c --- /dev/null +++ b/scripts/ledge/backend/server.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# +# Builds and runs the Ledge server. +# +# server.sh build [--jvm|--native] [--web] +# server.sh run [--jvm|--native] [--web] [--prebuilt] [--port N] +# server.sh web +# +# --jvm (the default) runs the server on this JDK, which is how you work on it. +# --native compiles it to a native binary, which is how it ships. +# +# The profile comes from CN1_PROFILE. `test` and `dev` need nothing else: an +# in-memory database, four demo accounts, simulated in-app purchases and +# push notifications that are printed, not sent. Anything else is a +# deployment and reads its settings from the environment -- see +# application.properties. +# +# `web` builds the app for the browser and stages it in target/webapp, which +# takes about a minute; `--web` does that as part of a build or a run. A server +# that finds the app there serves it at /, so http://localhost:8080/ is Ledge +# with nothing installed. It stays staged until the next `mvn clean`: build it +# once, and again when the app changed. +# +# The server prints "listening on http port N" when it accepts connections. +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +APP="$(cd "$HERE/.." && pwd)" +# The project's own Maven wrapper where it has one. +if [ -z "${MVN:-}" ]; then + if [ -x "$APP/mvnw" ]; then MVN="$APP/mvnw"; else MVN="mvn"; fi +fi + +log() { echo "[ledge-server] $*" >&2; } + +build_jvm() { + log "building the server for the JVM" + "$MVN" -B -q -f "$APP/pom.xml" -Dcodename1.platform=backend -pl shared,backend \ + -Dmaven.test.skip=true package dependency:copy-dependencies \ + -DincludeScope=runtime -DoutputDirectory="$APP/backend/target/server-lib" >&2 +} + +build_native() { + log "translating the server to a native binary" + "$MVN" -B -q -f "$APP/pom.xml" -Dcodename1.platform=backend -pl shared,backend \ + -Dmaven.test.skip=true package cn1:backend-package \ + -Dcn1.backend.output="$APP/backend/target/ledge-server" >&2 +} + +build_web() { + log "building the app for the browser" + "$MVN" -B -q -f "$APP/pom.xml" -Dcodename1.platform=backend -pl backend \ + cn1:backend-webapp >&2 +} + +# The server looks for the app in `webapp` beside its settings; here it is build +# output, so it is under target and the server is told. An address set by the +# caller is left alone. +serve_web() { + if [ -z "${CN1_WEBAPP_ROOT:-}" ] && [ -f "$APP/backend/target/webapp/index.html" ]; then + export CN1_WEBAPP_ROOT="target/webapp" + log "serving the web app in backend/target/webapp" + fi +} + +command="${1:-run}" +shift || true +mode="jvm" +port="${PORT:-8080}" +prebuilt=0 +web=0 +while [ $# -gt 0 ]; do + case "$1" in + --jvm) mode="jvm" ;; + --native) mode="native" ;; + --prebuilt) prebuilt=1 ;; + --web) web=1 ;; + --port) port="$2"; shift ;; + *) log "unknown argument $1"; exit 2 ;; + esac + shift +done + +case "$command" in + build) + if [ "$mode" = "native" ]; then build_native; else build_jvm; fi + [ "$web" = 0 ] || build_web + ;; + web) + build_web + ;; + run) + # application.properties is read from the working directory. + cd "$APP/backend" + if [ "$mode" = "native" ]; then + [ "$prebuilt" = 1 ] || build_native + [ "$web" = 0 ] || [ "$prebuilt" = 1 ] || build_web + serve_web + PORT="$port" exec "$APP/backend/target/ledge-server" + fi + [ "$prebuilt" = 1 ] || build_jvm + [ "$web" = 0 ] || [ "$prebuilt" = 1 ] || build_web + serve_web + main="$(tr -d '\r\n' < "$APP/backend/target/classes/META-INF/cn1-backend-main")" + log "running $main on port $port" + PORT="$port" exec java -cp "$APP/backend/target/classes:$APP/backend/target/server-lib/*" "$main" + ;; + *) + log "unknown command $command (build, run, web)" + exit 2 + ;; +esac diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Clock.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Clock.java new file mode 100644 index 00000000000..4c237575454 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Clock.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +/// Wall-clock time, in one place so day boundaries are computed the same way +/// everywhere (UTC days). +public final class Clock { + public static final long DAY = 24L * 60 * 60 * 1000; + + private Clock() { + } + + private static long offset; + + public static long now() { + return System.currentTimeMillis() + offset; + } + + /// Moves `now()` by `millis`, for the tests: a run that claims an hour + /// is only accepted an hour after its ticket was issued. + static void shiftForTests(long millis) { + offset = millis; + } + + /// Midnight UTC at the start of the day `millis` falls in. + public static long dayOf(long millis) { + return millis - millis % DAY; + } + + /// Midnight UTC on the Monday of the week `millis` falls in. The epoch was + /// a Thursday, hence the three days. + public static long weekOf(long millis) { + long day = dayOf(millis) / DAY; + long sinceMonday = ((day + 3) % 7 + 7) % 7; + return (day - sinceMonday) * DAY; + } + + /// The UTC date `millis` falls on, as `yyyy-mm-dd`. Worked out by hand + /// (the civil-from-days algorithm) so it needs nothing of `java.time` past + /// `Instant`, which is all the server's class library promises. + public static String date(long millis) { + long z = Math.floorDiv(millis, DAY) + 719468; + long era = Math.floorDiv(z, 146097); + long doe = z - era * 146097; + long yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + long y = yoe + era * 400; + long doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + long mp = (5 * doy + 2) / 153; + long d = doy - (153 * mp + 2) / 5 + 1; + long m = mp < 10 ? mp + 3 : mp - 9; + if (m <= 2) { + y++; + } + StringBuilder out = new StringBuilder(); + out.append(y).append('-'); + if (m < 10) { + out.append('0'); + } + out.append(m).append('-'); + if (d < 10) { + out.append('0'); + } + return out.append(d).toString(); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Ids.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Ids.java new file mode 100644 index 00000000000..5fd55e4e5a7 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Ids.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.Crypto; + +import java.io.IOException; + +/// Identifiers and secrets made of random bytes. +public final class Ids { + private static final char[] HEX = "0123456789abcdef".toCharArray(); + + private Ids() { + } + + /// A new identifier: 32 hex digits from 16 random bytes. Random and not a + /// counter, so the id of one delivery says nothing about the id of another, and + /// so no table needs a generated key, which every database spells its own way. + public static String next() throws IOException { + return hex(Crypto.randomBytes(16)); + } + + public static String hex(byte[] bytes) { + char[] out = new char[bytes.length * 2]; + for (int iter = 0; iter < bytes.length; iter++) { + out[iter * 2] = HEX[(bytes[iter] >> 4) & 0xf]; + out[iter * 2 + 1] = HEX[bytes[iter] & 0xf]; + } + return new String(out); + } + + /// The SHA-256 of `text`, in hex. What is stored in place of a secret that + /// only ever needs to be compared. + public static String sha256(String text) throws IOException { + return hex(Crypto.sha256(text.getBytes("UTF-8"))); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Roles.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Roles.java new file mode 100644 index 00000000000..b7e5c8aa846 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Roles.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +/// The two roles. Every account is a PLAYER; an ADMIN also gets god mode. +public final class Roles { + public static final String PLAYER = "PLAYER"; + public static final String ADMIN = "ADMIN"; + + private Roles() { + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/SecurityConfig.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/SecurityConfig.java new file mode 100644 index 00000000000..60d4408d351 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/SecurityConfig.java @@ -0,0 +1,402 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.Config; +import com.codename1.backend.DataSource; +import com.codename1.backend.HttpServer; +import com.codename1.backend.annotations.Bean; +import com.codename1.backend.annotations.Configuration; +import com.codename1.backend.annotations.Order; +import com.codename1.backend.annotations.Value; +import com.codename1.backend.security.AntPathRequestMatcher; +import com.codename1.backend.security.DisabledException; +import com.codename1.backend.security.GrantedAuthority; +import com.codename1.backend.security.HttpSecurity; +import com.codename1.backend.security.HttpStatusReturningLogoutSuccessHandler; +import com.codename1.backend.security.LogoutFilter; +import com.codename1.backend.security.SecurityExchange; +import com.codename1.backend.security.SecurityFilter; +import com.codename1.backend.security.SecurityFilterChain; +import com.codename1.backend.security.SessionCreationPolicy; +import com.codename1.backend.security.core.userdetails.JdbcUserDetailsManager; +import com.codename1.backend.security.core.userdetails.UserDetails; +import com.codename1.backend.security.crypto.JwkSource; +import com.codename1.backend.security.crypto.PasswordEncoder; +import com.codename1.backend.security.crypto.PasswordEncoderFactories; +import com.codename1.backend.security.oauth2.core.AuthorizationGrantType; +import com.codename1.backend.security.oauth2.core.ClientAuthenticationMethod; +import com.codename1.backend.security.oauth2.jwt.DefaultJwtDecoder; +import com.codename1.backend.security.oauth2.jwt.JwtAudienceValidator; +import com.codename1.backend.security.oauth2.jwt.JwtClaimValidator; +import com.codename1.backend.security.oauth2.jwt.JwtIssuerValidator; +import com.codename1.backend.security.oauth2.jwt.JwtValidators; +import com.codename1.backend.security.oauth2.server.authorization.AuthorizationServerKeys; +import com.codename1.backend.security.oauth2.server.authorization.AuthorizationServerSettings; +import com.codename1.backend.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService; +import com.codename1.backend.security.oauth2.server.authorization.JdbcRegisteredClientRepository; +import com.codename1.backend.security.oauth2.server.authorization.OAuth2AuthorizationService; +import com.codename1.backend.security.oauth2.server.authorization.RegisteredClient; +import com.codename1.backend.security.oauth2.server.authorization.RegisteredClientRepository; +import com.codename1.backend.security.oauth2.server.resource.JwtAuthenticationConverter; +import com.codename1.backend.security.ratelimit.InMemoryRateLimiter; +import com.codename1.backend.security.ratelimit.RateLimitKeys; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; + +/// Who may call what. +/// +/// This server is two things at once, and has a filter chain for each: +/// +/// - **An authorization server.** The app signs a user in here -- e-mail and +/// password, then the authorization-code flow with PKCE -- and gets a +/// short-lived access token and a refresh token. Nothing but this server ever +/// sees the password. +/// - **An API.** Everything under `/api` takes that access token as a bearer +/// token, keeps no session, and decides from the account's roles what the +/// caller may do. +/// +/// The roles are PLAYER and ADMIN ([Roles]). `/api/admin` is god mode and +/// for admins only; the rest is for anyone signed in and acts on the caller's +/// own account, scores and wallet. +@Configuration +public class SecurityConfig { + /// The id the app signs in as. A public client: it holds no secret, since + /// anything shipped inside an app can be read out of it, and proves itself + /// with PKCE instead. + public static final String CLIENT_ID = "ledge-app"; + /// Where the authorization code is sent back to. The app makes the requests + /// of the flow itself and reads the code out of the redirect, so this is + /// never opened; it is the loopback address because that is the one address + /// nobody else can register a listener on. An app that signs in through the + /// system browser adds its own address scheme here with `redirectUri`. + public static final String LOOPBACK_REDIRECT = "http://127.0.0.1/callback"; + /// Where the code is sent back to when the app runs in a browser: a path on + /// this server, which answers with the code it was given. See + /// [#withWebRedirect]. + public static final String WEB_REDIRECT_PATH = "/signin/code"; + /// Whom the access tokens are for. The API accepts no token issued for + /// anything else. + public static final String AUDIENCE = "urn:ledge:api"; + public static final String ISSUER_KEY = "cn1.security.authorizationserver.issuer"; + + @Bean + public PasswordEncoder passwordEncoder() { + return PasswordEncoderFactories.createDelegatingPasswordEncoder(); + } + + /// The accounts, in the tables `cn1.security.schema.enabled` creates. + @Bean + public JdbcUserDetailsManager users(DataSource db) { + return new JdbcUserDetailsManager(db); + } + + @Bean + public RegisteredClientRepository clients(DataSource db, + @Value("${" + ISSUER_KEY + ":}") final String issuer) throws IOException { + final JdbcRegisteredClientRepository clients = new JdbcRegisteredClientRepository(db); + if (clients.findByClientId(CLIENT_ID) == null) { + clients.save(RegisteredClient.withId("ledge").clientId(CLIENT_ID) + .clientName("Ledge") + .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) + .redirectUri(LOOPBACK_REDIRECT) + .scope("openid").scope("profile") + .build()); + } + // The app in a browser is the same client with one more address: this + // server's own. It is worked out and not stored, because on a + // development profile the server has no one address to store -- and a + // row written by an earlier version would not have it either. + return new RegisteredClientRepository() { + @Override + public void save(RegisteredClient client) { + clients.save(client); + } + + @Override + public RegisteredClient findByClientId(String clientId) { + return withWebRedirect(clients.findByClientId(clientId), issuer); + } + + @Override + public RegisteredClient findById(String id) { + return withWebRedirect(clients.findById(id), issuer); + } + }; + } + + /// The app's registration with [#WEB_REDIRECT_PATH] on this server added + /// to the addresses a code may be sent back to. + /// + /// A browser will not show a page the answer to a request that was + /// redirected to another origin, so the app running in one cannot read its + /// code off a redirect to the loopback address the way the installed app + /// does. It asks for the code to be sent to this server instead, which + /// hands it straight back ([SignInCodePage]). + /// + /// "This server" is the configured issuer where there is one, and is then + /// the only web address accepted. With none -- a development profile -- it + /// is the address the request arrived at, the same rule + /// [#issuedAtThisAddress] holds a token to: a code is only ever sent back + /// to the server the browser was already talking to. + static RegisteredClient withWebRedirect(RegisteredClient client, String issuer) { + if (client == null || !CLIENT_ID.equals(client.getClientId())) { + return client; + } + String here = here(issuer); + if (here == null) { + return client; + } + RegisteredClient.Builder copy = RegisteredClient.withId(client.getId()) + .clientId(client.getClientId()) + .clientName(client.getClientName()) + .clientSettings(client.getClientSettings()) + .tokenSettings(client.getTokenSettings()) + .redirectUri(here + WEB_REDIRECT_PATH); + for (ClientAuthenticationMethod method : client.getClientAuthenticationMethods()) { + copy.clientAuthenticationMethod(method); + } + for (AuthorizationGrantType grant : client.getAuthorizationGrantTypes()) { + copy.authorizationGrantType(grant); + } + for (String uri : client.getRedirectUris()) { + copy.redirectUri(uri); + } + for (String scope : client.getScopes()) { + copy.scope(scope); + } + for (String resource : client.getResources()) { + copy.resource(resource); + } + return copy.build(); + } + + /// Refuses a request that changes something and was sent by a page of + /// another site. + /// + /// A browser names the site a request came from in `Origin` on every + /// request that is not a plain read, and a page cannot change or drop it. + /// The installed app is not a browser and sends none, so a request without + /// one is let through: there is no cookie jar of somebody else's for it to + /// be riding on. + static SecurityFilter sameOrigin(final String issuer) { + return (request, chain) -> { + String method = request.getMethod(); + if ("GET".equals(method) || "HEAD".equals(method) || "OPTIONS".equals(method)) { + return chain.doFilter(request); + } + String origin = request.getHeader("Origin"); + if (origin == null || origin.length() == 0) { + return chain.doFilter(request); + } + String here = here(issuer); + if (here != null && sameOrigin(origin, here)) { + return chain.doFilter(request); + } + return new HttpServer.Response(403, "application/json", + "{\"error\":\"cross_origin\"}".getBytes("UTF-8")) + .header("Cache-Control", "no-store"); + }; + } + + /// This server's address: the configured issuer, and with none -- a + /// development profile -- the address the request in hand arrived at. Null + /// outside a request that says. + static String here(String issuer) { + if (issuer != null && issuer.length() > 0) { + return issuer; + } + SecurityExchange exchange = SecurityExchange.current(); + String host = exchange == null ? null : exchange.getRequest().getHeader("Host"); + if (host == null || host.length() == 0) { + return null; + } + return (exchange.isSecure() ? "https://" : "http://") + host; + } + + /// Whether `origin` is the origin of `address`: the same scheme, host and + /// port, whatever path the address goes on to name. Scheme and host are + /// compared without regard to case, and without folding it -- that would + /// depend on the language the server runs in. + static boolean sameOrigin(String origin, String address) { + int path = address.indexOf('/', address.indexOf("://") + 3); + String root = path < 0 ? address : address.substring(0, path); + return origin.equalsIgnoreCase(root); + } + + /// Kept in the database, so a refresh token outlives a restart and is good + /// on every instance of the server. + @Bean + public OAuth2AuthorizationService authorizations(DataSource db) { + return new JdbcOAuth2AuthorizationService(db); + } + + /// The keys the tokens are signed with: the files named by + /// `cn1.security.authorizationserver.jwk.keys`. On a development profile + /// with none configured, a key made at start-up -- which is why signing in + /// again is needed after restarting a development server. + @Bean + public JwkSource signingKeys(Config config) throws IOException { + return AuthorizationServerKeys.load(config); + } + + /// Signing in. A session exists here and only here, for the few requests + /// between the password being accepted and the code being handed over; + /// the app ends it with `POST /logout` once it has its tokens, and one it + /// never ends runs out after `cn1.session.timeout` seconds without a + /// request, half an hour unless set. + @Bean + @Order(1) + public SecurityFilterChain signIn(HttpSecurity http, + @Value("${" + ISSUER_KEY + ":}") final String issuer, + @Value("${ledge.signin.per-minute:10}") int signInsPerMinute) throws IOException { + http.securityMatcher("/oauth2/**", "/.well-known/**", "/userinfo", "/login", "/login/**", + "/logout") + .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) + // No CSRF token: the app posts the sign-in form itself, from its own + // screen, and would have to fetch a token first to send one. What a + // token is for still has to be done, because the app also runs in a + // browser, where the session is a cookie the browser keeps and would + // send along with a form another site submitted -- signing its + // visitor in as somebody else. Two things stand in for it. The + // session cookie is `SameSite=Lax`, the server's default, so it does + // not travel with another site's request; and [#sameOrigin] below + // refuses any request that changes something and says it came from + // another site, which is the one a forged sign-in is. A server that + // signs people in through a page it serves keeps CSRF on. + .csrf(csrf -> csrf.disable()) + .addFilterBefore(sameOrigin(issuer), LogoutFilter.class) + // Signing out is a POST and nothing else -- with CSRF off the + // default takes a GET too, which an image tag on any page can send + // -- and is answered with a status, for the reason signing in is. + .logout(logout -> logout + .logoutRequestMatcher(AntPathRequestMatcher.antMatcher("POST", "/logout")) + .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(204))) + // And it is answered with a status, not a redirect to a page: + // the app in a browser cannot see a redirect or the cookie, only + // how the request ended, so that has to be the answer. The session + // cookie is set either way; the installed app reads it, a browser + // keeps it. + .formLogin(form -> form + .successHandler((request, authentication) -> new HttpServer.Response(200, + "application/json", "{\"signedIn\":true}".getBytes("UTF-8")) + .header("Cache-Control", "no-store")) + .failureHandler((request, refused) -> new HttpServer.Response(401, + "application/json", "{\"signedIn\":false}".getBytes("UTF-8")) + .header("Cache-Control", "no-store"))) + // Guessing passwords is the attack on this chain. Ten tries a minute + // from one address, unless `ledge.signin.per-minute` says otherwise: + // the end-to-end tests are many people signing in from one address, + // and their profile raises it. + .rateLimit("/login", RateLimitKeys.clientAddress(), + new InMemoryRateLimiter(signInsPerMinute, 60)) + .authorizationServer(server -> server + .settings(AuthorizationServerSettings.builder() + .defaultAudience(AUDIENCE).build())); + return http.build(); + } + + /// The API. Stateless: every request stands on its own bearer token. + @Bean + @Order(2) + public SecurityFilterChain api(HttpSecurity http, JwkSource signingKeys, + @Value("${" + ISSUER_KEY + ":}") final String issuer, + JdbcUserDetailsManager users) throws IOException { + DefaultJwtDecoder decoder = DefaultJwtDecoder.withJwkSource(signingKeys).build(); + decoder.setJwtValidator(JwtValidators.createDefaultWithValidators( + new JwtAudienceValidator(AUDIENCE), + issuer.length() > 0 ? new JwtIssuerValidator(issuer) + : new JwtClaimValidator("iss", SecurityConfig::issuedAtThisAddress))); + + // The token says who the caller is and nothing about what they may do. + // The roles are read from the account on every request instead of being + // copied into the token, for one reason: an admin who withdraws a role + // or suspends an account means now, not when the token runs out. It + // costs a lookup by primary key per request. + JwtAuthenticationConverter roles = new JwtAuthenticationConverter(); + roles.setJwtGrantedAuthoritiesConverter(jwt -> { + String name = jwt.getSubject(); + if (name == null || !users.userExists(name)) { + throw new DisabledException("No such account"); + } + UserDetails account = users.loadUserByUsername(name); + if (!account.isEnabled() || !account.isAccountNonLocked()) { + throw new DisabledException("This account is suspended"); + } + Collection held = new ArrayList(); + held.addAll(account.getAuthorities()); + return held; + }); + + http.securityMatcher("/api/**") + .sessionManagement(session -> + session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + // Opening accounts is the one thing here that costs something + // each time and that a stranger can ask for. + .rateLimit("/api/account/register", RateLimitKeys.clientAddress(), + new InMemoryRateLimiter(20, 3600)) + // Receipts are checked against the store, in the game's name. + .rateLimit("/api/shop/receipt", + RateLimitKeys.firstOf(RateLimitKeys.principal(), RateLimitKeys.clientAddress()), + new InMemoryRateLimiter(60, 3600)) + // Rewarded ads are capped per day in Shop; this keeps a script + // from hammering the route to find out. + .rateLimit("/api/shop/ad-reward", + RateLimitKeys.firstOf(RateLimitKeys.principal(), RateLimitKeys.clientAddress()), + new InMemoryRateLimiter(30, 3600)) + // Every finished run is replayed in full on the server. + .rateLimit("/api/runs/start", RateLimitKeys.principal(), + new InMemoryRateLimiter(240, 3600)) + .rateLimit("/api/runs", RateLimitKeys.principal(), + new InMemoryRateLimiter(240, 3600)) + // A generated level is a model call and a solver search: each + // player gets a handful an hour. + .rateLimit("/api/levels/generate", RateLimitKeys.principal(), + new InMemoryRateLimiter(20, 3600)) + // tag::ledge-api-access[] + .authorizeHttpRequests(auth -> auth + .requestMatchers(AntPathRequestMatcher.antMatcher("POST", + "/api/account/register")).permitAll() + .requestMatchers("/api/admin/**").hasRole(Roles.ADMIN) + .anyRequest().authenticated()) + // end::ledge-api-access[] + .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(decoder) + .jwtAuthenticationConverter(roles))); + return http.build(); + } + + /// Whether a token's issuer is the address this request came to. + /// + /// Used only when no issuer is configured, which the server allows only on + /// a development profile: it then issues tokens in the name of whatever + /// address each request arrived at, so that is the name to hold a token to. + static boolean issuedAtThisAddress(Object issuer) { + SecurityExchange exchange = SecurityExchange.current(); + if (exchange == null || !(issuer instanceof String)) { + return false; + } + String host = exchange.getRequest().getHeader("Host"); + return host != null && ((exchange.isSecure() ? "https://" : "http://") + host) + .equals(issuer); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Services.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Services.java new file mode 100644 index 00000000000..fa4cb7e2172 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/Services.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.Config; +import com.codename1.backend.annotations.Bean; +import com.codename1.backend.annotations.Configuration; +import com.codename1.backend.annotations.Value; +import com.codename1.backend.push.CloudPush; +import com.codename1.appkit.server.push.CloudPushSender; +import com.codename1.appkit.server.push.ConsolePushSender; +import com.codename1.appkit.server.push.MisconfiguredPushSender; +import com.codename1.appkit.server.push.PushSender; +import com.codename1.appkit.server.push.RecordingPushSender; +import com.codenameone.examples.ledge.shop.MisconfiguredReceipts; +import com.codenameone.examples.ledge.shop.ReceiptValidator; +import com.codenameone.examples.ledge.shop.SimulatedReceipts; +import com.codenameone.examples.ledge.shop.StoreReceipts; + +/// The services this server reaches outside itself for, each behind an +/// interface and each chosen here from the settings. A development profile +/// (dev, test, local) gets the stand-in that needs no account; any other +/// profile gets the real one, and when its settings are missing the server +/// still starts and fails every call with a message naming them. It never +/// quietly falls back to a stand-in. +/// +/// Every setting is also read from the environment, in upper case with `_` +/// for each `.` (`LEDGE_IAP_APPLE_SECRET`), which is where secrets belong. +@Configuration +public class Services { + // tag::ledge-receipt-choice[] + /// `ledge.iap.provider` is one of: + /// + /// - `store`: receipts are checked with Apple (`ledge.iap.apple.secret`) + /// and Google Play (`ledge.iap.google.package` and + /// `ledge.iap.google.token`). A store with no settings refuses its + /// receipts; the other keeps working. + /// - `simulated`: every receipt is accepted, on a development profile only. + /// + /// Unset, it is `simulated` on a development profile and `store` otherwise. + @Bean + public ReceiptValidator receipts(Config config, + @Value("${ledge.iap.provider:}") String chosen, + @Value("${ledge.iap.apple.secret:}") String appleSecret, + @Value("${ledge.iap.apple.bundle:}") String appleBundle, + @Value("${ledge.iap.google.package:}") String googlePackage, + @Value("${ledge.iap.google.token:}") String googleToken) { + String kind = chosen.trim().length() > 0 ? chosen.trim() + : config.isDevelopmentProfile() ? "simulated" : "store"; + if ("simulated".equalsIgnoreCase(kind)) { + if (!config.isDevelopmentProfile()) { + return new MisconfiguredReceipts("ledge.iap.provider=simulated grants every " + + "purchase for free and is refused on the '" + config.getProfile() + + "' profile; set it to store"); + } + return new SimulatedReceipts(); + } + if (!"store".equalsIgnoreCase(kind)) { + return new MisconfiguredReceipts("ledge.iap.provider is '" + kind + + "', which is neither store nor simulated"); + } + if (appleSecret.trim().length() == 0 && (googlePackage.trim().length() == 0 + || googleToken.trim().length() == 0)) { + return new MisconfiguredReceipts("in-app purchases are not configured; set " + + "ledge.iap.apple.secret, or ledge.iap.google.package and " + + "ledge.iap.google.token"); + } + if (appleSecret.trim().length() > 0 && appleBundle.trim().length() == 0) { + // Without it, a genuine receipt from any other app could buy coins. + return new MisconfiguredReceipts("ledge.iap.apple.secret is set without " + + "ledge.iap.apple.bundle, the bundle id receipts must belong to"); + } + return new StoreReceipts(appleSecret.trim(), appleBundle.trim(), googlePackage.trim(), googleToken.trim()); + } + // end::ledge-receipt-choice[] + + // tag::ledge-push-choice[] + /// `ledge.push.provider` is one of: + /// + /// - `cloud`: the Codename One push service. It needs `ledge.push.app`, + /// the app's push id, and `ledge.push.key`, a server key with the push + /// scope; both are in the Push section of the Codename One console. + /// - `console`: prints each notification, on a development profile only. + /// - `recording`: keeps each notification for the tests to read, on a + /// development profile only. + /// + /// Unset, it is `recording` on the `test` profile, `console` on the other + /// development profiles and `cloud` otherwise. A server whose push settings + /// are missing still starts and still serves deliveries: it logs a configuration + /// error at start-up and again for every notification it could not send. + @Bean + public PushSender pushSender(Config config, + @Value("${ledge.push.provider:}") String chosen, + @Value("${ledge.push.app:}") String app, + @Value("${ledge.push.key:}") String key, + @Value("${ledge.push.url:}") String url) { + String kind = chosen.trim().length() > 0 ? chosen.trim() + : "test".equals(config.getProfile()) ? "recording" + : config.isDevelopmentProfile() ? "console" : "cloud"; + if ("console".equalsIgnoreCase(kind) || "recording".equalsIgnoreCase(kind)) { + if (!config.isDevelopmentProfile()) { + return new MisconfiguredPushSender("ledge.push.provider=" + kind + + " sends nothing and is refused on the '" + config.getProfile() + + "' profile; set it to cloud"); + } + return "console".equalsIgnoreCase(kind) ? new ConsolePushSender() + : new RecordingPushSender(); + } + if (!"cloud".equalsIgnoreCase(kind)) { + return new MisconfiguredPushSender("ledge.push.provider is '" + kind + + "', which is none of cloud, console or recording"); + } + String missing = missing("ledge.push.", new String[] {"app", app, "key", key}); + if (missing.length() > 0) { + return new MisconfiguredPushSender(unset("push", "cloud", missing)); + } + try { + CloudPush push = new CloudPush(app.trim(), key.trim()); + return new CloudPushSender(url.trim().length() > 0 ? push.withEndpoint(url.trim()) + : push); + } catch (IllegalArgumentException err) { + return new MisconfiguredPushSender("push provider 'cloud' is misconfigured: " + + err.getMessage()); + } + } + // end::ledge-push-choice[] + + /// The names, after `prefix`, of the settings in `namesAndValues` whose + /// value is empty, separated by commas. + private static String missing(String prefix, String[] namesAndValues) { + StringBuilder out = new StringBuilder(); + for (int iter = 0; iter + 1 < namesAndValues.length; iter += 2) { + if (namesAndValues[iter + 1] == null || namesAndValues[iter + 1].trim().length() == 0) { + if (out.length() > 0) { + out.append(", "); + } + out.append(prefix).append(namesAndValues[iter]); + } + } + return out.toString(); + } + + private static String unset(String service, String provider, String missing) { + return service + " provider '" + provider + "' is not configured; set " + missing; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/SignInCodePage.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/SignInCodePage.java new file mode 100644 index 00000000000..b7abbae8e0b --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/SignInCodePage.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.HttpServer; +import com.codename1.backend.Json; +import com.codename1.backend.annotations.GetMapping; +import com.codename1.backend.annotations.RequestParam; +import com.codename1.backend.annotations.RestController; + +import java.util.LinkedHashMap; +import java.util.Map; + +/// Where a sign-in from a browser ends: the authorization code, handed back. +/// +/// The installed app asks for its code to be sent to a loopback address and +/// reads it off the redirect without following it. A page in a browser cannot +/// do that -- the browser follows the redirect itself and shows the page only +/// what it found at the end -- so the app running in one asks for the code to +/// be sent here, and what is at the end is the code. +/// +/// Nothing is decided here and nothing is trusted: the code arrived in the +/// address, so repeating it tells the caller nothing it did not have, and it +/// is worth nothing without the PKCE verifier only the app that started the +/// sign-in holds. That is why this needs no sign-in of its own. +@RestController +public class SignInCodePage { + @GetMapping(SecurityConfig.WEB_REDIRECT_PATH) + public HttpServer.Response code( + @RequestParam(value = "code", required = false) String code, + @RequestParam(value = "state", required = false) String state, + @RequestParam(value = "error", required = false) String error) throws Exception { + Map answer = new LinkedHashMap(); + if (code != null) { + answer.put("code", code); + } + if (state != null) { + answer.put("state", state); + } + if (error != null) { + answer.put("error", error); + } + return new HttpServer.Response(code == null ? 400 : 200, "application/json", + Json.write(answer).getBytes("UTF-8")) + // A code is good once, for a few minutes; nothing should keep it. + .header("Cache-Control", "no-store") + // And nothing should read it as anything but data: the values + // come from the address, which anyone can write a link to. + .header("X-Content-Type-Options", "nosniff"); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/AccountEndpoint.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/AccountEndpoint.java new file mode 100644 index 00000000000..f9189d5b9c5 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/AccountEndpoint.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.account; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.ledge.api.AccountApiServer; +import com.codenameone.examples.ledge.api.PlayerDto; +import com.codenameone.examples.ledge.api.ProfileDto; +import com.codenameone.examples.ledge.api.PushDeviceDto; +import com.codenameone.examples.ledge.api.RegisterDto; +import com.codenameone.examples.ledge.push.PushDevices; + +/// `AccountApi` on the server: every call acts on the caller's own account. +@Component +public class AccountEndpoint implements AccountApiServer { + private final Accounts accounts; + private final PushDevices devices; + + public AccountEndpoint(Accounts accounts, PushDevices devices) { + this.accounts = accounts; + this.devices = devices; + } + + @Override + public PlayerDto register(RegisterDto request) throws Exception { + return accounts.register(request); + } + + @Override + public PlayerDto me() throws Exception { + return accounts.me(Caller.name()); + } + + @Override + public PlayerDto saveProfile(ProfileDto profile) throws Exception { + return accounts.saveProfile(Caller.name(), profile); + } + + @Override + public PushDeviceDto registerPush(PushDeviceDto device) throws Exception { + return devices.register(Caller.name(), device); + } + + @Override + public PushDeviceDto unregisterPush(PushDeviceDto device) throws Exception { + return devices.unregister(Caller.name(), device); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/Accounts.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/Accounts.java new file mode 100644 index 00000000000..1912784ecae --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/Accounts.java @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.account; + +import com.codename1.appkit.server.Text; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.backend.security.GrantedAuthority; +import com.codename1.backend.security.core.userdetails.JdbcUserDetailsManager; +import com.codename1.backend.security.core.userdetails.User; +import com.codename1.backend.security.core.userdetails.UserDetails; +import com.codename1.backend.security.crypto.PasswordEncoder; +import com.codenameone.examples.ledge.Roles; +import com.codenameone.examples.ledge.api.PlayerDto; +import com.codenameone.examples.ledge.api.ProfileDto; +import com.codenameone.examples.ledge.api.RegisterDto; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.progress.Progress; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.shop.Catalog; +import java.io.IOException; +import java.time.Instant; +import java.util.Iterator; + +/// Accounts: the sign-in record (users and authorities, owned by the security +/// layer) plus the [Profile] row that holds everything the game knows. +@Component +public class Accounts { + /// What a new player's wallet starts with: a taste, not enough for a scarf. + public static final int START_COINS = 50; + + private final ProfileRepository profiles; + private final JdbcUserDetailsManager users; + private final PasswordEncoder encoder; + + public Accounts(ProfileRepository profiles, JdbcUserDetailsManager users, PasswordEncoder encoder) { + this.profiles = profiles; + this.users = users; + this.encoder = encoder; + } + + public PlayerDto register(RegisterDto request) throws IOException { + if (request == null) { + throw new ResponseStatusException(400, "Nothing to register"); + } + String username = email(request.email()); + password(request.password()); + String name = displayName(request.displayName()); + if (users.userExists(username)) { + throw new ResponseStatusException(409, "That e-mail already has an account"); + } + try { + create(username, request.password(), name, false); + } catch (IOException | RuntimeException failed) { + // Two registrations racing for one address: the loser sees 409, + // not whatever the database said about the duplicate key. + if (users.userExists(username)) { + throw new ResponseStatusException(409, "That e-mail already has an account"); + } + throw failed; + } + return describe(username); + } + + @Transactional(rollbackFor = IOException.class) + public void create(String username, String password, String name, boolean admin) throws IOException { + users.createUser(User.withUsername(username).password(encoder.encode(password)) + .roles(admin ? new String[] {Roles.PLAYER, Roles.ADMIN} : new String[] {Roles.PLAYER}) + .build()); + Profile p = new Profile(); + p.setUsername(username); + p.setDisplayName(name); + p.setCoins(START_COINS); + p.setProgress(Progress.EMPTY); + p.setScarf(Catalog.FREE_SCARF); + p.setOwned(Catalog.FREE_SCARF); + p.setCreatedAt(Instant.now()); + p.setLastSeen(Instant.now()); + profiles.insert(p); + } + + public boolean exists(String username) { + return users.userExists(username); + } + + /// Adds coins to a player, as the demo seeding does. + /// + /// #### Parameters + /// + /// - `username`: the player + /// - `coins`: how many + /// + /// #### Throws + /// + /// - `IOException`: when the store fails + public void grant(String username, int coins) throws IOException { + Profile p = profiles.findById(username); + if (p != null) { + p.setCoins(p.getCoins() + coins); + profiles.save(p); + } + } + + /// The signed-in player, which also counts as being seen today: the + /// console's "active today" and a lapsed broadcast both read `lastSeen`. + @Transactional(rollbackFor = IOException.class) + public PlayerDto me(String username) throws IOException { + Profile p = profile(username); + p.setLastSeen(Instant.now()); + profiles.save(p); + return toDto(p); + } + + @Transactional(readOnly = true) + public PlayerDto describe(String username) throws IOException { + Profile p = profiles.findById(username); + if (p == null || !users.userExists(username)) { + throw new ResponseStatusException(404, "No such account"); + } + return toDto(p); + } + + public PlayerDto toDto(Profile p) { + UserDetails signIn = users.loadUserByUsername(p.getUsername()); + return new PlayerDto(p.getUsername(), p.getDisplayName(), p.getCoins(), + Progress.of(p.getProgress()), p.getBestDaily(), p.getRuns(), isAdmin(signIn), + !signIn.isEnabled() || isBenched(p), p.isFlagged(), p.getScarf(), + Lists.split(p.getOwned())); + } + + /// Changes the name and, when given, the equipped scarf (which must be owned). + @Transactional(rollbackFor = IOException.class) + public PlayerDto saveProfile(String username, ProfileDto profile) throws IOException { + if (profile == null) { + throw new ResponseStatusException(400, "Nothing to save"); + } + Profile p = profile(username); + if (profile.displayName() != null) { + p.setDisplayName(displayName(profile.displayName())); + } + if (profile.scarf() != null && profile.scarf().length() > 0) { + if (!Lists.contains(p.getOwned(), profile.scarf())) { + throw new ResponseStatusException(403, "You do not own that scarf"); + } + p.setScarf(profile.scarf()); + } + profiles.save(p); + return toDto(p); + } + + /// Whether a player is kept off the boards: banned, or suspended until a + /// time still to come. + public static boolean isBenched(Profile p) { + return p.isBanned() || p.getSuspendedUntil().toEpochMilli() > System.currentTimeMillis(); + } + + /// Enables or disables sign-in. A disabled account's tokens stop working on + /// its next request ([com.codenameone.examples.ledge.SecurityConfig] reads + /// the account every time). + public void setEnabled(String username, boolean enabled) { + UserDetails signIn = users.loadUserByUsername(username); + if (signIn.isEnabled() != enabled) { + users.updateUser(User.withUserDetails(signIn).disabled(!enabled).build()); + } + } + + public boolean isAdmin(String username) { + return users.userExists(username) && isAdmin(users.loadUserByUsername(username)); + } + + private static boolean isAdmin(UserDetails signIn) { + Iterator it = signIn.getAuthorities().iterator(); + while (it.hasNext()) { + if (("ROLE_" + Roles.ADMIN).equals(it.next().getAuthority())) { + return true; + } + } + return false; + } + + @Transactional(readOnly = true) + public Profile profile(String username) { + Profile p = profiles.findById(username); + if (p == null) { + throw new ResponseStatusException(404, "No such account"); + } + return p; + } + + /// An e-mail address, folded to lower case by hand: `toLowerCase` depends + /// on the language the server runs in. + public static String email(String value) { + String text = value == null ? "" : value.trim(); + int at = text.indexOf('@'); + if (at < 1 || at != text.lastIndexOf('@') || at > text.length() - 4 + || text.indexOf('.', at) < 0 || text.length() > 190) { + throw new ResponseStatusException(400, "That is not an e-mail address"); + } + StringBuilder out = new StringBuilder(text.length()); + for (int i = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c <= ' ' || c > '~') { + throw new ResponseStatusException(400, "That is not an e-mail address"); + } + out.append(c >= 'A' && c <= 'Z' ? (char) (c + ('a' - 'A')) : c); + } + return out.toString(); + } + + static void password(String value) { + if (value == null || value.length() < 8) { + throw new ResponseStatusException(400, "Choose a password of at least 8 characters"); + } + if (value.length() > 200) { + throw new ResponseStatusException(400, "That password is too long"); + } + } + + /// A player name: 3 to 20 characters, shown on every board, so control + /// characters and leading or trailing spaces are refused. + static String displayName(String value) { + String name = Text.required(value, 20, "your player name").trim(); + if (name.length() < 3) { + throw new ResponseStatusException(400, "A player name needs at least 3 characters"); + } + for (int i = 0; i < name.length(); i++) { + if (name.charAt(i) < ' ') { + throw new ResponseStatusException(400, "That name has characters we cannot show"); + } + } + return name; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/DemoAccounts.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/DemoAccounts.java new file mode 100644 index 00000000000..3a53126aab6 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/DemoAccounts.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.account; + +import com.codename1.backend.Config; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.PostConstruct; +import com.codename1.backend.annotations.Value; +import com.codenameone.examples.ledge.Clock; +import com.codename1.gaming.platformer.Input; +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.Replay; +import com.codenameone.examples.ledge.admin.Flags; +import com.codenameone.examples.ledge.friends.Friends; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.run.Runs; +import java.io.IOException; + +/// The accounts a development server starts with: a player and a rival to +/// compare scores, a player with a flagged run for the console to find, an +/// admin, and a field of rivals who have cleared different stretches of the +/// level pack, some this week and some today, so every board, every ghost and +/// the daily have something on them. +/// +/// Every run is real: the level's shipped solver input (`LevelPack.demo`), +/// replayed through `Scoring` on seed 1 exactly as a submitted run is. +/// Anywhere else only the admin is made, and only when `ledge.admin.email` +/// and `ledge.admin.password` say who. +@Component +public class DemoAccounts { + public static final String PLAYER = "player@ledge.example"; + public static final String RIVAL = "rival@ledge.example"; + public static final String TROUBLE = "trouble@ledge.example"; + public static final String ADMIN = "admin@ledge.example"; + public static final String PASSWORD = "ledge-demo"; + + /// The seed the shipped solver inputs finish every level on. + private static final long SEED = 1; + + private static final String[] FIELD = { + "Hopper", "Wren", "Cinder", "Moss", "Pip", "Bramble", "Skye", "Flint", + "Juniper", "Rook", "Tumble", "Sorrel", "Kestrel", "Nettle", "Ash" + }; + + private final Accounts accounts; + private final Runs runs; + private final Friends friends; + private final Flags flags; + private final Config config; + private final String adminEmail; + private final String adminPassword; + + public DemoAccounts(Accounts accounts, Runs runs, Friends friends, Flags flags, Config config, + @Value("${ledge.admin.email:}") String adminEmail, + @Value("${ledge.admin.password:}") String adminPassword) { + this.accounts = accounts; + this.runs = runs; + this.friends = friends; + this.flags = flags; + this.config = config; + this.adminEmail = adminEmail; + this.adminPassword = adminPassword; + } + + @PostConstruct + public void seed() throws IOException { + if (!config.isDevelopmentProfile()) { + if (adminEmail.length() > 0 && adminPassword.length() >= 8 + && !accounts.exists(Accounts.email(adminEmail))) { + accounts.create(Accounts.email(adminEmail), adminPassword, "Administrator", true); + } + return; + } + if (accounts.exists(PLAYER)) { + // Seeded on an earlier start against a database that kept it. + return; + } + long now = Clock.now(); + accounts.create(PLAYER, PASSWORD, "Riley", false); + accounts.create(RIVAL, PASSWORD, "Morgan", false); + accounts.create(ADMIN, PASSWORD, "Editor in Chief", true); + accounts.create(TROUBLE, PASSWORD, "Too Sharp", false); + Replay.Result[] solved = new Replay.Result[LevelPack.IDS.length]; + for (int i = 0; i < solved.length; i++) { + String demo = LevelPack.demo(i); + Replay.Result r = demo.length() == 0 ? null : Scoring.replay(i, SEED, demo); + solved[i] = r != null && r.isComplete() ? r : null; + } + clear(solved, PLAYER, 5, now - 3 * Clock.DAY); + // Enough for a first scarf, so the shop can be tried straight away. + accounts.grant(PLAYER, 300); + clear(solved, RIVAL, 7, now - 2 * 60 * 60 * 1000L); + clear(solved, TROUBLE, 2, now - 30 * 60 * 1000L); + flags.report(TROUBLE, "Reported by other players"); + for (int i = 0; i < FIELD.length; i++) { + String who = "rival" + (i + 1) + "@ledge.example"; + accounts.create(who, PASSWORD, FIELD[i], false); + // An old player, one active this week, or one who played today. + long[] ages = {20 * Clock.DAY, 2 * Clock.DAY, 60 * 60 * 1000L}; + clear(solved, who, 1 + i % solved.length, now - ages[i % ages.length] - i * 60000L); + } + attempts(solved, now); + friends.add(PLAYER, RIVAL); + friends.add(PLAYER, "rival1@ledge.example"); + friends.add(PLAYER, "rival2@ledge.example"); + } + + /// Plays the first `levels` levels as `who`, the shipped solver's input on + /// seed 1, all of them at `when`. + private void clear(Replay.Result[] solved, String who, int levels, long when) throws IOException { + for (int i = 0; i < levels && i < solved.length; i++) { + if (solved[i] != null) { + // The solver's route with a pause that differs per player + // and level, so a board ranks a spread of times rather than + // one run repeated. The routes are frame-tight -- a pause at + // the spawn meets every enemy late -- so the pause goes at the + // last place along the route where standing still is safe, + // found by trying points back from the exit. + int wait = 15 + ((who.hashCode() ^ (i * 7919)) & 0x7fffffff) % 136; + int[] route = InputLog.decode(LevelPack.demo(i), Scoring.MAX_TICKS).toArray(); + String encoded = LevelPack.demo(i); + Replay.Result r = solved[i]; + for (int at = route.length - 10; at > 0 && route.length - at < 1200; at -= 20) { + InputLog log = new InputLog(); + for (int t = 0; t < at; t++) { + log.add(route[t]); + } + for (int t = 0; t < wait; t++) { + log.add(0); + } + for (int t = at; t < route.length; t++) { + log.add(route[t]); + } + Replay.Result paused = Scoring.replay(i, SEED, log.encode()); + if (paused != null && paused.isComplete()) { + encoded = log.encode(); + r = paused; + break; + } + } + runs.record(who, i, false, SEED, encoded, r, when + i * 1000L); + } + } + } + + /// Runs that died, for the console's death map: each follows the solver's + /// route for a while, then holds right and jumps blindly until the lives + /// run out, so the deaths land on the real hazards of the level. + private void attempts(Replay.Result[] solved, long now) throws IOException { + for (int i = 0; i < 5 && i < solved.length; i++) { + String demo = LevelPack.demo(i); + if (solved[i] == null || demo.length() == 0) { + continue; + } + int[] route = InputLog.decode(demo, Scoring.MAX_TICKS).toArray(); + for (int k = 1; k <= 12; k++) { + InputLog log = new InputLog(); + int follow = route.length * k / 14; + for (int t = 0; t < follow; t++) { + log.add(route[t]); + } + for (int t = 0; t < 1800; t++) { + log.add(Input.RIGHT | (t % 40 < 12 ? Input.JUMP : 0)); + } + String encoded = log.encode(); + Replay.Result r = Scoring.replay(i, SEED, encoded); + if (r != null && !r.isComplete()) { + runs.attempt("demo-" + k, i, SEED, encoded, r, now - k * 60000L); + } + } + } + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/Lists.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/Lists.java new file mode 100644 index 00000000000..b4205028e3b --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/account/Lists.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.account; + +import java.util.ArrayList; +import java.util.List; + +/// Comma-separated id lists, the way a profile stores its owned items. +public final class Lists { + private Lists() { + } + + public static String join(String[] items) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < items.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(items[i]); + } + return sb.toString(); + } + + public static String join(List items) { + return join(items.toArray(new String[items.size()])); + } + + public static List split(String csv) { + List out = new ArrayList(); + if (csv == null || csv.length() == 0) { + return out; + } + int start = 0; + for (int i = 0; i <= csv.length(); i++) { + if (i == csv.length() || csv.charAt(i) == ',') { + if (i > start) { + out.add(csv.substring(start, i)); + } + start = i + 1; + } + } + return out; + } + + /// Like [#split], but keeps empty fields, so positions line up: a row's + /// player list has an empty entry for each bot. + public static List fields(String csv) { + List out = new ArrayList(); + if (csv == null || csv.length() == 0) { + return out; + } + int start = 0; + for (int i = 0; i <= csv.length(); i++) { + if (i == csv.length() || csv.charAt(i) == ',') { + out.add(csv.substring(start, i)); + start = i + 1; + } + } + return out; + } + + public static boolean contains(String csv, String id) { + return split(csv).contains(id); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/AdminEndpoint.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/AdminEndpoint.java new file mode 100644 index 00000000000..16cd286a783 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/AdminEndpoint.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.admin; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.gaming.platformer.TileGrid; +import com.codename1.orm.repository.PageRequest; +import com.codenameone.examples.ledge.Clock; +import com.codenameone.examples.ledge.account.Accounts; +import com.codenameone.examples.ledge.api.AdminActionDto; +import com.codenameone.examples.ledge.api.AdminApiServer; +import com.codenameone.examples.ledge.api.AdminStatsDto; +import com.codenameone.examples.ledge.api.AuditDto; +import com.codenameone.examples.ledge.api.BroadcastDto; +import com.codenameone.examples.ledge.api.DailyDto; +import com.codenameone.examples.ledge.api.DailySeedDto; +import com.codenameone.examples.ledge.api.FlagDto; +import com.codenameone.examples.ledge.api.HeatmapDto; +import com.codenameone.examples.ledge.api.PlayerDto; +import com.codenameone.examples.ledge.api.ResolveDto; +import com.codenameone.examples.ledge.domain.Attempt; +import com.codenameone.examples.ledge.domain.Flag; +import com.codenameone.examples.ledge.levels.Heatmap; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.domain.ScoreRun; +import com.codenameone.examples.ledge.push.Broadcasts; +import com.codenameone.examples.ledge.repository.AttemptRepository; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import com.codenameone.examples.ledge.repository.StorePurchaseRepository; +import com.codenameone.examples.ledge.run.Boards; +import com.codename1.backend.ResponseStatusException; +import com.codenameone.examples.ledge.run.DailySeeds; +import com.codenameone.examples.ledge.run.Runs; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/// `AdminApi` on the server. The ADMIN role is enforced for all of +/// `/api/admin` in [com.codenameone.examples.ledge.SecurityConfig], so no +/// method here can forget it; everything that changes something is audited. +@Component +public class AdminEndpoint implements AdminApiServer { + private final Accounts accounts; + private final ProfileRepository profiles; + private final ScoreRunRepository runs; + private final StorePurchaseRepository purchases; + private final Flags flags; + private final Moderation moderation; + private final Runs runService; + private final DailySeeds seeds; + private final Boards boards; + private final Broadcasts broadcasts; + private final AttemptRepository attempts; + + /// How many recent runs a death map replays. + static final int HEATMAP_RUNS = 200; + + public AdminEndpoint(Accounts accounts, ProfileRepository profiles, ScoreRunRepository runs, + StorePurchaseRepository purchases, Flags flags, Moderation moderation, Runs runService, + DailySeeds seeds, Boards boards, Broadcasts broadcasts, AttemptRepository attempts) { + this.attempts = attempts; + this.accounts = accounts; + this.profiles = profiles; + this.runs = runs; + this.purchases = purchases; + this.flags = flags; + this.moderation = moderation; + this.runService = runService; + this.seeds = seeds; + this.boards = boards; + this.broadcasts = broadcasts; + } + + @Override + @Transactional(readOnly = true) + public AdminStatsDto stats() throws Exception { + long now = Clock.now(); + Instant today = Instant.ofEpochMilli(Clock.dayOf(now)); + List top = runs.top(new PageRequest(0, 1)); + return new AdminStatsDto((int) profiles.count(), profiles.seenSince(today).intValue(), + runs.since(today).intValue(), (int) flags.open(), + top.isEmpty() ? 0 : top.get(0).getScore(), seeds.seedOf(now), (int) purchases.count()); + } + + @Override + @Transactional(readOnly = true) + public List players(String query) throws Exception { + String q = query == null ? "" : query.trim(); + List out = new ArrayList(); + for (Profile p : profiles.search("%" + q + "%", new PageRequest(0, 50))) { + out.add(accounts.toDto(p)); + } + return out; + } + + @Override + public PlayerDto act(String username, AdminActionDto action) throws Exception { + return moderation.act(Caller.name(), username, action); + } + + @Override + public List flags(boolean open) throws Exception { + return flags.list(open); + } + + @Override + @Transactional(rollbackFor = IOException.class) + public FlagDto resolve(String id, ResolveDto verdict) throws Exception { + String v = verdict == null ? null : verdict.verdict(); + Flag f = flags.resolve(Caller.name(), id, v); + if (Flags.REMOVE.equalsIgnoreCase(v)) { + runService.recomputeBests(f.getUsername()); + } + moderation.record(Caller.name(), f.getUsername(), "FLAG " + v, f.getReason()); + return flags.toDto(f); + } + + @Override + @Transactional(rollbackFor = IOException.class) + public DailyDto setDaily(DailySeedDto seed) throws Exception { + long value = seed == null ? 0 : seed.seed(); + if (value < 0 || value > DailySeeds.SEED_MASK) { + throw new ResponseStatusException(400, "A seed is a whole number from 0 to " + DailySeeds.SEED_MASK); + } + seeds.pick(Caller.name(), value); + moderation.record(Caller.name(), "", "SET_DAILY", Long.toString(value)); + return boards.daily(Caller.name()); + } + + @Override + @Transactional(rollbackFor = IOException.class) + public BroadcastDto broadcast(BroadcastDto broadcast) throws Exception { + // Audited before the push, which is the one step a rollback cannot undo. + moderation.record(Caller.name(), "", "BROADCAST", broadcast == null ? "" : broadcast.title()); + return broadcasts.send(broadcast); + } + + /// Replays a level's latest runs and counts where the hero died. The + /// replay is the server's own, so a doctored client cannot paint it. + /// Finished runs and the runs that died short of the exit both count. + @Override + @Transactional(readOnly = true) + public HeatmapDto heatmap(String level) throws Exception { + int index = LevelPack.indexOf(level); + if (index < 0) { + throw new ResponseStatusException(404, "No such level"); + } + TileGrid grid = LevelPack.load(index).createWorld(1).getGrid(); + int cols = grid.getCols(); + int rows = grid.getRows(); + int[] counts = new int[cols * rows]; + int replayed = 0; + int deaths = 0; + for (ScoreRun r : runs.recent(level, new PageRequest(0, HEATMAP_RUNS))) { + int d = Heatmap.add(index, r.getSeed(), r.getLog(), counts); + if (d >= 0) { + replayed++; + deaths += d; + } + } + for (Attempt a : attempts.recent(level, new PageRequest(0, HEATMAP_RUNS))) { + int d = Heatmap.add(index, a.getSeed(), a.getLog(), counts); + if (d >= 0) { + replayed++; + deaths += d; + } + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < counts.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(counts[i]); + } + return new HeatmapDto(level, cols, rows, sb.toString(), replayed, deaths); + } + + @Override + public List audit() throws Exception { + return moderation.audit(); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/Flags.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/Flags.java new file mode 100644 index 00000000000..b2a758e0b57 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/Flags.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.admin; + +import com.codename1.appkit.server.Text; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.orm.repository.PageRequest; +import com.codenameone.examples.ledge.Ids; +import com.codenameone.examples.ledge.api.FlagDto; +import com.codenameone.examples.ledge.domain.Flag; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.domain.ScoreRun; +import com.codenameone.examples.ledge.repository.FlagRepository; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/// Runs held for a person's look. A flagged run stays on the boards until an +/// admin decides: a remarkable run is usually a good player, and taking it +/// down on arithmetic alone would punish exactly them. +@Component +public class Flags { + public static final String KEEP = "KEEP"; + public static final String REMOVE = "REMOVE"; + + private final FlagRepository flags; + private final ProfileRepository profiles; + private final ScoreRunRepository runs; + + public Flags(FlagRepository flags, ProfileRepository profiles, ScoreRunRepository runs) { + this.flags = flags; + this.profiles = profiles; + this.runs = runs; + } + + /// Files a flag for `run`, inside the caller's transaction. + public Flag file(Profile p, ScoreRun run, String reason) throws IOException { + Flag f = new Flag(); + f.setId(Ids.next()); + f.setUsername(p.getUsername()); + f.setRunId(run.getId()); + f.setLevel(run.getLevel()); + f.setScore(run.getScore()); + f.setTicks(run.getTicks()); + f.setReason(reason); + f.setCreatedAt(run.getCreatedAt()); + f.setPending(true); + flags.insert(f); + return f; + } + + /// Holds a player's latest standing run for review by hand, as a report + /// from other players would. + @Transactional(rollbackFor = IOException.class) + public void report(String username, String reason) throws IOException { + Profile p = profiles.findById(username); + List theirs = runs.of(username); + if (p == null || theirs.isEmpty()) { + throw new ResponseStatusException(404, "Nothing to report"); + } + p.setFlagged(true); + profiles.save(p); + file(p, theirs.get(theirs.size() - 1), reason); + } + + @Transactional(readOnly = true) + public List list(boolean open) { + List out = new ArrayList(); + for (Flag f : flags.inState(open, new PageRequest(0, 200))) { + out.add(toDto(f)); + } + return out; + } + + /// Closes a flag. REMOVE strikes the run; the caller recomputes the + /// player's bests, which needs [com.codenameone.examples.ledge.run.Runs]. + @Transactional(rollbackFor = IOException.class) + public Flag resolve(String admin, String id, String verdict) throws IOException { + String v = Text.oneOf(verdict, new String[] {KEEP, REMOVE}, "", "the verdict"); + Flag f = flags.findById(id); + if (f == null) { + throw new ResponseStatusException(404, "No such flag"); + } + if (!f.isPending()) { + throw new ResponseStatusException(409, "That flag is already closed"); + } + f.setPending(false); + f.setResolvedBy(admin); + flags.save(f); + if (REMOVE.equalsIgnoreCase(v)) { + ScoreRun r = runs.findById(f.getRunId()); + if (r != null && !r.isStruck()) { + r.setStruck(true); + runs.save(r); + } + } + // The player stays marked while anything about them is still open. + Profile p = profiles.findById(f.getUsername()); + if (p != null && flags.countByUsernameAndPendingTrue(p.getUsername()) == 0) { + p.setFlagged(false); + profiles.save(p); + } + return f; + } + + public long open() { + return flags.countByPendingTrue(); + } + + public FlagDto toDto(Flag f) { + Profile p = profiles.findById(f.getUsername()); + return new FlagDto(f.getId(), f.getUsername(), p == null ? f.getUsername() : p.getDisplayName(), + f.getLevel(), f.getScore(), f.getTicks(), f.getReason(), + f.getCreatedAt().toEpochMilli(), f.isPending()); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/Moderation.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/Moderation.java new file mode 100644 index 00000000000..00e85761cdd --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/admin/Moderation.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.admin; + +import com.codename1.appkit.server.Text; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Scheduled; +import com.codename1.backend.annotations.Transactional; +import com.codename1.orm.repository.PageRequest; +import com.codenameone.examples.ledge.Clock; +import com.codenameone.examples.ledge.Ids; +import com.codenameone.examples.ledge.account.Accounts; +import com.codenameone.examples.ledge.api.AdminActionDto; +import com.codenameone.examples.ledge.api.AuditDto; +import com.codenameone.examples.ledge.api.PlayerDto; +import com.codenameone.examples.ledge.domain.AdminAction; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.domain.ScoreRun; +import com.codenameone.examples.ledge.repository.AdminActionRepository; +import com.codenameone.examples.ledge.progress.Progress; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/// What an admin does to a player, every step written to the audit log in +/// the same transaction as the change, so the log cannot miss one. +@Component +public class Moderation { + private final Accounts accounts; + private final ProfileRepository profiles; + private final ScoreRunRepository runs; + private final AdminActionRepository audit; + + public Moderation(Accounts accounts, ProfileRepository profiles, ScoreRunRepository runs, + AdminActionRepository audit) { + this.accounts = accounts; + this.profiles = profiles; + this.runs = runs; + this.audit = audit; + } + + @Transactional(rollbackFor = IOException.class) + public PlayerDto act(String admin, String username, AdminActionDto action) throws IOException { + if (action == null) { + throw new ResponseStatusException(400, "No action"); + } + String kind = Text.oneOf(action.action(), + new String[] {"WARN", "SUSPEND", "BAN", "UNBAN", "RESET_SCORES"}, "", "the action"); + String reason = Text.optional(action.reason(), 255, "the reason"); + Profile p = accounts.profile(username); + if (admin.equals(username) && !"WARN".equals(kind)) { + // An admin who bans themselves loses the console that would undo it. + throw new ResponseStatusException(400, "Not on your own account"); + } + if ("SUSPEND".equals(kind)) { + int days = action.days() <= 0 ? 1 : Math.min(action.days(), 365); + p.setSuspendedUntil(Instant.ofEpochMilli(Clock.now() + days * Clock.DAY)); + accounts.setEnabled(username, false); + kind = "SUSPEND " + days + "d"; + } else if ("BAN".equals(kind)) { + p.setBanned(true); + accounts.setEnabled(username, false); + } else if ("UNBAN".equals(kind)) { + p.setBanned(false); + p.setSuspendedUntil(Instant.EPOCH); + accounts.setEnabled(username, true); + } else if ("RESET_SCORES".equals(kind)) { + for (ScoreRun r : runs.of(username)) { + r.setStruck(true); + runs.save(r); + } + p.setProgress(Progress.EMPTY); + p.setBestDaily(0); + } + profiles.save(p); + record(admin, username, kind, reason == null ? "" : reason); + return accounts.toDto(p); + } + + /// Writes one audit row, inside the caller's transaction. + public void record(String admin, String username, String action, String reason) throws IOException { + AdminAction a = new AdminAction(); + a.setId(Ids.next()); + a.setAdmin(admin); + a.setUsername(username); + a.setAction(action); + a.setReason(reason.length() > 255 ? reason.substring(0, 255) : reason); + a.setCreatedAt(Instant.now()); + audit.insert(a); + } + + @Transactional(readOnly = true) + public List audit() { + List out = new ArrayList(); + for (AdminAction a : audit.newest(new PageRequest(0, 200))) { + out.add(new AuditDto(a.getId(), a.getAdmin(), a.getUsername(), a.getAction(), a.getReason(), + a.getCreatedAt().toEpochMilli())); + } + return out; + } + + /// Lifts suspensions that have run their course. + @Scheduled(fixedDelay = 60000, initialDelay = 60000, lock = "ledge-suspensions") + @Transactional + public void liftExpired() { + for (Profile p : profiles.expired(Instant.EPOCH, Instant.ofEpochMilli(Clock.now()))) { + p.setSuspendedUntil(Instant.EPOCH); + profiles.save(p); + accounts.setEnabled(p.getUsername(), true); + } + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/ai/LevelAi.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/ai/LevelAi.java new file mode 100644 index 00000000000..6c8072c1586 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/ai/LevelAi.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ai; + +import com.codename1.backend.Json; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.Web; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Value; +import com.codename1.gaming.platformer.InputLog; +import com.codenameone.examples.ledge.levels.LevelGenerator; +import com.codenameone.examples.ledge.api.GeneratedDto; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Levels from a description. A language model draws the level as a sketch +/// -- the same text format the shipped levels are written in -- and the +/// [Solver] has to finish it before the player sees it. A model's level that +/// does not parse, or that the solver cannot finish, is replaced by one the +/// [LevelGenerator] builds from the same words, and the note says so. +/// +/// The provider is configured as in the other samples, and the key never +/// reaches the app: +/// +/// ```properties +/// # openai, anthropic, gemini, or url +/// ledge.ai.provider=openai +/// ledge.ai.key=... +/// ledge.ai.model=gpt-4o-mini +/// # for "url": any OpenAI-compatible server +/// ledge.ai.url=http://localhost:11434/v1 +/// ``` +/// +/// With no provider every level comes from the generator, which is what +/// development and the tests use. +@Component +public class LevelAi { + static final int MAX_PROMPT = 300; + static final long SOLVER_BUDGET = 20_000_000L; + static final String SYSTEM = "You design levels for a 2D platformer. Reply with a level " + + "sketch and nothing else. First line: a JSON object {\"name\": short title, " + + "\"theme\": one of meadow, cavern, foundry, sky, forge, \"par\": seconds, " + + "\"tuning\": {\"maxJumps\": 2}, \"abilities\": [\"move\", \"jump\", \"crouch\", " + + "\"dash\", \"walljump\", \"ladder\"]}. Then a line '---'. Then exactly 16 rows of " + + "equal length, 60 to 140 characters. Tiles: '.' air, '#' ground, '=' ledge you " + + "can jump up through, '/' and '\\\\' slopes, 'H' ladder, '^' spikes, '~' water. " + + "Things (each stands on the cell below it): S start (exactly one, left), X goal " + + "(exactly one, right), C checkpoint, o coin, * gem, h heart, k key, D door, s " + + "spring, e slime, w beetle, B brute, T turret, F frog, V bat. The bottom two rows " + + "are mostly ground. A jump rises 3 rows (5 with the double jump) and crosses 4 " + + "columns. Every gap must be crossable."; + + @Value("${ledge.ai.provider:}") + private String provider; + @Value("${ledge.ai.key:}") + private String key; + @Value("${ledge.ai.model:}") + private String model; + @Value("${ledge.ai.url:}") + private String url; + + /// Makes a level the solver can finish. + /// + /// #### Parameters + /// + /// - `prompt`: what the player asked for + /// - `seed`: varies the generator's answer + /// + /// #### Returns + /// + /// the level + /// + /// #### Throws + /// + /// - `ResponseStatusException`: 400 for an over-long description, 503 when + /// nothing finishable could be made + public GeneratedDto generate(String prompt, long seed) { + String words = prompt == null ? "" : prompt.trim(); + if (words.length() > MAX_PROMPT) { + throw new ResponseStatusException(400, "Describe the level in " + MAX_PROMPT + " characters or fewer"); + } + String note = null; + if (base() != null) { + String reply; + try { + reply = ask(words); + } catch (IOException e) { + reply = null; + } + String sketch = sketchOf(reply); + InputLog run = sketch == null ? null : LevelGenerator.check(sketch, SOLVER_BUDGET); + if (run != null) { + return new GeneratedDto(sketch, "ai", null); + } + note = reply == null ? "The level designer is unavailable, so here is one built from your words" + : "The drawn level could not be finished, so here is one built from the same words"; + } + String sketch = LevelGenerator.solvable(words, seed, SOLVER_BUDGET); + if (sketch == null) { + throw new ResponseStatusException(503, "No finishable level came out of that; try other words"); + } + return new GeneratedDto(sketch, "pieces", note); + } + + /// The sketch in a model's reply: from the first `{` on, without a + /// Markdown fence around it; null when there is none. + public static String sketchOf(String reply) { + if (reply == null) { + return null; + } + int start = reply.indexOf('{'); + if (start < 0 || reply.indexOf("\n---\n", start) < 0) { + return null; + } + String s = reply.substring(start); + int fence = s.indexOf("```"); + return fence >= 0 ? s.substring(0, fence) : s; + } + + private String ask(String words) throws IOException { + List> messages = new ArrayList>(); + messages.add(message("system", SYSTEM)); + messages.add(message("user", words.length() == 0 ? "Surprise me." : words)); + Map out = new LinkedHashMap(); + out.put("model", modelName()); + out.put("messages", messages); + out.put("max_tokens", 4000); + List headers = new ArrayList(); + headers.add("Authorization: Bearer " + key); + headers.add("Content-Type: application/json"); + Web.Result answer = Web.request("POST", base() + "/chat/completions", headers, + Json.write(out).getBytes("UTF-8")); + if (answer.getStatus() < 200 || answer.getStatus() >= 300) { + return null; + } + Object choices = Json.parseObject(answer.getBodyAsString()).get("choices"); + if (!(choices instanceof List) || ((List) choices).isEmpty()) { + return null; + } + Object first = ((List) choices).get(0); + Object msg = first instanceof Map ? ((Map) first).get("message") : null; + Object content = msg instanceof Map ? ((Map) msg).get("content") : null; + return content instanceof String ? (String) content : null; + } + + private static Map message(String role, String content) { + Map m = new LinkedHashMap(); + m.put("role", role); + m.put("content", content); + return m; + } + + /// The provider's OpenAI-compatible base, or null when none is set. + String base() { + String p = provider == null ? "" : provider.trim(); + if ("openai".equalsIgnoreCase(p)) { + return "https://api.openai.com/v1"; + } + if ("anthropic".equalsIgnoreCase(p)) { + return "https://api.anthropic.com/v1"; + } + if ("gemini".equalsIgnoreCase(p)) { + return "https://generativelanguage.googleapis.com/v1beta/openai"; + } + if ("url".equalsIgnoreCase(p) && url != null && url.trim().length() > 0) { + return url.trim(); + } + return null; + } + + private String modelName() { + if (model != null && model.trim().length() > 0) { + return model.trim(); + } + String p = provider == null ? "" : provider.trim(); + if ("anthropic".equalsIgnoreCase(p)) { + return "claude-haiku-5-5"; + } + if ("gemini".equalsIgnoreCase(p)) { + return "gemini-2.5-flash"; + } + return "gpt-4o-mini"; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/ai/LevelsEndpoint.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/ai/LevelsEndpoint.java new file mode 100644 index 00000000000..14cda375e12 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/ai/LevelsEndpoint.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ai; + +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.ledge.api.GenerateDto; +import com.codenameone.examples.ledge.api.GeneratedDto; +import com.codenameone.examples.ledge.api.LevelsApiServer; + +/// `LevelsApi` on the server. +@Component +public class LevelsEndpoint implements LevelsApiServer { + private final LevelAi ai; + + public LevelsEndpoint(LevelAi ai) { + this.ai = ai; + } + + @Override + public GeneratedDto generate(GenerateDto request) throws Exception { + return ai.generate(request == null ? null : request.prompt(), request == null ? 0 : request.seed()); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/AdNonce.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/AdNonce.java new file mode 100644 index 00000000000..17c28ad7ea3 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/AdNonce.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A rewarded-ad nonce already paid out. The key is its hash, so one nonce pays once. +@Entity +public class AdNonce { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + public AdNonce() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/AdminAction.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/AdminAction.java new file mode 100644 index 00000000000..b074519c3fe --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/AdminAction.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// One entry of the admin audit log. Rows are only ever inserted. +@Entity +public class AdminAction { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(32)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String admin = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(24)") + private String action = ""; + + @Column(nullable = false, type = "VARCHAR(255)") + private String reason = ""; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + public AdminAction() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getAdmin() { + return admin; + } + + public void setAdmin(String admin) { + this.admin = admin; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Attempt.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Attempt.java new file mode 100644 index 00000000000..76eb2b2ed05 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Attempt.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A run that ended short of the exit but replays: kept for the death map, +/// which would otherwise see only the runs that got through. +@Entity +public class Attempt { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(32)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String level = ""; + + @Column(nullable = false) + private long seed; + + @Column(nullable = false, type = "TEXT") + private String log = ""; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + public Attempt() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public long getSeed() { + return seed; + } + + public void setSeed(long seed) { + this.seed = seed; + } + + public String getLog() { + return log; + } + + public void setLog(String log) { + this.log = log; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Broadcast.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Broadcast.java new file mode 100644 index 00000000000..8135bb47963 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Broadcast.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A push sent from the console. +@Entity +public class Broadcast { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(32)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(80)") + private String title = ""; + + @Column(nullable = false, type = "VARCHAR(255)") + private String body = ""; + + @Column(nullable = false) + private int days; + + @Column(nullable = false) + private int targets; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + public Broadcast() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public int getDays() { + return days; + } + + public void setDays(int days) { + this.days = days; + } + + public int getTargets() { + return targets; + } + + public void setTargets(int targets) { + this.targets = targets; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/DailySeed.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/DailySeed.java new file mode 100644 index 00000000000..8885f4f4d8c --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/DailySeed.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// An admin's pick of seed for one UTC day, keyed by the date (`2026-11-20`). +@Entity +public class DailySeed { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(10)") + private String day = ""; + + @Column(nullable = false) + private long seed; + + @Column(nullable = false, type = "VARCHAR(190)") + private String setBy = ""; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + public DailySeed() { + } + + public String getDay() { + return day; + } + + public void setDay(String day) { + this.day = day; + } + + public long getSeed() { + return seed; + } + + public void setSeed(long seed) { + this.seed = seed; + } + + public String getSetBy() { + return setBy; + } + + public void setSetBy(String setBy) { + this.setBy = setBy; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Flag.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Flag.java new file mode 100644 index 00000000000..57fad45a7f4 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Flag.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A run held for a person's look. +@Entity +public class Flag { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(32)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(32)") + private String runId = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String level = ""; + + @Column(nullable = false) + private long score; + + @Column(nullable = false) + private int ticks; + + @Column(nullable = false, type = "VARCHAR(255)") + private String reason = ""; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + @Column(nullable = false) + private boolean pending; + + @Column(nullable = false, type = "VARCHAR(190)") + private String resolvedBy = ""; + + public Flag() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getRunId() { + return runId; + } + + public void setRunId(String runId) { + this.runId = runId; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public long getScore() { + return score; + } + + public void setScore(long score) { + this.score = score; + } + + public int getTicks() { + return ticks; + } + + public void setTicks(int ticks) { + this.ticks = ticks; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public boolean isPending() { + return pending; + } + + public void setPending(boolean pending) { + this.pending = pending; + } + + public String getResolvedBy() { + return resolvedBy; + } + + public void setResolvedBy(String resolvedBy) { + this.resolvedBy = resolvedBy; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Friend.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Friend.java new file mode 100644 index 00000000000..e95e7a247c5 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Friend.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// One direction of a friendship: `username` sees `friend` on their FRIENDS board. +@Entity +public class Friend { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String friend = ""; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + public Friend() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getFriend() { + return friend; + } + + public void setFriend(String friend) { + this.friend = friend; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Profile.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Profile.java new file mode 100644 index 00000000000..cc5fe01ce32 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/Profile.java @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A player's game data beyond the sign-in record: wallet, level progress, scarves and moderation state. +@Entity +public class Profile { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(40)") + private String displayName = ""; + + @Column(nullable = false) + private int coins; + + /// Stars per level, one digit per `LevelPack` index. + @Column(nullable = false, type = "VARCHAR(64)") + private String progress = ""; + + @Column(nullable = false) + private long bestDaily; + + @Column(nullable = false) + private int runs; + + @Column(nullable = false, type = "VARCHAR(40)") + private String scarf = ""; + + @Column(nullable = false, type = "VARCHAR(1000)") + private String owned = ""; + + @Column(nullable = false) + private boolean flagged; + + @Column(nullable = false) + private Instant suspendedUntil = Instant.EPOCH; + + @Column(nullable = false) + private boolean banned; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + @Column(nullable = false) + private Instant lastSeen = Instant.EPOCH; + + public Profile() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public int getCoins() { + return coins; + } + + public void setCoins(int coins) { + this.coins = coins; + } + + public long getBestDaily() { + return bestDaily; + } + + public void setBestDaily(long bestDaily) { + this.bestDaily = bestDaily; + } + + public int getRuns() { + return runs; + } + + public void setRuns(int runs) { + this.runs = runs; + } + + public String getScarf() { + return scarf; + } + + public void setScarf(String scarf) { + this.scarf = scarf; + } + + public String getProgress() { + return progress; + } + + public void setProgress(String progress) { + this.progress = progress; + } + + public String getOwned() { + return owned; + } + + public void setOwned(String owned) { + this.owned = owned; + } + + public boolean isFlagged() { + return flagged; + } + + public void setFlagged(boolean flagged) { + this.flagged = flagged; + } + + public Instant getSuspendedUntil() { + return suspendedUntil; + } + + public void setSuspendedUntil(Instant suspendedUntil) { + this.suspendedUntil = suspendedUntil; + } + + public boolean isBanned() { + return banned; + } + + public void setBanned(boolean banned) { + this.banned = banned; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getLastSeen() { + return lastSeen; + } + + public void setLastSeen(Instant lastSeen) { + this.lastSeen = lastSeen; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/PushDevice.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/PushDevice.java new file mode 100644 index 00000000000..72698178563 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/PushDevice.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A device an account is sent push notifications on. +/// +/// Keyed by the hash of its provider and token, so a token is on one account at +/// a time: the phone belongs to whoever signed in on it last. +@Entity +public class PushDevice { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + /// `fcm`, `apns`, `huawei`, `wns` or `web`. + @Column(nullable = false, type = "VARCHAR(16)") + private String provider = ""; + + @Column(nullable = false, type = "VARCHAR(1024)") + private String token = ""; + + @Column(nullable = false, type = "VARCHAR(32)") + private String platform = ""; + + @Column(nullable = false) + private Instant updatedAt = Instant.EPOCH; + + public PushDevice() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getPlatform() { + return platform; + } + + public void setPlatform(String platform) { + this.platform = platform; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/RunTicket.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/RunTicket.java new file mode 100644 index 00000000000..89fd1cc2451 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/RunTicket.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// Permission to submit one run. The token is the key; using it marks the row. +@Entity +public class RunTicket { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String token = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String level = ""; + + @Column(nullable = false) + private boolean daily; + + @Column(nullable = false) + private long seed; + + @Column(nullable = false) + private Instant expiresAt = Instant.EPOCH; + + @Column(nullable = false) + private boolean used; + + public RunTicket() { + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public long getSeed() { + return seed; + } + + public void setSeed(long seed) { + this.seed = seed; + } + + public Instant getExpiresAt() { + return expiresAt; + } + + public void setExpiresAt(Instant expiresAt) { + this.expiresAt = expiresAt; + } + + public boolean isUsed() { + return used; + } + + public void setUsed(boolean used) { + this.used = used; + } + + public boolean isDaily() { + return daily; + } + + public void setDaily(boolean daily) { + this.daily = daily; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/ScoreRun.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/ScoreRun.java new file mode 100644 index 00000000000..f8df1837deb --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/ScoreRun.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// One accepted run. Struck runs stay for the record but leave every board. +@Entity +public class ScoreRun { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(32)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String level = ""; + + @Column(nullable = false) + private boolean daily; + + @Column(nullable = false) + private long score; + + @Column(nullable = false) + private int ticks; + + @Column(nullable = false) + private int stars; + + @Column(nullable = false) + private long seed; + + @Column(nullable = false, type = "TEXT") + private String log = ""; + + @Column(nullable = false) + private long day; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + @Column(nullable = false) + private boolean struck; + + public ScoreRun() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public long getScore() { + return score; + } + + public void setScore(long score) { + this.score = score; + } + + public long getDay() { + return day; + } + + public void setDay(long day) { + this.day = day; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public boolean isStruck() { + return struck; + } + + public void setStruck(boolean struck) { + this.struck = struck; + } + + public String getLog() { + return log; + } + + public void setLog(String log) { + this.log = log; + } + + public long getSeed() { + return seed; + } + + public void setSeed(long seed) { + this.seed = seed; + } + + public int getStars() { + return stars; + } + + public void setStars(int stars) { + this.stars = stars; + } + + public int getTicks() { + return ticks; + } + + public void setTicks(int ticks) { + this.ticks = ticks; + } + + public boolean isDaily() { + return daily; + } + + public void setDaily(boolean daily) { + this.daily = daily; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/StorePurchase.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/StorePurchase.java new file mode 100644 index 00000000000..1ad6c673a10 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/domain/StorePurchase.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.domain; + +import com.codename1.annotations.Column; +import com.codename1.annotations.Entity; +import com.codename1.annotations.Id; +import java.time.Instant; + +/// A verified store transaction. The key is the store's transaction id, so a receipt can only ever be redeemed once. +@Entity +public class StorePurchase { + @Id(autoIncrement = false) + @Column(nullable = false, type = "VARCHAR(64)") + private String id = ""; + + @Column(nullable = false, type = "VARCHAR(190)") + private String username = ""; + + @Column(nullable = false, type = "VARCHAR(16)") + private String store = ""; + + @Column(nullable = false, type = "VARCHAR(64)") + private String sku = ""; + + @Column(nullable = false) + private int coins; + + @Column(nullable = false) + private Instant createdAt = Instant.EPOCH; + + public StorePurchase() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getStore() { + return store; + } + + public void setStore(String store) { + this.store = store; + } + + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + + public int getCoins() { + return coins; + } + + public void setCoins(int coins) { + this.coins = coins; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/friends/Friends.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/friends/Friends.java new file mode 100644 index 00000000000..7e43d110830 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/friends/Friends.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.friends; + +import com.codename1.appkit.server.Caller; +import com.codename1.appkit.server.Text; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.ledge.Ids; +import com.codenameone.examples.ledge.api.FriendAddDto; +import com.codenameone.examples.ledge.api.FriendDto; +import com.codenameone.examples.ledge.api.FriendsApiServer; +import com.codenameone.examples.ledge.domain.Friend; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.repository.FriendRepository; +import com.codenameone.examples.ledge.progress.Progress; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codename1.orm.repository.PageRequest; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/// Friends, and `FriendsApi` on the server. A friendship goes one way: adding +/// somebody puts them on your FRIENDS board, not you on theirs, so nobody has +/// to accept anything and nobody can push themselves onto a stranger's board. +@Component +public class Friends implements FriendsApiServer { + private final FriendRepository friends; + private final ProfileRepository profiles; + + public Friends(FriendRepository friends, ProfileRepository profiles) { + this.friends = friends; + this.profiles = profiles; + } + + @Override + public List friends() throws Exception { + return list(Caller.name()); + } + + @Override + public List add(FriendAddDto friend) throws Exception { + return add(Caller.name(), friend == null ? null : friend.name()); + } + + @Override + public List remove(FriendAddDto friend) throws Exception { + return remove(Caller.name(), friend == null ? null : friend.name()); + } + + @Transactional(readOnly = true) + public List list(String username) { + List out = new ArrayList(); + for (Friend f : friends.findByUsername(username)) { + Profile p = profiles.findById(f.getFriend()); + if (p != null) { + out.add(new FriendDto(p.getUsername(), p.getDisplayName(), Progress.stars(p.getProgress()), p.getScarf())); + } + } + return out; + } + + @Transactional(rollbackFor = IOException.class) + public List add(String username, String name) throws IOException { + Profile other = find(name); + if (other.getUsername().equals(username)) { + throw new ResponseStatusException(400, "You are always on your own board"); + } + String key = key(username, other.getUsername()); + if (friends.findById(key) == null) { + Friend f = new Friend(); + f.setId(key); + f.setUsername(username); + f.setFriend(other.getUsername()); + f.setCreatedAt(Instant.now()); + friends.insert(f); + } + return list(username); + } + + @Transactional(rollbackFor = IOException.class) + public List remove(String username, String name) throws IOException { + Friend f = friends.findById(key(username, find(name).getUsername())); + if (f != null) { + friends.delete(f); + } + return list(username); + } + + /// A player by username, else by display name. Display names are not + /// unique, so one shared by several players is refused rather than guessed. + private Profile find(String name) { + String text = Text.required(name, 190, "a player name").trim(); + Profile p = profiles.findById(text); + if (p != null) { + return p; + } + List named = profiles.named(text, new PageRequest(0, 2)); + if (named.isEmpty()) { + throw new ResponseStatusException(404, "Nobody plays by that name"); + } + if (named.size() > 1) { + throw new ResponseStatusException(409, "Several players use that name; use their e-mail"); + } + return named.get(0); + } + + /// The row's key: one row per ordered pair, so adding twice is harmless. + private static String key(String username, String friend) throws IOException { + return Ids.sha256(username + "\n" + friend); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/progress/Achievements.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/progress/Achievements.java new file mode 100644 index 00000000000..7c0fbc5d87a --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/progress/Achievements.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.progress; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.ledge.api.AchievementDto; +import com.codenameone.examples.ledge.api.ProgressApiServer; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.domain.ScoreRun; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import com.codenameone.examples.ledge.levels.LevelPack; +import java.util.ArrayList; +import java.util.List; + +/// Achievements, and `ProgressApi` on the server. Nothing is stored: each is +/// worked out from the player's standing runs whenever asked, so an admin +/// striking a run takes back what it unlocked, and a new achievement counts +/// every run played before it existed. +@Component +public class Achievements implements ProgressApiServer { + private final ScoreRunRepository runs; + private final ProfileRepository profiles; + + public Achievements(ScoreRunRepository runs, ProfileRepository profiles) { + this.runs = runs; + this.profiles = profiles; + } + + @Override + public List achievements() throws Exception { + return of(Caller.name()); + } + + @Transactional(readOnly = true) + public List of(String username) { + long coins = 0; + long dailies = 0; + for (ScoreRun r : runs.of(username)) { + if (r.isDaily()) { + dailies++; + } + } + Profile p = profiles.findById(username); + String progress = p == null ? Progress.EMPTY : p.getProgress(); + if (p != null) { + coins = p.getCoins(); + } + List out = new ArrayList(); + out.add(goal("first-clear", "First Light", "Reach the exit of any level", Progress.cleared(progress), 1)); + out.add(goal("clear-10", "Climber", "Clear 10 levels", Progress.cleared(progress), 10)); + out.add(goal("world-1-3star", "Meadow Master", "Earn three stars on every level of world 1", + worldStars(progress, "1-"), worldGoal("1-"))); + out.add(goal("stars-all", "Star Collector", "Earn every star", Progress.stars(progress), + 3L * LevelPack.IDS.length)); + out.add(goal("coins-100", "Pocket Money", "Hold 100 coins", coins, 100)); + out.add(goal("daily-1", "Daily Climber", "Play a daily challenge", dailies, 1)); + return out; + } + + /// Stars earned in the world whose level ids start with `prefix`. + private static long worldStars(String progress, String prefix) { + long total = 0; + for (int i = 0; i < LevelPack.IDS.length; i++) { + if (LevelPack.IDS[i].startsWith(prefix)) { + total += Progress.at(progress, i); + } + } + return total; + } + + private static long worldGoal(String prefix) { + long total = 0; + for (String id : LevelPack.IDS) { + if (id.startsWith(prefix)) { + total += 3; + } + } + return total; + } + + private static AchievementDto goal(String id, String name, String description, long progress, long goal) { + return new AchievementDto(id, name, description, progress >= goal, Math.min(progress, goal), goal); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/progress/Progress.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/progress/Progress.java new file mode 100644 index 00000000000..ff024fac306 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/progress/Progress.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.progress; + +import com.codenameone.examples.ledge.levels.LevelPack; + +/// A player's stars per level, kept as one digit per `LevelPack` index. +public final class Progress { + /// No stars anywhere. + public static final String EMPTY = of(""); + + private Progress() { + } + + /// `progress` padded (or cut) to one digit per level. + public static String of(String progress) { + StringBuilder b = new StringBuilder(); + int n = LevelPack.IDS.length; + for (int i = 0; i < n; i++) { + b.append(digit(progress, i)); + } + return b.toString(); + } + + /// The stars recorded for level `index`. + public static int at(String progress, int index) { + return digit(progress, index) - '0'; + } + + /// `progress` with level `index` raised to `stars`, never lowered. + public static String raise(String progress, int index, int stars) { + String p = of(progress); + if (index < 0 || index >= p.length() || stars <= at(p, index)) { + return p; + } + return p.substring(0, index) + (char) ('0' + Math.min(3, stars)) + p.substring(index + 1); + } + + /// Every star earned, across all levels. + public static int stars(String progress) { + int total = 0; + for (int i = 0; i < LevelPack.IDS.length; i++) { + total += at(progress, i); + } + return total; + } + + /// How many levels have been finished at least once. + public static int cleared(String progress) { + int total = 0; + for (int i = 0; i < LevelPack.IDS.length; i++) { + if (at(progress, i) > 0) { + total++; + } + } + return total; + } + + private static char digit(String progress, int i) { + if (progress == null || i < 0 || i >= progress.length()) { + return '0'; + } + char c = progress.charAt(i); + return c >= '0' && c <= '3' ? c : '0'; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/push/Broadcasts.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/push/Broadcasts.java new file mode 100644 index 00000000000..0e126fa251d --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/push/Broadcasts.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.push; + +import com.codename1.appkit.server.Text; +import com.codename1.appkit.server.push.PushSender; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.push.PushNotification; +import com.codename1.backend.push.PushTarget; +import com.codename1.orm.repository.PageRequest; +import com.codenameone.examples.ledge.Clock; +import com.codenameone.examples.ledge.Ids; +import com.codenameone.examples.ledge.api.BroadcastDto; +import com.codenameone.examples.ledge.domain.Broadcast; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.repository.BroadcastRepository; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +/// A push from the console to every player, or to the ones not seen for some +/// days. Sent through the configured [PushSender]: the console prints it on a +/// development server, the recorder keeps it for the tests. +@Component +public class Broadcasts { + private static final int PAGE = 500; + + private final ProfileRepository profiles; + private final PushDevices devices; + private final PushSender sender; + private final BroadcastRepository broadcasts; + + public Broadcasts(ProfileRepository profiles, PushDevices devices, PushSender sender, + BroadcastRepository broadcasts) { + this.profiles = profiles; + this.devices = devices; + this.sender = sender; + this.broadcasts = broadcasts; + } + + /// Sends it and records it. `targets` in the answer counts players with at + /// least one device, not devices: that is the number an admin means. + public BroadcastDto send(BroadcastDto request) throws IOException { + if (request == null) { + throw new ResponseStatusException(400, "Nothing to send"); + } + String title = Text.required(request.title(), 80, "the title"); + String body = Text.required(request.body(), 255, "the message"); + int days = Math.max(0, request.days()); + Instant seenBefore = days == 0 ? Instant.ofEpochMilli(Long.MAX_VALUE) + : Instant.ofEpochMilli(Clock.now() - days * Clock.DAY); + String id = Ids.next(); + List targets = new ArrayList(); + int reached = 0; + for (int page = 0;; page++) { + List batch = profiles.audience(seenBefore, new PageRequest(page, PAGE)); + for (Profile p : batch) { + List mine = devices.targetsOf(p.getUsername()); + if (!mine.isEmpty()) { + reached++; + targets.addAll(mine); + } + } + if (batch.size() < PAGE) { + break; + } + } + Broadcast row = new Broadcast(); + row.setId(id); + row.setTitle(title); + row.setBody(body); + row.setDays(days); + row.setTargets(reached); + row.setCreatedAt(Instant.now()); + broadcasts.insert(row); + // The push goes last: it cannot be rolled back, so everything that + // can fail is written first. The caller audits before calling this. + if (!targets.isEmpty()) { + sender.send(targets, PushNotification.builder().id(id).title(title).body(body) + .collapseKey("broadcast").ttlSeconds(24 * 60 * 60).data("broadcast", id) + // The app opens today's sheet from it (Notifications). + .data("screen", "daily").build(), null); + } + return new BroadcastDto(id, title, body, days, reached, row.getCreatedAt().toEpochMilli()); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/push/PushDevices.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/push/PushDevices.java new file mode 100644 index 00000000000..34e4cabca31 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/push/PushDevices.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.push; + +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codename1.backend.push.PushTarget; +import com.codenameone.examples.ledge.Ids; +import com.codename1.appkit.server.Text; +import com.codenameone.examples.ledge.api.PushDeviceDto; +import com.codenameone.examples.ledge.domain.PushDevice; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.PushDeviceRepository; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +// tag::ledge-push-devices[] +/// The devices each account is sent notifications on. +/// +/// The app registers its token when somebody signs in and removes it when they +/// sign out. A token registered by a second account moves to it: the phone +/// belongs to whoever signed in on it last, and the one before is not to be +/// told about the new owner's deliveries. +@Component +public class PushDevices { + /// How many devices one account keeps. A new one past this replaces the + /// one heard from longest ago: a token the platform has replaced is never + /// removed by its app, and would otherwise be sent to for good. + static final int MAX_PER_ACCOUNT = 8; + + private final PushDeviceRepository devices; + private final ProfileRepository profiles; + + public PushDevices(PushDeviceRepository devices, ProfileRepository profiles) { + this.devices = devices; + this.profiles = profiles; + } + + @Transactional + public PushDeviceDto register(String username, PushDeviceDto device) throws IOException { + PushTarget target = target(device); + String id = key(target); + long now = System.currentTimeMillis(); + // Before anything is read, the account's profile row is held: a no-op + // update that answers 0 when the profile is gone and otherwise keeps + // the row locked until this commits. It settles two races. + // + // Against closing the account: Accounts.erase holds the same row + // first and deletes it before it commits, so a registration either + // runs first (and erase's cleanup then deletes the device with the + // rest) or waits, finds no profile and is refused. Without it, a + // registration authorized just before the closure could insert its + // device after erase removed the account's, leaving a device of an + // account that no longer exists and that nobody can unregister. + // + // Against itself: two devices registering at once for an account one + // short of the cap would both count the same rows in makeRoom(), both + // skip the eviction and both insert, one past the cap. Behind the hold + // the second counts after the first committed, and evicts. + if (profiles.hold(username) == 0) { + throw new ResponseStatusException(404, "No such account"); + } + // The device row itself is not locked. Two accounts registering one + // token at the same moment -- a registration of the account that + // signed out still in flight as the next one signs in -- can leave it + // with the earlier account. The app settles it: a registration that + // answers after its account signed out is sent again for the account + // signed in now, and that one, sent after the stale one committed, + // lands last (Notifications.signedIn). + PushDevice row = devices.findById(id); + if (row == null || !username.equals(row.getUsername())) { + // A device new to this account, whether its token is new or moves + // here from another account, takes a place under the cap. + makeRoom(username); + } + if (row == null) { + row = new PushDevice(); + row.setId(id); + row.setProvider(target.getProvider()); + row.setToken(target.getToken()); + fill(row, username, device, now); + devices.insert(row); + } else { + fill(row, username, device, now); + } + return new PushDeviceDto(target.getProvider(), target.getToken(), row.getPlatform()); + } + + /// Removes `username`'s devices heard from longest ago until one more fits + /// under [#MAX_PER_ACCOUNT]. + private void makeRoom(String username) { + List held = new ArrayList(devices.findByUsername(username)); + while (held.size() >= MAX_PER_ACCOUNT) { + PushDevice oldest = held.get(0); + for (PushDevice each : held) { + if (each.getUpdatedAt().isBefore(oldest.getUpdatedAt())) { + oldest = each; + } + } + devices.deleteById(oldest.getId()); + held.remove(oldest); + } + } + + /// Forgets a device, if it is this account's. Somebody else's is left alone. + @Transactional + public PushDeviceDto unregister(String username, PushDeviceDto device) throws IOException { + PushTarget target = target(device); + devices.deleteByIdAndUsername(key(target), username); + return new PushDeviceDto(target.getProvider(), target.getToken(), ""); + } + + /// Where to reach `username`: every device they registered. + @Transactional(readOnly = true) + public List targets(String username) { + return targetsOf(username); + } + + /// [#targets] for a caller already inside a transaction. + public List targetsOf(String username) { + List out = new ArrayList(); + if (username == null || username.length() == 0) { + return out; + } + for (PushDevice each : devices.findByUsername(username)) { + out.add(PushTarget.of(each.getProvider(), each.getToken())); + } + return out; + } + // end::ledge-push-devices[] + + private static void fill(PushDevice row, String username, PushDeviceDto device, long now) { + row.setUsername(username); + row.setPlatform(Text.optional(device.platform(), 32, "the platform")); + row.setUpdatedAt(Instant.ofEpochMilli(now)); + } + + /// The device as a target of the push service, which also spells its + /// provider the one way: `gcm` and `fcm` are one device. + private static PushTarget target(PushDeviceDto device) { + if (device == null) { + throw new ResponseStatusException(400, "Tell us the device"); + } + String token = Text.required(device.token(), 1024, "the device's token"); + try { + return PushTarget.of(Text.required(device.provider(), 16, "the push provider"), token); + } catch (IllegalArgumentException err) { + throw new ResponseStatusException(400, err.getMessage()); + } + } + + private static String key(PushTarget target) throws IOException { + return Ids.sha256(target.getProvider() + ":" + target.getToken()); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AdNonceRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AdNonceRepository.java new file mode 100644 index 00000000000..f13c4ed1aa0 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AdNonceRepository.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.AdNonce; + +/// Rewarded-ad nonces already paid. +@Repository(entity = AdNonce.class, key = String.class) +public interface AdNonceRepository extends CrudRepository { + /// How many ads `username` was paid for since `since`: the daily cap. + long countByUsernameAndCreatedAtAfter(String username, Instant since); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AdminActionRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AdminActionRepository.java new file mode 100644 index 00000000000..1f07d959bd2 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AdminActionRepository.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.ledge.domain.AdminAction; +import java.util.List; + +@Repository(entity = AdminAction.class, key = String.class) +public interface AdminActionRepository extends CrudRepository { + @Query("select a from AdminAction a order by a.createdAt desc, a.id asc") + List newest(PageRequest page); + + @Query("select a from AdminAction a where a.username = :u order by a.createdAt desc, a.id asc") + List of(@Param("u") String username, PageRequest page); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AttemptRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AttemptRepository.java new file mode 100644 index 00000000000..17ebacb0bb3 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/AttemptRepository.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.ledge.domain.Attempt; +import java.time.Instant; +import java.util.List; + +/// Runs that died short of the exit. +@Repository(entity = Attempt.class, key = String.class) +public interface AttemptRepository extends CrudRepository { + /// A level's latest attempts, newest first. + @Query("select a from Attempt a where a.level = :level order by a.createdAt desc, a.id desc") + List recent(@Param("level") String level, PageRequest page); + + /// How many attempts a player left on a level since `since`. + @Query("select count(a) from Attempt a where a.username = :u and a.level = :level and a.createdAt >= :since") + Long countSince(@Param("u") String username, @Param("level") String level, @Param("since") Instant since); + + /// Drops attempts older than `before`. + @Modifying + @Query("delete from Attempt a where a.createdAt < :before") + int prune(@Param("before") Instant before); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/BroadcastRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/BroadcastRepository.java new file mode 100644 index 00000000000..e2d53f19520 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/BroadcastRepository.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.Broadcast; + +/// Pushes sent from the console. +@Repository(entity = Broadcast.class, key = String.class) +public interface BroadcastRepository extends CrudRepository { + @Query("select b from Broadcast b order by b.createdAt desc, b.id asc") + List newest(PageRequest page); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/DailySeedRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/DailySeedRepository.java new file mode 100644 index 00000000000..1a8654c08d5 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/DailySeedRepository.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.DailySeed; + +/// Days an admin picked the seed for. +@Repository(entity = DailySeed.class, key = String.class) +public interface DailySeedRepository extends CrudRepository { +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/FlagRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/FlagRepository.java new file mode 100644 index 00000000000..d677a3c06dd --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/FlagRepository.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.Flag; + +/// Runs held for review. +@Repository(entity = Flag.class, key = String.class) +public interface FlagRepository extends CrudRepository { + @Query("select f from Flag f where f.pending = :pending order by f.createdAt desc, f.id asc") + List inState(@Param("pending") boolean pending, PageRequest page); + + long countByPendingTrue(); + + long countByUsernameAndPendingTrue(String username); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/FriendRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/FriendRepository.java new file mode 100644 index 00000000000..777ec2751b4 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/FriendRepository.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.Friend; + +/// Who sees whom on the FRIENDS board. +@Repository(entity = Friend.class, key = String.class) +public interface FriendRepository extends CrudRepository { + List findByUsername(String username); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/ProfileRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/ProfileRepository.java new file mode 100644 index 00000000000..9c516850b07 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/ProfileRepository.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.Profile; + +/// The players' game data. +@Repository(entity = Profile.class, key = String.class) +public interface ProfileRepository extends CrudRepository { + /// Locks the row for the rest of the transaction; answers 0 when there is none. + @Modifying + @Query("update Profile p set p.createdAt = p.createdAt where p.username = :username") + int hold(@Param("username") String username); + + @Query("select p from Profile p where p.username like :q or p.displayName like :q " + + "order by p.lastSeen desc, p.username asc") + List search(@Param("q") String like, PageRequest page); + + @Query("select p from Profile p where p.displayName = :name order by p.username asc") + List named(@Param("name") String displayName, PageRequest page); + + @Query("select count(p) from Profile p where p.lastSeen >= :since") + Long seenSince(@Param("since") Instant since); + + /// The players a broadcast reaches, a page at a time; banned players are + /// never sent anything. + @Query("select p from Profile p where p.banned = false and p.lastSeen < :seen order by p.username asc") + List audience(@Param("seen") Instant seenBefore, PageRequest page); + + /// Suspensions whose time is up, for the sweep that lifts them. + @Query("select p from Profile p where p.banned = false and p.suspendedUntil > :epoch " + + "and p.suspendedUntil <= :now") + List expired(@Param("epoch") Instant epoch, @Param("now") Instant now); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/PushDeviceRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/PushDeviceRepository.java new file mode 100644 index 00000000000..8561f475ddb --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/PushDeviceRepository.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.ledge.domain.PushDevice; + +import java.util.List; + +/// The devices each account is sent notifications on. +@Repository(entity = PushDevice.class, key = String.class) +public interface PushDeviceRepository extends CrudRepository { + List findByUsername(String username); + + int deleteByUsername(String username); + + int deleteByIdAndUsername(String id, String username); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/RunTicketRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/RunTicketRepository.java new file mode 100644 index 00000000000..01ce7bca118 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/RunTicketRepository.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.RunTicket; + +/// Outstanding run tickets. +@Repository(entity = RunTicket.class, key = String.class) +public interface RunTicketRepository extends CrudRepository { + /// Marks a ticket used, once: answers 1 for the request that wins and 0 for + /// a second submit racing it. + @Modifying + @Query("update RunTicket t set t.used = true where t.token = :token and t.used = false") + int use(@Param("token") String token); + + int deleteByExpiresAtLessThan(Instant before); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/ScoreRunRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/ScoreRunRepository.java new file mode 100644 index 00000000000..ecaa10a303b --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/ScoreRunRepository.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Modifying; +import com.codename1.orm.repository.PageRequest; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import java.time.Instant; +import java.util.List; +import com.codenameone.examples.ledge.domain.ScoreRun; + +/// Accepted runs. +@Repository(entity = ScoreRun.class, key = String.class) +public interface ScoreRunRepository extends CrudRepository { + /// Every standing run of a level since `since`, best first: the daily's + /// runs or the ordinary ones. A board keeps the first row it meets per + /// player. + @Query("select r from ScoreRun r where r.level = :level and r.daily = :daily and r.struck = false " + + "and r.createdAt >= :since order by r.score desc, r.ticks asc, r.createdAt asc, r.id asc") + List board(@Param("level") String level, @Param("daily") boolean daily, + @Param("since") Instant since); + + /// One player's standing runs of a level, best first. + @Query("select r from ScoreRun r where r.username = :u and r.level = :level and r.daily = false " + + "and r.struck = false order by r.score desc, r.ticks asc, r.createdAt asc, r.id asc") + List bestOf(@Param("u") String username, @Param("level") String level, PageRequest page); + + @Query("select r from ScoreRun r where r.username = :u and r.struck = false order by r.createdAt asc, r.id asc") + List of(@Param("u") String username); + + /// The highest standing scores of any level, for the console. + @Query("select r from ScoreRun r where r.struck = false order by r.score desc, r.id asc") + List top(PageRequest page); + + /// A level's most recent standing runs, for the death map. + @Query("select r from ScoreRun r where r.level = :level and r.struck = false " + + "order by r.createdAt desc, r.id desc") + List recent(@Param("level") String level, PageRequest page); + + /// How many daily runs a player has stored on `day`. + @Query("select count(r) from ScoreRun r where r.username = :u and r.daily = true and r.day = :day") + Long dailiesOn(@Param("u") String username, @Param("day") long day); + + @Query("select count(r) from ScoreRun r where r.createdAt >= :since") + Long since(@Param("since") Instant since); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/StorePurchaseRepository.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/StorePurchaseRepository.java new file mode 100644 index 00000000000..51267c3cf14 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/repository/StorePurchaseRepository.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.repository; + +import com.codename1.orm.repository.CrudRepository; +import com.codename1.orm.repository.Param; +import com.codename1.orm.repository.Query; +import com.codename1.orm.repository.Repository; +import com.codenameone.examples.ledge.domain.StorePurchase; +import java.time.Instant; +import java.util.List; + +@Repository(entity = StorePurchase.class, key = String.class) +public interface StorePurchaseRepository extends CrudRepository { + @Query("select s from StorePurchase s where s.username = :u order by s.createdAt desc, s.id asc") + List of(@Param("u") String username); + + @Query("select s from StorePurchase s where s.createdAt >= :since") + List since(@Param("since") Instant since); +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Boards.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Boards.java new file mode 100644 index 00000000000..d9083db9e13 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Boards.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.run; + +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.ledge.Clock; +import com.codenameone.examples.ledge.account.Accounts; +import com.codenameone.examples.ledge.api.DailyDto; +import com.codenameone.examples.ledge.api.GhostDto; +import com.codenameone.examples.ledge.api.LeaderDto; +import com.codenameone.examples.ledge.domain.Friend; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.domain.ScoreRun; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.repository.FriendRepository; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import java.io.IOException; +import com.codename1.orm.repository.PageRequest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/// The leaderboards: each player's best standing run of a level over a period. +/// +/// A board is worked out from the runs on every request rather than kept as a +/// table of bests, because WEEK and TODAY are windows a stored best cannot +/// answer, and a struck run or a benched player has to vanish from all of +/// them at once. The query walks the period's runs best first and keeps each +/// player's first, which is cheap at a sample's scale; a game with millions of +/// runs would keep a per-period best table instead. +@Component +public class Boards { + /// How many rows a board shows. + public static final int TOP = 50; + + private final ScoreRunRepository runs; + private final ProfileRepository profiles; + private final FriendRepository friends; + private final DailySeeds seeds; + + public Boards(ScoreRunRepository runs, ProfileRepository profiles, FriendRepository friends, + DailySeeds seeds) { + this.runs = runs; + this.profiles = profiles; + this.friends = friends; + this.seeds = seeds; + } + + @Transactional(readOnly = true) + public List leaderboard(String asker, String level, String period) { + String id = LevelPack.IDS[Modes.level(level)]; + List all = board(asker, id, false, Modes.period(period)); + return all.size() > TOP ? new ArrayList(all.subList(0, TOP)) : all; + } + + /// Where `username` stands on the all-time board of `level`; 0 when not on it. + @Transactional(readOnly = true) + public int rank(String username, String level) { + for (LeaderDto row : board(username, level, false, Modes.ALL)) { + if (row.me()) { + return row.rank(); + } + } + return 0; + } + + /// Today's challenge: its level, its seed and how today's daily runs stand. + @Transactional(readOnly = true) + public DailyDto daily(String asker) throws IOException { + long now = Clock.now(); + String level = LevelPack.IDS[Scoring.dailyLevel(Clock.dayOf(now) / Clock.DAY)]; + List today = board(asker, level, true, Modes.TODAY); + long mine = 0; + for (LeaderDto row : today) { + if (row.me()) { + mine = row.score(); + } + } + LeaderDto top = today.isEmpty() ? null : today.get(0); + return new DailyDto(Clock.date(now), level, seeds.seedOf(now), mine, top == null ? 0 : top.score(), + top == null ? null : top.displayName(), today.size()); + } + + /// The run to race on `level`: the best standing one, or the best of + /// `username`. A run on the public board is public, so anyone's best can + /// be raced -- except a benched player's, which the boards hide. + @Transactional(readOnly = true) + public GhostDto ghost(String asker, String level, String username) { + String id = LevelPack.IDS[Modes.level(level)]; + ScoreRun best = null; + if (username == null || username.length() == 0) { + for (ScoreRun r : runs.board(id, false, Instant.EPOCH)) { + Profile p = profiles.findById(r.getUsername()); + if (p != null && !Accounts.isBenched(p)) { + best = r; + break; + } + } + } else { + Profile owner = profiles.findById(username); + if (!username.equals(asker) && (owner == null || Accounts.isBenched(owner))) { + throw new ResponseStatusException(404, "No run to race yet"); + } + List mine = runs.bestOf(username, id, new PageRequest(0, 1)); + best = mine.isEmpty() ? null : mine.get(0); + } + if (best == null) { + throw new ResponseStatusException(404, "No run to race yet"); + } + Profile p = profiles.findById(best.getUsername()); + return new GhostDto(id, best.getUsername(), p == null ? best.getUsername() : p.getDisplayName(), + best.getSeed(), best.getLog(), best.getTicks(), best.getScore()); + } + + + /// The whole board, ranked, without the cut to [#TOP]. + List board(String asker, String level, boolean daily, String period) { + long now = Clock.now(); + long since = Modes.WEEK.equals(period) ? Clock.weekOf(now) + : Modes.TODAY.equals(period) ? Clock.dayOf(now) : 0; + Set circle = null; + if (Modes.FRIENDS.equals(period)) { + circle = new HashSet(); + circle.add(asker); + for (Friend f : friends.findByUsername(asker)) { + circle.add(f.getFriend()); + } + } + Map seen = new HashMap(); + List out = new ArrayList(); + for (ScoreRun r : runs.board(level, daily, Instant.ofEpochMilli(since))) { + String who = r.getUsername(); + if (seen.containsKey(who) || (circle != null && !circle.contains(who))) { + continue; + } + Profile p = profiles.findById(who); + seen.put(who, p); + if (p == null || Accounts.isBenched(p)) { + continue; + } + out.add(new LeaderDto(out.size() + 1, who, p.getDisplayName(), r.getScore(), r.getTicks(), p.getScarf(), + who.equals(asker))); + } + return out; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/DailySeeds.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/DailySeeds.java new file mode 100644 index 00000000000..7e06021d46c --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/DailySeeds.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.run; + +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.ledge.Clock; +import com.codenameone.examples.ledge.Ids; +import com.codenameone.examples.ledge.domain.DailySeed; +import com.codenameone.examples.ledge.repository.DailySeedRepository; +import java.io.IOException; +import java.time.Instant; + +/// The seed of the daily sheet: the same for every player on a UTC day, so +/// the day's board compares like with like. +/// +/// It is a hash of the date unless an admin has picked one for that day. +/// Worked out rather than stored, so a day nobody played still has a seed and +/// two servers agree on it without talking. +@Component +public class DailySeeds { + private final DailySeedRepository overrides; + + public DailySeeds(DailySeedRepository overrides) { + this.overrides = overrides; + } + + @Transactional(readOnly = true) + public long seedOf(long millis) throws IOException { + String date = Clock.date(millis); + DailySeed picked = overrides.findById(date); + return picked != null ? picked.getSeed() : hashed(date); + } + + /// Every seed fits in 52 bits, so it survives a JSON parser that reads + /// numbers as doubles exactly. + public static final long SEED_MASK = (1L << 52) - 1; + + /// The seed a date gets when nobody picked one: the first 52 bits of the + /// SHA-256 of `ledge-daily:` and the date. Positive, so it reads the + /// same in every log. + public static long hashed(String date) throws IOException { + return Long.parseLong(Ids.sha256("ledge-daily:" + date).substring(0, 13), 16); + } + + /// Overrides today's seed. + @Transactional(rollbackFor = IOException.class) + public void pick(String admin, long seed) throws IOException { + String date = Clock.date(Clock.now()); + DailySeed row = overrides.findById(date); + boolean fresh = row == null; + if (fresh) { + row = new DailySeed(); + row.setDay(date); + } + row.setSeed(seed); + row.setSetBy(admin); + row.setCreatedAt(Instant.now()); + if (fresh) { + overrides.insert(row); + } else { + overrides.save(row); + } + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Modes.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Modes.java new file mode 100644 index 00000000000..c957ce1c177 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Modes.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.run; + +import com.codename1.backend.ResponseStatusException; +import com.codenameone.examples.ledge.levels.LevelPack; + +/// The levels a run can be for, and the periods a board covers. +public final class Modes { + /// What `StartRunDto.level` says for today's challenge. + public static final String DAILY = "daily"; + public static final String ALL = "ALL"; + public static final String WEEK = "WEEK"; + public static final String TODAY = "TODAY"; + public static final String FRIENDS = "FRIENDS"; + + private Modes() { + } + + /// `value` as an index into `LevelPack`. + public static int level(String value) { + int i = value == null ? -1 : LevelPack.indexOf(value); + if (i < 0) { + throw new ResponseStatusException(400, "No such level"); + } + return i; + } + + public static String period(String value) { + if (value == null || value.length() == 0) { + return ALL; + } + String[] all = {ALL, WEEK, TODAY, FRIENDS}; + for (String p : all) { + if (p.equalsIgnoreCase(value)) { + return p; + } + } + throw new ResponseStatusException(400, "Period is ALL, WEEK, TODAY or FRIENDS"); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/RunEndpoint.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/RunEndpoint.java new file mode 100644 index 00000000000..9885819caa8 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/RunEndpoint.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.run; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.ledge.api.DailyDto; +import com.codenameone.examples.ledge.api.GhostDto; +import com.codenameone.examples.ledge.api.LeaderDto; +import com.codenameone.examples.ledge.api.RunApiServer; +import com.codenameone.examples.ledge.api.RunDto; +import com.codenameone.examples.ledge.api.RunResultDto; +import com.codenameone.examples.ledge.api.RunTicketDto; +import com.codenameone.examples.ledge.api.StartRunDto; +import java.util.List; + +/// `RunApi` on the server. +@Component +public class RunEndpoint implements RunApiServer { + private final Runs runs; + private final Boards boards; + + public RunEndpoint(Runs runs, Boards boards) { + this.runs = runs; + this.boards = boards; + } + + @Override + public RunTicketDto start(StartRunDto request) throws Exception { + return runs.start(Caller.name(), request == null ? null : request.level()); + } + + @Override + public RunResultDto submit(RunDto run) throws Exception { + return runs.submit(Caller.name(), run); + } + + @Override + public List leaderboard(String level, String period) throws Exception { + return boards.leaderboard(Caller.name(), level, period); + } + + @Override + public GhostDto ghost(String level, String username) throws Exception { + return boards.ghost(Caller.name(), level, username); + } + + @Override + public DailyDto daily() throws Exception { + return boards.daily(Caller.name()); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Runs.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Runs.java new file mode 100644 index 00000000000..f2aed8541fc --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/run/Runs.java @@ -0,0 +1,329 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.run; + +import com.codename1.backend.Crypto; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Scheduled; +import com.codename1.backend.annotations.Transactional; +import com.codename1.orm.repository.PageRequest; +import com.codename1.gaming.platformer.Replay; +import com.codenameone.examples.ledge.Clock; +import com.codenameone.examples.ledge.Ids; +import com.codenameone.examples.ledge.admin.Flags; +import com.codenameone.examples.ledge.api.RunDto; +import com.codenameone.examples.ledge.api.RunResultDto; +import com.codenameone.examples.ledge.api.RunTicketDto; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.domain.RunTicket; +import com.codenameone.examples.ledge.domain.ScoreRun; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.progress.Progress; +import com.codenameone.examples.ledge.domain.Attempt; +import com.codenameone.examples.ledge.repository.AttemptRepository; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.RunTicketRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import java.io.IOException; +import java.time.Instant; +import java.util.List; + +/// Tickets and results. +/// +/// The server plays every submitted run again. The game is deterministic, so +/// the level, the ticket's seed and the recorded input decide the outcome +/// completely: the score, time and stars a player is credited with are the +/// ones the replay produced, never numbers the client sent. What the client +/// claims (ticks and the final state hash) only has to agree with it. +@Component +public class Runs { + /// How long a ticket stays good: longer than any run (`Scoring.MAX_TICKS` + /// is ten minutes) plus a pause and a slow network. + public static final long TICKET_MILLIS = 2L * 60 * 60 * 1000; + /// Coins per run: the coins collected in it, at most this many. + public static final int MAX_COINS = 100; + + /// How many failed runs a player may leave on one level an hour. + static final int ATTEMPTS_PER_HOUR = 6; + + /// How long a failed run is kept for the death map. + static final long ATTEMPT_DAYS = 30; + /// Extra coins for playing the daily. + public static final int DAILY_BONUS = 5; + /// A run this much faster than the shipped solver's is held for review. + public static final double FLOOR_RATIO = 0.6; + /// The longest log the `TEXT` column takes on every database (MySQL's is + /// 65,535 bytes; logs are ASCII). + static final int MAX_STORED_LOG = Math.min(Scoring.MAX_LOG_CHARS, 65535); + + private static int[] floors; + + private final RunTicketRepository tickets; + private final ScoreRunRepository runs; + private final ProfileRepository profiles; + private final DailySeeds seeds; + private final Boards boards; + private final Flags flags; + private final AttemptRepository attempts; + + public Runs(RunTicketRepository tickets, ScoreRunRepository runs, ProfileRepository profiles, + DailySeeds seeds, Boards boards, Flags flags, AttemptRepository attempts) { + this.attempts = attempts; + this.tickets = tickets; + this.runs = runs; + this.profiles = profiles; + this.seeds = seeds; + this.boards = boards; + this.flags = flags; + } + + /// Issues a ticket for a level id, or for `daily`: today's level on + /// today's seed. + @Transactional(rollbackFor = IOException.class) + public RunTicketDto start(String username, String level) throws IOException { + long now = Clock.now(); + boolean daily = Modes.DAILY.equalsIgnoreCase(level); + int index = daily ? Scoring.dailyLevel(Clock.dayOf(now) / Clock.DAY) : Modes.level(level); + RunTicket t = new RunTicket(); + t.setToken(Ids.next()); + t.setUsername(username); + t.setLevel(LevelPack.IDS[index]); + t.setDaily(daily); + t.setSeed(daily ? seeds.seedOf(now) : randomSeed()); + t.setExpiresAt(Instant.ofEpochMilli(now + TICKET_MILLIS)); + tickets.insert(t); + return new RunTicketDto(t.getToken(), t.getLevel(), daily, t.getSeed(), t.getExpiresAt().toEpochMilli()); + } + + private static long randomSeed() throws IOException { + byte[] b = Crypto.randomBytes(8); + long seed = 0; + for (int i = 0; i < 8; i++) { + seed = (seed << 8) | (b[i] & 0xff); + } + // 52 bits: a seed travels as a JSON number, and a client whose parser + // reads numbers as doubles would round anything wider -- the run would + // then be played on a different seed than the one it is checked on. + return seed & DailySeeds.SEED_MASK; + } + + /// Takes a finished run. A refusal for a reason the player can do nothing + /// about (a stale or reused ticket) is a 4xx; a run the replay does not + /// confirm is answered `accepted=false` with the reason, because the app + /// shows it. Either way the ticket is spent. + @Transactional(rollbackFor = IOException.class) + public RunResultDto submit(String username, RunDto run) throws IOException { + if (run == null || run.token() == null) { + throw new ResponseStatusException(400, "No run"); + } + RunTicket t = tickets.findById(run.token()); + if (t == null || !t.getUsername().equals(username)) { + throw new ResponseStatusException(404, "Unknown ticket"); + } + if (t.isUsed()) { + throw new ResponseStatusException(409, "That ticket was already used"); + } + if (t.getExpiresAt().toEpochMilli() < Clock.now()) { + throw new ResponseStatusException(410, "That ticket has expired"); + } + // Spent before anything else, and by a conditional update, so a second + // submit racing this one finds it used even before this commits. + if (tickets.use(t.getToken()) == 0) { + throw new ResponseStatusException(409, "That ticket was already used"); + } + int index = LevelPack.indexOf(t.getLevel()); + long issued = t.getExpiresAt().toEpochMilli() - TICKET_MILLIS; + if (t.isDaily() && Clock.dayOf(issued) != Clock.dayOf(Clock.now())) { + // A daily's level and seed are the day it was issued on; finished + // after midnight it would count towards the next day's board. + return refused(username, index, "That daily challenge has ended"); + } + String log = run.log(); + Replay.Result r = log == null || log.length() > MAX_STORED_LOG ? null + : Scoring.replay(index, t.getSeed(), log); + if (r == null) { + return refused(username, index, "That run could not be replayed"); + } + if (!r.isComplete()) { + attempt(username, index, t.getSeed(), log, r, Clock.now()); + return refused(username, index, "That run does not reach the exit"); + } + if (r.getTicks() != run.ticks() || r.getHash() != run.hash()) { + return refused(username, index, "That run does not replay to the result it claims"); + } + // Ledge's levels draw nothing from the world's Rng, so a run replays + // the same on any seed and a ghost's log could be submitted again on + // a fresh ticket. Refusing an exact copy would not help -- one idle + // tick more makes it a different log -- so the defence is the board + // itself: a copy scores exactly what the original did, never more, a + // tie ranks the earlier run first, and it pays no coins unless it is + // the submitter's own new best. A level that wants copies to fail + // draws on the seed (AIBrain.Chance, a hazard's phase). + // Game time cannot run ahead of the wall clock: the run cannot have + // lasted longer than the ticket has existed. + long elapsed = (Clock.now() - issued) / 1000 + 5; + long seconds = r.getTicks() / Scoring.TICKS_PER_SECOND; + if (seconds > elapsed) { + return refused(username, index, + "That run lasts " + seconds + " seconds, but it started " + elapsed + " seconds ago"); + } + return record(username, index, t.isDaily(), t.getSeed(), log, r, Clock.now()); + } + + /// Keeps a run that died short of the exit, for the death map. One that + /// never died tells the map nothing and is not kept, and a player leaves + /// at most [#ATTEMPTS_PER_HOUR] an hour on a level, so neither the table + /// nor the map can be filled by one account dying on purpose. + public void attempt(String username, int index, long seed, String log, Replay.Result result, long when) + throws IOException { + if (result == null || result.getDeaths() == 0) { + return; + } + if (attempts.countSince(username, LevelPack.IDS[index], + Instant.ofEpochMilli(when - 3600000L)).longValue() >= ATTEMPTS_PER_HOUR) { + return; + } + Attempt a = new Attempt(); + a.setId(Ids.next()); + a.setUsername(username); + a.setLevel(LevelPack.IDS[index]); + a.setSeed(seed); + a.setLog(log); + a.setCreatedAt(Instant.ofEpochMilli(when)); + attempts.insert(a); + } + + private RunResultDto refused(String username, int index, String message) { + return new RunResultDto(false, false, false, 0, 0, 0, best(username, index), 0, 0, message); + } + + /// Stores a replayed, finished run and pays for it. Also how the demo data + /// is written, with a `when` in the past. + @Transactional(rollbackFor = IOException.class) + public RunResultDto record(String username, int index, boolean daily, long seed, String log, + Replay.Result result, long when) throws IOException { + if (profiles.hold(username) == 0) { + throw new ResponseStatusException(404, "No such account"); + } + Profile p = profile(username); + String level = LevelPack.IDS[index]; + long score = Scoring.points(index, result); + int stars = Scoring.stars(index, result); + long before = best(username, index); + ScoreRun r = new ScoreRun(); + r.setId(Ids.next()); + r.setUsername(username); + r.setLevel(level); + r.setDaily(daily); + r.setScore(score); + r.setTicks(result.getTicks()); + r.setStars(stars); + r.setSeed(seed); + r.setLog(log); + r.setDay(Clock.dayOf(when)); + r.setCreatedAt(Instant.ofEpochMilli(when)); + boolean firstDaily = daily && runs.dailiesOn(username, r.getDay()).longValue() == 0; + runs.insert(r); + boolean newBest = !daily && score > before; + // Coins are paid for a new best of a level and for the first daily of + // the day, never for replaying a level already beaten: the economy is + // bounded, as the shop's ad rewards are. + int coins = (newBest || firstDaily ? Math.min(MAX_COINS, Math.max(0, result.getCoins())) : 0) + + (firstDaily ? DAILY_BONUS : 0); + p.setCoins(p.getCoins() + coins); + p.setProgress(Progress.raise(p.getProgress(), index, stars)); + if (daily && score > p.getBestDaily()) { + p.setBestDaily(score); + } + p.setRuns(p.getRuns() + 1); + p.setLastSeen(Instant.ofEpochMilli(Math.max(when, p.getLastSeen().toEpochMilli()))); + boolean flagged = result.getTicks() < floor(index); + if (flagged) { + p.setFlagged(true); + } + profiles.save(p); + if (flagged) { + flags.file(p, r, "Faster than the solver"); + } + return new RunResultDto(true, flagged, newBest, score, result.getTicks(), stars, + daily ? p.getBestDaily() : Math.max(before, score), + daily ? 0 : boards.rank(username, level), coins, newBest ? "New best!" : "Run saved"); + } + + /// The fewest ticks a run of level `index` may take before it is held for + /// review: [#FLOOR_RATIO] of the shipped demo's time. Worked out once. + static int floor(int index) { + int[] f = floors; + if (f == null) { + f = new int[LevelPack.IDS.length]; + for (int i = 0; i < f.length; i++) { + String demo = LevelPack.demo(i); + Replay.Result r = demo.length() == 0 ? null : Scoring.replay(i, 1, demo); + f[i] = r == null || !r.isComplete() ? 0 : (int) (r.getTicks() * FLOOR_RATIO); + } + floors = f; + } + return f[index]; + } + + /// Works a player's progress and daily best out again from their standing + /// runs, after an admin struck some. + @Transactional(rollbackFor = IOException.class) + public void recomputeBests(String username) { + Profile p = profile(username); + String progress = Progress.EMPTY; + long daily = 0; + for (ScoreRun r : runs.of(username)) { + progress = Progress.raise(progress, LevelPack.indexOf(r.getLevel()), r.getStars()); + if (r.isDaily()) { + daily = Math.max(daily, r.getScore()); + } + } + p.setProgress(progress); + p.setBestDaily(daily); + profiles.save(p); + } + + /// Clears the tickets nobody came back for. + @Scheduled(fixedDelay = 600000, initialDelay = 600000) + @Transactional + public void sweep() throws IOException { + tickets.deleteByExpiresAtLessThan(Instant.ofEpochMilli(Clock.now() - Clock.DAY)); + attempts.prune(Instant.ofEpochMilli(Clock.now() - ATTEMPT_DAYS * Clock.DAY)); + } + + /// The player's best standing score on level `index`, 0 for none. + long best(String username, int index) { + if (index < 0) { + return 0; + } + List mine = runs.bestOf(username, LevelPack.IDS[index], new PageRequest(0, 1)); + return mine.isEmpty() ? 0 : mine.get(0).getScore(); + } + + private Profile profile(String username) { + Profile p = profiles.findById(username); + if (p == null) { + throw new ResponseStatusException(404, "No such account"); + } + return p; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/Catalog.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/Catalog.java new file mode 100644 index 00000000000..ade788ed39b --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/Catalog.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.shop; + +import com.codenameone.examples.ledge.api.ShopItemDto; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/// What the shop sells. Fixed in code rather than in a table: prices are part +/// of a release, and a catalogue the console could edit is a feature this +/// sample does not need. +public final class Catalog { + public static final String SCARF = "scarf"; + public static final String COINS = "coins"; + public static final String ADFREE = "adfree"; + /// The scarf every player owns from the start. + public static final String FREE_SCARF = "scarf-ember"; + /// The store product that turns the ads off, kept in `owned` once bought. + public static final String ADFREE_ITEM = "adfree"; + + private static final List ITEMS; + + static { + List items = new ArrayList(); + items.add(new ShopItemDto(FREE_SCARF, "Ember", SCARF, 0, null, "#ff7648")); + items.add(new ShopItemDto("scarf-teal", "Teal", SCARF, 150, null, "#2bb3a3")); + items.add(new ShopItemDto("scarf-mint", "Mint", SCARF, 250, null, "#8fe3b0")); + items.add(new ShopItemDto("scarf-violet", "Violet", SCARF, 400, null, "#8a5cf6")); + items.add(new ShopItemDto("scarf-midnight", "Midnight", SCARF, 600, null, "#22305a")); + items.add(new ShopItemDto("scarf-gold", "Gold", SCARF, 1200, null, "#f2c14e")); + items.add(new ShopItemDto("coins-small", "Pouch of Coins", COINS, 0, "ledge.coins.small", null)); + items.add(new ShopItemDto("coins-large", "Chest of Coins", COINS, 0, "ledge.coins.large", null)); + items.add(new ShopItemDto(ADFREE_ITEM, "No Ads", ADFREE, 0, "ledge.adfree", null)); + ITEMS = Collections.unmodifiableList(items); + } + + private Catalog() { + } + + public static List items() { + return ITEMS; + } + + public static ShopItemDto byId(String id) { + for (ShopItemDto item : ITEMS) { + if (item.id().equals(id)) { + return item; + } + } + return null; + } + + public static ShopItemDto bySku(String sku) { + for (ShopItemDto item : ITEMS) { + if (item.sku() != null && item.sku().equals(sku)) { + return item; + } + } + return null; + } + + /// The coins a store pack grants. + public static int coins(ShopItemDto item) { + if ("ledge.coins.small".equals(item.sku())) { + return 500; + } + if ("ledge.coins.large".equals(item.sku())) { + return 3000; + } + return 0; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/MisconfiguredReceipts.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/MisconfiguredReceipts.java new file mode 100644 index 00000000000..92a4521756f --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/MisconfiguredReceipts.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.shop; + +import com.codename1.backend.ResponseStatusException; + +/// Stands in when the store settings are missing, so the server still starts and +/// says what is wrong instead of granting purchases it cannot check. +public class MisconfiguredReceipts implements ReceiptValidator { + private final String problem; + + public MisconfiguredReceipts(String problem) { + this.problem = problem; + System.err.println("[config] " + problem); + } + + @Override + public String verify(String store, String sku, String transactionId, String receipt) { + throw new ResponseStatusException(503, "Purchases are not available right now"); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/ReceiptValidator.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/ReceiptValidator.java new file mode 100644 index 00000000000..3b9cac7c31d --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/ReceiptValidator.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.shop; + +import java.io.IOException; + +/// Asks a store whether a purchase is real. The server grants nothing on the +/// app's word: a modified client can claim any purchase it likes. +// tag::ledge-receipt-validator[] +public interface ReceiptValidator { + /// The store's transaction id when `receipt` proves a purchase of `sku`, or + /// null when it does not. + String verify(String store, String sku, String transactionId, String receipt) throws IOException; +} +// end::ledge-receipt-validator[] diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/Shop.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/Shop.java new file mode 100644 index 00000000000..accb6066302 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/Shop.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.shop; + +import com.codename1.appkit.server.Text; +import com.codename1.backend.ResponseStatusException; +import com.codename1.backend.annotations.Component; +import com.codename1.backend.annotations.Transactional; +import com.codenameone.examples.ledge.Ids; +import com.codenameone.examples.ledge.account.Lists; +import com.codenameone.examples.ledge.api.AdRewardDto; +import com.codenameone.examples.ledge.api.ReceiptDto; +import com.codenameone.examples.ledge.api.ShopItemDto; +import com.codenameone.examples.ledge.api.WalletDto; +import com.codenameone.examples.ledge.domain.AdNonce; +import com.codenameone.examples.ledge.domain.Profile; +import com.codenameone.examples.ledge.domain.StorePurchase; +import com.codenameone.examples.ledge.repository.AdNonceRepository; +import com.codenameone.examples.ledge.repository.ProfileRepository; +import com.codenameone.examples.ledge.repository.StorePurchaseRepository; +import java.io.IOException; +import com.codenameone.examples.ledge.Clock; +import java.time.Instant; + +/// The wallet. Every change takes the profile row's lock first, so two taps +/// on "buy" cannot both spend the same coins. +@Component +public class Shop { + /// What one watched rewarded ad pays. + public static final int AD_REWARD = 15; + /// Rewarded ads paid per account per UTC day. The nonce is the client's, + /// so it proves nothing by itself: without a server-to-server callback + /// from a real ad network, this cap (and the route's rate limit) is what + /// bounds the coins a modified client can mint -- a few hundred a day, + /// less than a single coin pack. A fork wiring a real network should + /// grant from that network's verification callback instead. + public static final int AD_REWARDS_PER_DAY = 10; + + private final ProfileRepository profiles; + private final StorePurchaseRepository purchases; + private final AdNonceRepository nonces; + private final ReceiptValidator validator; + + public Shop(ProfileRepository profiles, StorePurchaseRepository purchases, AdNonceRepository nonces, + ReceiptValidator validator) { + this.profiles = profiles; + this.purchases = purchases; + this.nonces = nonces; + this.validator = validator; + } + + @Transactional(readOnly = true) + public WalletDto wallet(String username) { + return toDto(profile(username)); + } + + /// Buys a scarf, once. Coin packs and ad-free cost real money and only + /// come through a receipt. + @Transactional(rollbackFor = IOException.class) + public WalletDto buy(String username, String itemId) throws IOException { + ShopItemDto item = Catalog.byId(itemId == null ? "" : itemId); + if (item == null || !Catalog.SCARF.equals(item.kind())) { + throw new ResponseStatusException(404, "No such item"); + } + hold(username); + Profile p = profile(username); + if (Lists.contains(p.getOwned(), item.id())) { + throw new ResponseStatusException(409, "You already own that scarf"); + } + if (p.getCoins() < item.priceCoins()) { + throw new ResponseStatusException(402, "Not enough coins"); + } + p.setCoins(p.getCoins() - item.priceCoins()); + p.setOwned(own(p.getOwned(), item.id())); + profiles.save(p); + return toDto(p); + } + + @Transactional(rollbackFor = IOException.class) + public WalletDto equip(String username, String scarf) throws IOException { + hold(username); + Profile p = profile(username); + ShopItemDto item = Catalog.byId(scarf == null ? "" : scarf); + if (item == null || !Catalog.SCARF.equals(item.kind()) || !Lists.contains(p.getOwned(), scarf)) { + throw new ResponseStatusException(403, "You do not own that scarf"); + } + p.setScarf(scarf); + profiles.save(p); + return toDto(p); + } + + /// Grants a store purchase once its receipt checks out. The key is the + /// hash of the store's transaction id, so replaying a receipt -- the app + /// retrying after a lost answer -- grants nothing a second time. + public WalletDto receipt(String username, ReceiptDto receipt) throws IOException { + if (receipt == null) { + throw new ResponseStatusException(400, "No receipt"); + } + String store = Text.oneOf(receipt.store(), new String[] {"itunes", "play", "simulator"}, "", + "the store"); + ShopItemDto item = Catalog.bySku(receipt.sku()); + if (item == null) { + throw new ResponseStatusException(404, "Unknown product"); + } + String transaction = validator.verify(store, receipt.sku(), + Text.optional(receipt.transactionId(), 190, "the transaction"), receipt.receipt()); + if (transaction == null) { + throw new ResponseStatusException(402, "The store did not confirm this purchase"); + } + return redeem(username, store, item, transaction); + } + + @Transactional(rollbackFor = IOException.class) + WalletDto redeem(String username, String store, ShopItemDto item, String transaction) throws IOException { + hold(username); + Profile p = profile(username); + String key = Ids.sha256(transaction); + StorePurchase seen = purchases.findById(key); + if (seen != null) { + if (!seen.getUsername().equals(username)) { + throw new ResponseStatusException(409, "That purchase belongs to another account"); + } + return toDto(p); + } + StorePurchase row = new StorePurchase(); + row.setId(key); + row.setUsername(username); + row.setStore(store); + row.setSku(item.sku()); + int coins = Catalog.coins(item); + row.setCoins(coins); + row.setCreatedAt(Instant.now()); + purchases.insert(row); + p.setCoins(p.getCoins() + coins); + if (Catalog.ADFREE.equals(item.kind())) { + p.setOwned(own(p.getOwned(), item.id())); + } + profiles.save(p); + return toDto(p); + } + + private static String own(String owned, String id) { + if (Lists.contains(owned, id)) { + return owned; + } + return owned.length() == 0 ? id : owned + "," + id; + } + + /// Pays for a watched rewarded ad: each nonce once, and at most + /// [#AD_REWARDS_PER_DAY] a day. + @Transactional(rollbackFor = IOException.class) + public WalletDto adReward(String username, AdRewardDto reward) throws IOException { + String nonce = Text.required(reward == null ? null : reward.nonce(), 190, "the ad nonce"); + hold(username); + Profile p = profile(username); + String key = Ids.sha256(nonce); + if (nonces.findById(key) != null) { + throw new ResponseStatusException(409, "That ad was already rewarded"); + } + long dayStart = Clock.now() / 86400000L * 86400000L; + if (nonces.countByUsernameAndCreatedAtAfter(username, Instant.ofEpochMilli(dayStart)) + >= AD_REWARDS_PER_DAY) { + throw new ResponseStatusException(429, "That's all the ads for today"); + } + AdNonce row = new AdNonce(); + row.setId(key); + row.setUsername(username); + row.setCreatedAt(Instant.now()); + nonces.insert(row); + p.setCoins(p.getCoins() + AD_REWARD); + profiles.save(p); + return toDto(p); + } + + /// The wallet as the app sees it. + public static WalletDto toDto(Profile p) { + return new WalletDto(p.getCoins(), Lists.split(p.getOwned()), p.getScarf()); + } + + private void hold(String username) { + if (profiles.hold(username) == 0) { + throw new ResponseStatusException(404, "No such account"); + } + } + + private Profile profile(String username) { + Profile p = profiles.findById(username); + if (p == null) { + throw new ResponseStatusException(404, "No such account"); + } + return p; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/ShopEndpoint.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/ShopEndpoint.java new file mode 100644 index 00000000000..cdc08c21d18 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/ShopEndpoint.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.shop; + +import com.codename1.appkit.server.Caller; +import com.codename1.backend.annotations.Component; +import com.codenameone.examples.ledge.api.AdRewardDto; +import com.codenameone.examples.ledge.api.BuyDto; +import com.codenameone.examples.ledge.api.EquipDto; +import com.codenameone.examples.ledge.api.ReceiptDto; +import com.codenameone.examples.ledge.api.ShopApiServer; +import com.codenameone.examples.ledge.api.ShopItemDto; +import com.codenameone.examples.ledge.api.WalletDto; +import java.util.List; + +/// `ShopApi` on the server. +@Component +public class ShopEndpoint implements ShopApiServer { + private final Shop shop; + + public ShopEndpoint(Shop shop) { + this.shop = shop; + } + + @Override + public List items() throws Exception { + return Catalog.items(); + } + + @Override + public WalletDto wallet() throws Exception { + return shop.wallet(Caller.name()); + } + + @Override + public WalletDto buy(BuyDto item) throws Exception { + return shop.buy(Caller.name(), item == null ? null : item.itemId()); + } + + @Override + public WalletDto equip(EquipDto scarf) throws Exception { + return shop.equip(Caller.name(), scarf == null ? null : scarf.scarf()); + } + + @Override + public WalletDto receipt(ReceiptDto receipt) throws Exception { + return shop.receipt(Caller.name(), receipt); + } + + @Override + public WalletDto adReward(AdRewardDto reward) throws Exception { + return shop.adReward(Caller.name(), reward); + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/SimulatedReceipts.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/SimulatedReceipts.java new file mode 100644 index 00000000000..bf053498e7c --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/SimulatedReceipts.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.shop; + +/// Development and tests: accepts the receipts the simulator's store produces, +/// which carry no signature to check. Refused outside development profiles. +public class SimulatedReceipts implements ReceiptValidator { + @Override + public String verify(String store, String sku, String transactionId, String receipt) { + if (transactionId == null || transactionId.length() == 0 || sku == null) { + return null; + } + return "sim:" + transactionId; + } +} diff --git a/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/StoreReceipts.java b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/StoreReceipts.java new file mode 100644 index 00000000000..a6a39205637 --- /dev/null +++ b/scripts/ledge/backend/src/main/java/com/codenameone/examples/ledge/shop/StoreReceipts.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.shop; + +import com.codename1.backend.Json; +import com.codename1.backend.Web; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/// Verifies receipts with the stores themselves. +/// +/// - Apple: the receipt is posted to `verifyReceipt` with the app's shared +/// secret; a sandbox receipt (status 21007) is retried against the sandbox. +/// Apple now recommends the App Store Server API for new code; this endpoint +/// still answers, and keeps the sample free of a signing-key setup. Swap the +/// method for a call to `/inApps/v1/transactions/{id}` when you outgrow it. +/// - Google Play: the purchase token is checked with the Play Developer API, +/// authorized by an OAuth access token for a service account with the +/// "View financial data" permission (`ledge.iap.google.token`). Minting +/// that token from the service account key is left to your deployment. +// tag::ledge-store-receipts[] +public class StoreReceipts implements ReceiptValidator { + static final String APPLE_PRODUCTION = "https://buy.itunes.apple.com/verifyReceipt"; + static final String APPLE_SANDBOX = "https://sandbox.itunes.apple.com/verifyReceipt"; + + private final String appleSecret; + private final String appleBundle; + private final String googlePackage; + private final String googleToken; + + public StoreReceipts(String appleSecret, String appleBundle, String googlePackage, String googleToken) { + this.appleSecret = appleSecret; + this.appleBundle = appleBundle; + this.googlePackage = googlePackage; + this.googleToken = googleToken; + } + + @Override + public String verify(String store, String sku, String transactionId, String receipt) throws IOException { + if ("itunes".equals(store)) { + return apple(sku, transactionId, receipt); + } + if ("play".equals(store)) { + return google(sku, receipt); + } + return null; + } + + private String apple(String sku, String transactionId, String receipt) throws IOException { + if (appleSecret.length() == 0) { + return null; + } + String body = "{\"receipt-data\":" + Json.write(receipt) + ",\"password\":" + Json.write(appleSecret) + + ",\"exclude-old-transactions\":true}"; + Map answer = Json.parseObject(Web.postJson(APPLE_PRODUCTION, body, null).getBodyAsString()); + if (answer.get("status") instanceof Number && ((Number) answer.get("status")).intValue() == 21007) { + answer = Json.parseObject(Web.postJson(APPLE_SANDBOX, body, null).getBodyAsString()); + } + if (!(answer.get("status") instanceof Number) || ((Number) answer.get("status")).intValue() != 0) { + return null; + } + Object r = answer.get("receipt"); + // A receipt is only good for the app it was issued to. + if (!(r instanceof Map) || !appleBundle.equals(((Map) r).get("bundle_id"))) { + return null; + } + Object inApp = r instanceof Map ? ((Map) r).get("in_app") : null; + if (!(inApp instanceof List)) { + return null; + } + for (Object each : (List) inApp) { + if (each instanceof Map) { + Map t = (Map) each; + if (sku.equals(t.get("product_id")) && transactionId != null + && transactionId.equals(t.get("transaction_id"))) { + return "itunes:" + transactionId; + } + } + } + return null; + } + + private String google(String sku, String purchaseToken) throws IOException { + if (googleToken.length() == 0 || googlePackage.length() == 0 || purchaseToken == null) { + return null; + } + // The token and the SKU come from the client: anything but the + // characters Play uses would change which resource the request reads. + if (!pathSafe(sku) || !pathSafe(purchaseToken)) { + return null; + } + String url = "https://androidpublisher.googleapis.com/androidpublisher/v3/applications/" + + googlePackage + "/purchases/products/" + sku + "/tokens/" + purchaseToken; + Web.Result answer = Web.getJson(url, googleToken); + if (!answer.isSuccess()) { + return null; + } + Map purchase = Json.parseObject(answer.getBodyAsString()); + Object state = purchase.get("purchaseState"); + Object order = purchase.get("orderId"); + if (!(state instanceof Number) || ((Number) state).intValue() != 0 || !(order instanceof String)) { + return null; + } + return "play:" + order; + } + + private static boolean pathSafe(String s) { + if (s == null || s.length() == 0 || s.length() > 512) { + return false; + } + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' + || c == '.' || c == '_' || c == '-')) { + return false; + } + } + return !s.contains(".."); + } +} +// end::ledge-store-receipts[] diff --git a/scripts/ledge/backend/src/main/resources/db/migration/V1__game.sql b/scripts/ledge/backend/src/main/resources/db/migration/V1__game.sql new file mode 100644 index 00000000000..cd52b19b58b --- /dev/null +++ b/scripts/ledge/backend/src/main/resources/db/migration/V1__game.sql @@ -0,0 +1,133 @@ +-- The tables every database shares. Portable SQL only: no generated keys, no +-- native boolean (a yes/no is a SMALLINT 0/1), times are epoch milliseconds. +-- Pushes, purchases and the audit log are at the end. + +CREATE TABLE profile ( + username VARCHAR(190) NOT NULL PRIMARY KEY, + display_name VARCHAR(40) NOT NULL, + coins INTEGER NOT NULL, + progress VARCHAR(64) NOT NULL, + best_daily BIGINT NOT NULL, + runs INTEGER NOT NULL, + scarf VARCHAR(40) NOT NULL, + owned VARCHAR(1000) NOT NULL, + flagged SMALLINT NOT NULL, + suspended_until BIGINT NOT NULL, + banned SMALLINT NOT NULL, + created_at BIGINT NOT NULL, + last_seen BIGINT NOT NULL +); + +CREATE TABLE score_run ( + id VARCHAR(32) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + level VARCHAR(16) NOT NULL, + daily SMALLINT NOT NULL, + score BIGINT NOT NULL, + ticks INTEGER NOT NULL, + stars INTEGER NOT NULL, + seed BIGINT NOT NULL, + log TEXT NOT NULL, + day BIGINT NOT NULL, + created_at BIGINT NOT NULL, + struck SMALLINT NOT NULL +); +CREATE INDEX score_run_board ON score_run (level, created_at); +CREATE INDEX score_run_username ON score_run (username, created_at); + +CREATE TABLE run_ticket ( + token VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + level VARCHAR(16) NOT NULL, + daily SMALLINT NOT NULL, + seed BIGINT NOT NULL, + expires_at BIGINT NOT NULL, + used SMALLINT NOT NULL +); +CREATE INDEX run_ticket_expires ON run_ticket (expires_at); + +CREATE TABLE attempt ( + id VARCHAR(32) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + level VARCHAR(16) NOT NULL, + seed BIGINT NOT NULL, + log TEXT NOT NULL, + created_at BIGINT NOT NULL +); +CREATE INDEX attempt_level ON attempt (level, created_at); +CREATE INDEX attempt_username ON attempt (username, level, created_at); + +CREATE TABLE flag ( + id VARCHAR(32) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + run_id VARCHAR(32) NOT NULL, + level VARCHAR(16) NOT NULL, + score BIGINT NOT NULL, + ticks INTEGER NOT NULL, + reason VARCHAR(255) NOT NULL, + created_at BIGINT NOT NULL, + pending SMALLINT NOT NULL, + resolved_by VARCHAR(190) NOT NULL +); +CREATE INDEX flag_pending ON flag (pending, created_at); +CREATE INDEX flag_username ON flag (username); + +CREATE TABLE friend ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + friend VARCHAR(190) NOT NULL, + created_at BIGINT NOT NULL +); +CREATE INDEX friend_username ON friend (username); + +CREATE TABLE daily_seed ( + day VARCHAR(10) NOT NULL PRIMARY KEY, + seed BIGINT NOT NULL, + set_by VARCHAR(190) NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE TABLE ad_nonce ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE TABLE broadcast ( + id VARCHAR(32) NOT NULL PRIMARY KEY, + title VARCHAR(80) NOT NULL, + body VARCHAR(255) NOT NULL, + days INTEGER NOT NULL, + targets INTEGER NOT NULL, + created_at BIGINT NOT NULL +); + +CREATE TABLE push_device ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + provider VARCHAR(16) NOT NULL, + token VARCHAR(1024) NOT NULL, + platform VARCHAR(32) NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX push_device_username ON push_device (username); + +CREATE TABLE store_purchase ( + id VARCHAR(64) NOT NULL PRIMARY KEY, + username VARCHAR(190) NOT NULL, + store VARCHAR(16) NOT NULL, + sku VARCHAR(64) NOT NULL, + coins INTEGER NOT NULL, + created_at BIGINT NOT NULL +); +CREATE INDEX store_purchase_username ON store_purchase (username); + +CREATE TABLE admin_action ( + id VARCHAR(32) NOT NULL PRIMARY KEY, + admin VARCHAR(190) NOT NULL, + username VARCHAR(190) NOT NULL, + action VARCHAR(24) NOT NULL, + reason VARCHAR(255) NOT NULL, + created_at BIGINT NOT NULL +); +CREATE INDEX admin_action_created ON admin_action (created_at); diff --git a/scripts/ledge/backend/src/main/resources/db/migration/mysql/V2__collation.sql b/scripts/ledge/backend/src/main/resources/db/migration/mysql/V2__collation.sql new file mode 100644 index 00000000000..62145deb5f9 --- /dev/null +++ b/scripts/ledge/backend/src/main/resources/db/migration/mysql/V2__collation.sql @@ -0,0 +1,15 @@ +-- Usernames and display names compare exactly, the way they do on the other +-- databases: binary and NO PAD, never MySQL's case-insensitive default. +ALTER DATABASE CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE profile CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE score_run CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE run_ticket CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE attempt CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE flag CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE friend CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE daily_seed CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE ad_nonce CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE broadcast CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE push_device CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE store_purchase CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; +ALTER TABLE admin_action CONVERT TO CHARACTER SET utf8mb4 COLLATE /*!80000 utf8mb4_0900_bin */ /*M!100400 utf8mb4_nopad_bin */; diff --git a/scripts/ledge/backend/src/main/resources/db/migration/postgresql/V2__collation.sql b/scripts/ledge/backend/src/main/resources/db/migration/postgresql/V2__collation.sql new file mode 100644 index 00000000000..3041cad68a7 --- /dev/null +++ b/scripts/ledge/backend/src/main/resources/db/migration/postgresql/V2__collation.sql @@ -0,0 +1,2 @@ +-- Text is already case sensitive here; see mysql/V2__collation.sql. +SELECT 1; diff --git a/scripts/ledge/backend/src/main/resources/db/migration/sqlite/V2__collation.sql b/scripts/ledge/backend/src/main/resources/db/migration/sqlite/V2__collation.sql new file mode 100644 index 00000000000..d13b0e7e144 --- /dev/null +++ b/scripts/ledge/backend/src/main/resources/db/migration/sqlite/V2__collation.sql @@ -0,0 +1,2 @@ +-- Text is already case sensitive and NO PAD here; see mysql/V2__collation.sql. +SELECT 1; diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/AccountTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/AccountTest.java new file mode 100644 index 00000000000..ccf27ea7187 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/AccountTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.ledge.account.Accounts; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Registration, the signed-in player and the profile. +@BackendTest +class AccountTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + + @Test + void aNewPlayerStartsWithTheFreeScarfAndCanRenameThemselves() throws Exception { + String who = Api.player(accounts, "newcomer"); + Map me = Api.json(mvc, Api.as(get("/api/me"), who)); + assertEquals("newcomer", me.get("displayName")); + assertEquals((long) Accounts.START_COINS, Api.number(me, "coins")); + assertEquals("scarf-ember", me.get("scarf")); + assertEquals("0000000000000", me.get("progress")); + assertFalse((Boolean) me.get("admin")); + Map renamed = Api.json(mvc, Api.as(Api.body(post("/api/me/profile"), + "{\"displayName\":\"Fresh Sheet\"}"), who)); + assertEquals("Fresh Sheet", renamed.get("displayName")); + // A scarf nobody bought cannot be equipped through the profile either. + assertEquals(403, Api.statusOf(mvc, Api.as(Api.body(post("/api/me/profile"), + "{\"scarf\":\"scarf-gold\"}"), who))); + } + + @Test + void anAddressRegistersOnceAndBadInputIsRefused() throws Exception { + String body = "{\"email\":\"Twice@Test.example\",\"password\":\"long-enough\",\"displayName\":\"Twice\"}"; + Map first = Api.json(mvc, Api.body(post("/api/account/register"), body)); + assertEquals("twice@test.example", first.get("username")); + assertEquals(409, Api.statusOf(mvc, Api.body(post("/api/account/register"), body))); + assertEquals(400, Api.statusOf(mvc, Api.body(post("/api/account/register"), + "{\"email\":\"nope\",\"password\":\"long-enough\",\"displayName\":\"Nope\"}"))); + assertEquals(400, Api.statusOf(mvc, Api.body(post("/api/account/register"), + "{\"email\":\"short@test.example\",\"password\":\"x\",\"displayName\":\"Short\"}"))); + } + + @Test + void theDemoFieldIsSeeded() throws Exception { + assertTrue(accounts.exists("player@ledge.example")); + assertTrue(accounts.isAdmin("admin@ledge.example")); + Map trouble = Api.json(mvc, Api.as(get("/api/me"), "trouble@ledge.example")); + assertTrue((Boolean) trouble.get("flagged")); + List board = Api.list(mvc, Api.as(get("/api/leaderboard?level=1-1&period=ALL"), + "player@ledge.example")); + assertFalse(board.isEmpty()); + Map ghost = Api.json(mvc, Api.as(get("/api/ghost?level=1-1"), "player@ledge.example")); + assertTrue(((String) ghost.get("log")).length() > 0); + Map player = Api.json(mvc, Api.as(get("/api/me"), "player@ledge.example")); + assertTrue(((String) player.get("progress")).charAt(0) > '0'); + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/AdminTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/AdminTest.java new file mode 100644 index 00000000000..20ca6cbed64 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/AdminTest.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.ledge.account.Accounts; +import com.codenameone.examples.ledge.admin.Flags; +import com.codenameone.examples.ledge.repository.RunTicketRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// The console: every route is ADMIN-only, every action lands in the audit +/// log, and REMOVE on a flag takes the run off the boards. +@BackendTest +class AdminTest { + private static final String ADMIN = "admin@ledge.example"; + + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + @Autowired + private RunTicketRepository tickets; + @Autowired + private ScoreRunRepository runs; + @Autowired + private Flags flags; + + @Test + void everyRouteNeedsTheAdminRole() throws Exception { + String who = Api.player(accounts, "nosy"); + assertEquals(403, Api.statusOf(mvc, Api.as(get("/api/admin/stats"), who))); + assertEquals(403, Api.statusOf(mvc, Api.as(get("/api/admin/audit"), who))); + assertEquals(403, Api.statusOf(mvc, Api.as(Api.body(post("/api/admin/players/" + who + "/action"), + "{\"action\":\"BAN\",\"reason\":\"me\",\"days\":0}"), who))); + assertEquals(403, Api.statusOf(mvc, Api.as(Api.body(post("/api/admin/daily"), "{\"seed\":1}"), who))); + Map stats = Api.json(mvc, Api.asAdmin(get("/api/admin/stats"), ADMIN)); + assertTrue(Api.number(stats, "players") >= 19); + assertTrue(Api.number(stats, "flagsOpen") >= 1); + assertFalse(Api.list(mvc, Api.asAdmin(get("/api/admin/players?q=ledge"), ADMIN)).isEmpty()); + } + + @Test + void aBanTakesAPlayerOffTheBoardsAndIsAudited() throws Exception { + String who = Api.player(accounts, "banned"); + Api.play(mvc, tickets, who, 0); + Api.stored(runs, who, "1-3", 12345678, 3000, System.currentTimeMillis()); + assertEquals(who, top("1-3", "TODAY", who)); + Map banned = Api.json(mvc, Api.asAdmin(Api.body(post("/api/admin/players/" + who + "/action"), + "{\"action\":\"BAN\",\"reason\":\"test ban\",\"days\":0}"), ADMIN)); + assertTrue((Boolean) banned.get("suspended")); + assertFalse(who.equals(top("1-3", "TODAY", "player@ledge.example"))); + assertTrue(audited(who, "BAN")); + Api.json(mvc, Api.asAdmin(Api.body(post("/api/admin/players/" + who + "/action"), + "{\"action\":\"UNBAN\",\"reason\":\"appeal\",\"days\":0}"), ADMIN)); + assertEquals(who, top("1-3", "TODAY", "player@ledge.example")); + Map reset = Api.json(mvc, Api.asAdmin(Api.body(post("/api/admin/players/" + who + "/action"), + "{\"action\":\"RESET_SCORES\",\"reason\":\"start over\",\"days\":0}"), ADMIN)); + assertEquals("0000000000000", reset.get("progress")); + assertFalse(who.equals(top("1-3", "TODAY", "player@ledge.example"))); + assertTrue(audited(who, "RESET_SCORES")); + } + + @Test + void removingAFlaggedRunStrikesItAndRecomputesTheBest() throws Exception { + String who = Api.player(accounts, "suspect"); + Map first = Api.play(mvc, tickets, who, 0); + assertTrue((Boolean) first.get("accepted")); + Api.play(mvc, tickets, who, 1); + flags.report(who, "test report"); + assertTrue((Boolean) Api.json(mvc, Api.as(get("/api/me"), who)).get("flagged")); + String flag = null; + for (Object f : Api.list(mvc, Api.asAdmin(get("/api/admin/flags?open=true"), ADMIN))) { + if (who.equals(((Map) f).get("username"))) { + flag = (String) ((Map) f).get("id"); + } + } + assertTrue(flag != null); + Map closed = Api.json(mvc, Api.asAdmin(Api.body(post("/api/admin/flags/" + flag + "/resolve"), + "{\"verdict\":\"REMOVE\"}"), ADMIN)); + assertFalse((Boolean) closed.get("open")); + Map me = Api.json(mvc, Api.as(get("/api/me"), who)); + String progress = (String) me.get("progress"); + assertTrue(progress.charAt(0) > '0'); + assertEquals('0', progress.charAt(1)); + assertFalse((Boolean) me.get("flagged")); + for (Object row : Api.list(mvc, Api.as(get("/api/leaderboard?level=1-2&period=ALL"), who))) { + assertFalse(who.equals(((Map) row).get("username"))); + } + assertEquals(409, Api.statusOf(mvc, Api.asAdmin(Api.body(post("/api/admin/flags/" + flag + "/resolve"), + "{\"verdict\":\"KEEP\"}"), ADMIN))); + assertTrue(audited(who, "FLAG REMOVE")); + } + + @Test + void aBroadcastIsAuditedAndCountsItsAudience() throws Exception { + String who = Api.player(accounts, "listener"); + Api.json(mvc, Api.as(Api.body(post("/api/account/push"), + "{\"provider\":\"fcm\",\"token\":\"device-token-for-listener-0001\",\"platform\":\"ios\"}"), who)); + Map sent = Api.json(mvc, Api.asAdmin(Api.body(post("/api/admin/broadcast"), + "{\"title\":\"New scarf\",\"body\":\"Gold is in the shop\",\"days\":0}"), ADMIN)); + assertTrue(Api.number(sent, "targets") >= 1); + assertTrue(audited("", "BROADCAST")); + } + + private String top(String level, String period, String asker) throws Exception { + List board = Api.list(mvc, Api.as(get("/api/leaderboard?level=" + level + "&period=" + period), asker)); + return board.isEmpty() ? null : (String) ((Map) board.get(0)).get("username"); + } + + private boolean audited(String username, String action) throws Exception { + for (Object a : Api.list(mvc, Api.asAdmin(get("/api/admin/audit"), ADMIN))) { + Map row = (Map) a; + if (username.equals(row.get("username")) && action.equals(row.get("action")) + && ADMIN.equals(row.get("admin"))) { + return true; + } + } + return false; + } + + /// A run that died on the way is replayed by the server and lands on the + /// death map at the tile it died on; players cannot read the map. + @Test + void deathsLandOnTheMap() throws Exception { + String who = Api.player(accounts, "faller"); + Map ticket = Api.ticket(mvc, who, "1-1"); + StringBuilder log = new StringBuilder(); + com.codename1.gaming.platformer.InputLog in = new com.codename1.gaming.platformer.InputLog(); + for (int t = 0; t < 3600; t++) { + in.add(com.codename1.gaming.platformer.Input.RIGHT + | (t % 40 < 12 ? com.codename1.gaming.platformer.Input.JUMP : 0)); + } + log.append(in.encode()); + com.codename1.gaming.platformer.Replay.Result r = com.codenameone.examples.ledge.levels.Scoring.replay(0, + Api.number(ticket, "seed"), log.toString()); + assertTrue(r.getDeaths() > 0 && !r.isComplete(), "the blind run dies"); + Map before = Api.json(mvc, Api.asAdmin(get("/api/admin/heatmap/1-1"), ADMIN)); + Map refused = Api.submit(mvc, who, (String) ticket.get("token"), log.toString(), r.getTicks(), r.getHash()); + assertFalse((Boolean) refused.get("accepted")); + Map after = Api.json(mvc, Api.asAdmin(get("/api/admin/heatmap/1-1"), ADMIN)); + assertEquals(Api.number(before, "deaths") + r.getDeaths(), Api.number(after, "deaths")); + assertEquals(403, Api.statusOf(mvc, Api.as(get("/api/admin/heatmap/1-1"), who))); + assertEquals(404, Api.statusOf(mvc, Api.asAdmin(get("/api/admin/heatmap/9-9"), ADMIN))); + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/Api.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/Api.java new file mode 100644 index 00000000000..51b3a8668f3 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/Api.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.Json; +import com.codename1.backend.test.MockMvc; +import com.codename1.backend.test.MockRequestBuilder; +import com.codenameone.examples.ledge.account.Accounts; +import com.codename1.gaming.platformer.Replay; +import com.codenameone.examples.ledge.api.RegisterDto; +import com.codenameone.examples.ledge.domain.RunTicket; +import com.codenameone.examples.ledge.domain.ScoreRun; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.repository.RunTicketRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static com.codename1.backend.test.MockMvcResultMatchers.status; +import static com.codename1.backend.test.SecurityMockMvcRequestPostProcessors.jwt; + +/// The steps most tests take: making a player, calling the API as them, and +/// reading what came back. +public final class Api { + public static final String PASSWORD = "a-long-password"; + + private Api() { + } + + /// A fresh player of the test's own, so no test meets what another left. + public static String player(Accounts accounts, String name) throws Exception { + return accounts.register(new RegisterDto(name + "@test.example", PASSWORD, name)).username(); + } + + public static MockRequestBuilder as(MockRequestBuilder request, String username) { + return request.with(jwt().subject(username).authorities("ROLE_PLAYER")); + } + + public static MockRequestBuilder asAdmin(MockRequestBuilder request, String username) { + return request.with(jwt().subject(username).authorities("ROLE_PLAYER", "ROLE_ADMIN")); + } + + public static MockRequestBuilder body(MockRequestBuilder request, String json) { + return request.contentType("application/json").content(json); + } + + public static Map json(MockMvc mvc, MockRequestBuilder request) throws Exception { + return Json.parseObject(mvc.perform(request).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString()); + } + + public static List list(MockMvc mvc, MockRequestBuilder request) throws Exception { + return (List) Json.parse(mvc.perform(request).andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString()); + } + + public static int statusOf(MockMvc mvc, MockRequestBuilder request) throws Exception { + return mvc.perform(request).andReturn().getResponse().getStatus(); + } + + public static long number(Map object, String field) { + return ((Number) object.get(field)).longValue(); + } + + /// A ticket for `level` (a level id or `daily`), as the app asks before a run. + public static Map ticket(MockMvc mvc, String who, String level) throws Exception { + return json(mvc, as(body(post("/api/runs/start"), "{\"level\":\"" + level + "\"}"), who)); + } + + /// A ticket for `level` whose seed is pinned to 1, the seed the shipped + /// solver inputs finish every level on. Returns the token. + public static String pinnedTicket(MockMvc mvc, RunTicketRepository tickets, String who, String level) + throws Exception { + String token = (String) ticket(mvc, who, level).get("token"); + RunTicket t = tickets.findById(token); + t.setSeed(1); + tickets.save(t); + return token; + } + + /// Submits `log` against `token` claiming `ticks` and `hash`, after + /// letting as much wall-clock time pass as the run lasts. + public static Map submit(MockMvc mvc, String who, String token, String log, int ticks, long hash) + throws Exception { + Clock.shiftForTests((ticks / Scoring.TICKS_PER_SECOND + 1) * 1000L); + try { + return json(mvc, as(body(post("/api/runs"), run(token, log, ticks, hash)), who)); + } finally { + Clock.shiftForTests(0); + } + } + + /// Plays level `index` honestly: the shipped solver input on seed 1. + public static Map play(MockMvc mvc, RunTicketRepository tickets, String who, int index) throws Exception { + String token = pinnedTicket(mvc, tickets, who, LevelPack.IDS[index]); + Replay.Result r = demo(index); + return submit(mvc, who, token, LevelPack.demo(index), r.getTicks(), r.getHash()); + } + + /// What the solver input of level `index` replays to on seed 1. + public static Replay.Result demo(int index) { + return Scoring.replay(index, 1, LevelPack.demo(index)); + } + + /// A stored run with any score, for tests of the boards rather than of + /// verification. + public static ScoreRun stored(ScoreRunRepository runs, String who, String level, long score, int ticks, + long when) throws Exception { + ScoreRun r = new ScoreRun(); + r.setId(Ids.next()); + r.setUsername(who); + r.setLevel(level); + r.setScore(score); + r.setTicks(ticks); + r.setStars(1); + r.setSeed(1); + r.setLog(""); + r.setDay(Clock.dayOf(when)); + r.setCreatedAt(Instant.ofEpochMilli(when)); + runs.insert(r); + return r; + } + + public static String run(String token, String log, int ticks, long hash) { + return "{\"token\":\"" + token + "\",\"log\":\"" + log + "\",\"ticks\":" + ticks + + ",\"hash\":" + hash + "}"; + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/BoardTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/BoardTest.java new file mode 100644 index 00000000000..906ca9bc683 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/BoardTest.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.ledge.account.Accounts; +import com.codename1.gaming.platformer.Replay; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.repository.RunTicketRepository; +import com.codenameone.examples.ledge.repository.ScoreRunRepository; +import com.codenameone.examples.ledge.run.DailySeeds; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// The per-level leaderboards' periods, the friends board and the daily. +@BackendTest +class BoardTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + @Autowired + private ScoreRunRepository runs; + @Autowired + private RunTicketRepository tickets; + + @Test + void aBoardKeepsEachPlayersBestOfTheLevelWithinItsPeriod() throws Exception { + String now = Api.player(accounts, "nowplayer"); + String old = Api.player(accounts, "oldtimer"); + long t = System.currentTimeMillis(); + Api.stored(runs, now, "5-1", 8000000, 3000, t); + Api.stored(runs, now, "5-1", 7000000, 3100, t); + Api.stored(runs, old, "5-1", 8100000, 2900, t - 20 * Clock.DAY); + // Another level's run is on another board. + Api.stored(runs, old, "4-2", 9900000, 2900, t); + List all = Api.list(mvc, Api.as(get("/api/leaderboard?level=5-1&period=ALL"), now)); + assertTrue(all.size() <= 50); + Map first = (Map) all.get(0); + Map second = (Map) all.get(1); + assertEquals(old, first.get("username")); + assertEquals(2900L, Api.number(first, "ticks")); + assertEquals("scarf-ember", first.get("scarf")); + assertEquals(now, second.get("username")); + assertEquals(8000000L, Api.number(second, "score")); + assertTrue((Boolean) second.get("me")); + assertEquals(2L, Api.number(second, "rank")); + assertEquals(1, count(all, now)); + for (String period : new String[] {"WEEK", "TODAY"}) { + List windowed = Api.list(mvc, Api.as(get("/api/leaderboard?level=5-1&period=" + period), now)); + assertEquals(now, ((Map) windowed.get(0)).get("username")); + assertEquals(0, count(windowed, old)); + } + assertEquals(old, ((Map) Api.list(mvc, Api.as(get("/api/leaderboard?level=4-2&period=TODAY"), now)) + .get(0)).get("username")); + assertEquals(400, Api.statusOf(mvc, Api.as(get("/api/leaderboard?level=9-9&period=ALL"), now))); + } + + @Test + void theFriendsBoardIsTheAskerAndTheirFriends() throws Exception { + String me = Api.player(accounts, "befriender"); + String pal = Api.player(accounts, "palfriend"); + Api.play(mvc, tickets, me, 0); + long t = System.currentTimeMillis(); + Api.stored(runs, me, "3-3", 5000, 4000, t); + Api.stored(runs, pal, "3-3", 6000, 4000, t); + List friends = Api.list(mvc, Api.as(Api.body(post("/api/friends"), "{\"name\":\"palfriend\"}"), me)); + assertEquals(1, friends.size()); + assertEquals(0L, Api.number((Map) friends.get(0), "stars")); + assertEquals(400, Api.statusOf(mvc, Api.as(Api.body(post("/api/friends"), + "{\"name\":\"" + me + "\"}"), me))); + assertEquals(404, Api.statusOf(mvc, Api.as(Api.body(post("/api/friends"), + "{\"name\":\"nobody at all\"}"), me))); + List board = Api.list(mvc, Api.as(get("/api/leaderboard?level=3-3&period=FRIENDS"), me)); + assertEquals(2, board.size()); + assertEquals(pal, ((Map) board.get(0)).get("username")); + assertTrue((Boolean) ((Map) board.get(1)).get("me")); + // A friend may race my ghost. + Api.list(mvc, Api.as(Api.body(post("/api/friends"), "{\"name\":\"" + me + "\"}"), pal)); + Map ghost = Api.json(mvc, Api.as(get("/api/ghost?level=1-1&username=" + me), pal)); + assertEquals(me, ghost.get("username")); + Api.list(mvc, Api.as(Api.body(post("/api/friends/remove"), "{\"name\":\"" + pal + "\"}"), me)); + assertEquals(1, Api.list(mvc, Api.as(get("/api/leaderboard?level=3-3&period=FRIENDS"), me)).size()); + } + + @Test + void theDailyIsStableWithinADayAndAnAdminCanPickItsSeed() throws Exception { + assertEquals("1970-01-01", Clock.date(0)); + assertEquals("2026-11-20", Clock.date(1795132800000L + 3600000L)); + assertEquals(DailySeeds.hashed("2026-11-20"), DailySeeds.hashed("2026-11-20")); + assertTrue(DailySeeds.hashed("2026-11-20") != DailySeeds.hashed("2026-11-21")); + String who = Api.player(accounts, "dailyplayer"); + Map daily = Api.json(mvc, Api.as(get("/api/daily"), who)); + long seed = Api.number(daily, "seed"); + String level = (String) daily.get("level"); + assertEquals(LevelPack.IDS[Scoring.dailyLevel(Clock.dayOf(Clock.now()) / Clock.DAY)], level); + Map ticket = Api.ticket(mvc, who, "daily"); + assertEquals(seed, Api.number(ticket, "seed")); + assertEquals(level, ticket.get("level")); + assertTrue((Boolean) ticket.get("daily")); + Map picked = Api.json(mvc, Api.asAdmin(Api.body(post("/api/admin/daily"), "{\"seed\":1}"), + "admin@ledge.example")); + assertEquals(1L, Api.number(picked, "seed")); + String token = (String) Api.ticket(mvc, who, "daily").get("token"); + int index = LevelPack.indexOf(level); + Replay.Result r = Api.demo(index); + Map result = Api.submit(mvc, who, token, LevelPack.demo(index), r.getTicks(), r.getHash()); + assertTrue((Boolean) result.get("accepted"), (String) result.get("message")); + assertEquals(Math.min(100, r.getCoins()) + 5L, Api.number(result, "coinsEarned")); + Map after = Api.json(mvc, Api.as(get("/api/daily"), who)); + assertEquals(Scoring.points(index, r), Api.number(after, "myBest")); + assertTrue(Api.number(after, "players") >= 1); + assertEquals(Scoring.points(index, r), Api.number(Api.json(mvc, Api.as(get("/api/me"), who)), + "bestDaily")); + } + + private static int count(List board, String username) { + int n = 0; + for (Object row : board) { + if (username.equals(((Map) row).get("username"))) { + n++; + } + } + return n; + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/LevelAiTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/LevelAiTest.java new file mode 100644 index 00000000000..aff2821feb2 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/LevelAiTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.ledge.account.Accounts; +import java.util.Map; +import com.codenameone.examples.ledge.ai.LevelAi; +import com.codenameone.examples.ledge.api.GeneratedDto; +import com.codenameone.examples.ledge.levels.LevelGenerator; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Levels on request: with no model configured the generator answers, and +/// whatever comes back has been finished by the solver. +@BackendTest +class LevelAiTest { + @Autowired + private LevelAi ai; + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + + /// The route the editor's Ask AI button calls: a player gets a level, a + /// stranger gets nothing, and a description past the limit is refused. + @Test + void theRouteAnswersPlayersOnly() throws Exception { + String who = Api.player(accounts, "designer"); + Map level = Api.json(mvc, Api.as(Api.body(post("/api/levels/generate"), + "{\"prompt\":\"a short meadow\",\"seed\":3}"), who)); + assertNotNull(LevelGenerator.check((String) level.get("sketch"), 20_000_000L)); + assertEquals(401, Api.statusOf(mvc, Api.body(post("/api/levels/generate"), + "{\"prompt\":\"a short meadow\",\"seed\":3}"))); + StringBuilder longWords = new StringBuilder(); + for (int i = 0; i < 40; i++) { + longWords.append("spikes and "); + } + assertEquals(400, Api.statusOf(mvc, Api.as(Api.body(post("/api/levels/generate"), + "{\"prompt\":\"" + longWords + "\",\"seed\":3}"), who))); + } + + @Test + void everyAnswerCanBeFinished() { + String[] asks = {"", "a long cave full of spikes", "SKY WITH JUMPS", "enemies in a factory"}; + for (int i = 0; i < asks.length; i++) { + GeneratedDto level = ai.generate(asks[i], i); + assertEquals("pieces", level.source()); + assertNotNull(LevelGenerator.check(level.sketch(), 20_000_000L), asks[i]); + } + } + + @Test + void theWordsPickTheWorld() { + assertTrue(ai.generate("a dark crystal cave", 1).sketch().contains("\"cavern\"")); + assertTrue(ai.generate("A LAVA FORGE", 1).sketch().contains("\"forge\"")); + } + + @Test + void aModelReplyLosesItsFence() { + assertEquals("{\"a\":1}\n---\n...\n", + LevelAi.sketchOf("Here you go:\n```\n{\"a\":1}\n---\n...\n```")); + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/LevelsTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/LevelsTest.java new file mode 100644 index 00000000000..8b32ff8c759 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/LevelsTest.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.LevelData; +import com.codename1.gaming.platformer.Replay; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.LevelSketch; +import com.codenameone.examples.ledge.levels.Solver; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Every shipped level can be finished, by its own recorded run on any seed +/// and by the solver from nothing, and its sketch is still the level that +/// ships. +class LevelsTest { + private static final long[] SEEDS = {1, 2, 77, 123456789}; + + @Test + void everyDemoFinishesOnEverySeed() { + for (int i = 0; i < LevelPack.IDS.length; i++) { + InputLog log = InputLog.decode(LevelPack.demo(i), 1 << 20); + for (long seed : SEEDS) { + Replay.Result r = Replay.run(LevelPack.load(i), seed, log); + assertTrue(r.isComplete(), LevelPack.IDS[i] + " on seed " + seed); + } + } + } + + @Test + void theSolverFinishesEveryLevel() { + for (int i = 0; i < LevelPack.IDS.length; i++) { + LevelData level = LevelPack.load(i); + InputLog log = new Solver(level, 7, 1).solve(40_000_000L); + assertNotNull(log, LevelPack.IDS[i] + " found no route"); + assertTrue(Replay.run(level, 7, log).isComplete(), LevelPack.IDS[i]); + } + } + + @Test + void sketchesCompileToTheShippedLevels() throws Exception { + Path src = Paths.get("..", "levels", "src"); + for (int i = 0; i < LevelPack.IDS.length; i++) { + String sketch = new String(Files.readAllBytes(src.resolve(LevelPack.IDS[i] + ".sketch")), + StandardCharsets.UTF_8); + InputLog log = InputLog.decode(LevelPack.demo(i), 1 << 20); + Replay.Result mine = Replay.run(LevelData.parse(LevelSketch.compile(sketch)), 5, log); + Replay.Result shipped = Replay.run(LevelPack.load(i), 5, log); + assertEquals(shipped.getHash(), mine.getHash(), LevelPack.IDS[i]); + } + } + + /// Records the demo of a new or changed level: `-Dledge.record=2-4` (or a + /// comma separated list) has the solver find a route through + /// `levels/2-4.json` and writes it to `levels/demo/2-4.log`, after checking + /// it finishes on every seed. `tools/pack-levels.py` then packs it. Does + /// nothing unless asked. + @Test + void recordsADemoWhenAsked() throws Exception { + String ids = System.getProperty("ledge.record", ""); + for (String id : ids.split(",")) { + id = id.trim(); + if (id.isEmpty()) { + continue; + } + if (!id.matches("[0-9A-Za-z_-]{1,16}")) { + throw new IllegalArgumentException("A level id is letters, digits, - and _: " + id); + } + Path levels = Paths.get("..", "levels"); + LevelData level = LevelData.parse(new String(Files.readAllBytes(levels.resolve(id + ".json")), + StandardCharsets.UTF_8)); + InputLog log = new Solver(level, 7, 1).solve(200_000_000L); + assertNotNull(log, id + ": the solver found no route; make the level easier or check its exit"); + for (long seed : SEEDS) { + assertTrue(Replay.run(level, seed, log).isComplete(), id + " finishes on seed " + seed); + } + Files.write(levels.resolve("demo").resolve(id + ".log"), log.encode().getBytes(StandardCharsets.UTF_8)); + } + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/ProgressTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/ProgressTest.java new file mode 100644 index 00000000000..bca921beefa --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/ProgressTest.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.ledge.account.Accounts; +import com.codenameone.examples.ledge.repository.RunTicketRepository; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Achievements, worked out from replayed runs and level progress. +@BackendTest +class ProgressTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + @Autowired + private RunTicketRepository tickets; + + @Test + void achievementsFollowTheRunsAPlayerHasHad() throws Exception { + String who = Api.player(accounts, "achiever"); + Map before = byId(Api.list(mvc, Api.as(get("/api/achievements"), who))); + assertFalse((Boolean) ((Map) before.get("first-clear")).get("unlocked")); + assertEquals(0L, Api.number((Map) before.get("clear-10"), "progress")); + Api.play(mvc, tickets, who, 0); + Api.play(mvc, tickets, who, 1); + Map after = byId(Api.list(mvc, Api.as(get("/api/achievements"), who))); + assertTrue((Boolean) ((Map) after.get("first-clear")).get("unlocked")); + Map climber = (Map) after.get("clear-10"); + assertFalse((Boolean) climber.get("unlocked")); + assertEquals(2L, Api.number(climber, "progress")); + assertEquals(10L, Api.number(climber, "goal")); + assertEquals(12L, Api.number((Map) after.get("world-1-3star"), "goal")); + assertEquals(0L, Api.number((Map) after.get("daily-1"), "progress")); + } + + private static Map byId(List achievements) { + Map out = new java.util.HashMap(); + for (Object a : achievements) { + out.put(((Map) a).get("id"), a); + } + return out; + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/RunTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/RunTest.java new file mode 100644 index 00000000000..cd4fe173671 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/RunTest.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codename1.gaming.platformer.Replay; +import com.codenameone.examples.ledge.account.Accounts; +import com.codenameone.examples.ledge.domain.RunTicket; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.repository.RunTicketRepository; +import java.time.Instant; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// A run is credited with what the server's own replay of it produced, and +/// only when that replay agrees with what the client claimed. +@BackendTest +class RunTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + @Autowired + private RunTicketRepository tickets; + + @Test + void anHonestRunIsReplayedScoredAndPaid() throws Exception { + String who = Api.player(accounts, "runner"); + Replay.Result r = Api.demo(0); + assertTrue(r.isComplete()); + Map result = Api.play(mvc, tickets, who, 0); + assertTrue((Boolean) result.get("accepted"), (String) result.get("message")); + assertFalse((Boolean) result.get("flagged")); + assertTrue((Boolean) result.get("newBest")); + assertEquals(Scoring.points(0, r), Api.number(result, "score")); + assertEquals((long) r.getTicks(), Api.number(result, "ticks")); + int stars = Scoring.stars(0, r); + assertEquals((long) stars, Api.number(result, "stars")); + long coins = Math.min(100, r.getCoins()); + assertEquals(coins, Api.number(result, "coinsEarned")); + assertTrue(Api.number(result, "rank") > 0); + Map me = Api.json(mvc, Api.as(get("/api/me"), who)); + String progress = (String) me.get("progress"); + assertEquals(LevelPack.IDS.length, progress.length()); + assertEquals((char) ('0' + stars), progress.charAt(0)); + assertEquals(1L, Api.number(me, "runs")); + assertEquals(Accounts.START_COINS + coins, Api.number(me, "coins")); + // The stored run is a ghost anybody signed in can race. + Map ghost = Api.json(mvc, Api.as(get("/api/ghost?level=1-1&username=" + who), who)); + assertEquals(LevelPack.demo(0), ghost.get("log")); + assertEquals(1L, Api.number(ghost, "seed")); + String stranger = Api.player(accounts, "stranger"); + // A board run is public: a stranger races it too. + assertEquals(LevelPack.demo(0), Api.json(mvc, + Api.as(get("/api/ghost?level=1-1&username=" + who), stranger)).get("log")); + Api.json(mvc, Api.as(get("/api/ghost?level=1-1"), stranger)); + assertEquals(404, Api.statusOf(mvc, Api.as(get("/api/ghost?level=1-1&username=" + stranger), + stranger))); + } + + @Test + void aTamperedLogIsRefused() throws Exception { + String who = Api.player(accounts, "tamperer"); + Replay.Result r = Api.demo(0); + String log = LevelPack.demo(0); + // The first steps held a few ticks longer: the claimed result no longer follows. + String tampered = "8*40" + log.substring(log.indexOf(',')); + Map refused = Api.submit(mvc, who, Api.pinnedTicket(mvc, tickets, who, "1-1"), tampered, + r.getTicks(), r.getHash()); + assertFalse((Boolean) refused.get("accepted")); + assertTrue(((String) refused.get("message")).length() > 0); + Map garbage = Api.submit(mvc, who, Api.pinnedTicket(mvc, tickets, who, "1-1"), "not a log", + r.getTicks(), r.getHash()); + assertFalse((Boolean) garbage.get("accepted")); + assertEquals(0L, Api.number(Api.json(mvc, Api.as(get("/api/me"), who)), "runs")); + } + + @Test + void aWrongHashIsRefused() throws Exception { + String who = Api.player(accounts, "hasher"); + Replay.Result r = Api.demo(0); + Map refused = Api.submit(mvc, who, Api.pinnedTicket(mvc, tickets, who, "1-1"), LevelPack.demo(0), + r.getTicks(), r.getHash() + 1); + assertFalse((Boolean) refused.get("accepted")); + assertEquals(0L, Api.number(refused, "score")); + assertEquals(0L, Api.number(Api.json(mvc, Api.as(get("/api/me"), who)), "runs")); + } + + @Test + void anUnfinishedRunIsRefused() throws Exception { + String who = Api.player(accounts, "quitter"); + String log = LevelPack.demo(0); + int cut = 0; + for (int i = 0; i < 10; i++) { + cut = log.indexOf(',', cut + 1); + } + String part = log.substring(0, cut); + Replay.Result r = Scoring.replay(0, 1, part); + assertFalse(r.isComplete()); + Map refused = Api.submit(mvc, who, Api.pinnedTicket(mvc, tickets, who, "1-1"), part, r.getTicks(), + r.getHash()); + assertFalse((Boolean) refused.get("accepted")); + assertTrue(((String) refused.get("message")).contains("exit")); + } + + @Test + void aRunCannotBeLongerThanItsTicketIsOld() throws Exception { + String who = Api.player(accounts, "hasty"); + Replay.Result r = Api.demo(0); + String token = Api.pinnedTicket(mvc, tickets, who, "1-1"); + Map early = Api.json(mvc, Api.as(Api.body(post("/api/runs"), + Api.run(token, LevelPack.demo(0), r.getTicks(), r.getHash())), who)); + assertFalse((Boolean) early.get("accepted")); + assertEquals(0L, Api.number(Api.json(mvc, Api.as(get("/api/me"), who)), "runs")); + } + + @Test + void aTicketIsGoodOnceForItsOwnerAndUntilItExpires() throws Exception { + String who = Api.player(accounts, "ticketed"); + Replay.Result r = Api.demo(0); + String token = Api.pinnedTicket(mvc, tickets, who, "1-1"); + assertTrue((Boolean) Api.submit(mvc, who, token, LevelPack.demo(0), r.getTicks(), r.getHash()) + .get("accepted")); + assertEquals(409, Api.statusOf(mvc, Api.as(Api.body(post("/api/runs"), + Api.run(token, LevelPack.demo(0), r.getTicks(), r.getHash())), who))); + assertEquals(404, Api.statusOf(mvc, Api.as(Api.body(post("/api/runs"), + Api.run("no-such-ticket", LevelPack.demo(0), r.getTicks(), r.getHash())), who))); + // Somebody else's ticket is as good as none. + String other = Api.player(accounts, "borrower"); + String theirs = Api.pinnedTicket(mvc, tickets, other, "1-1"); + assertEquals(404, Api.statusOf(mvc, Api.as(Api.body(post("/api/runs"), + Api.run(theirs, LevelPack.demo(0), r.getTicks(), r.getHash())), who))); + String stale = Api.pinnedTicket(mvc, tickets, who, "1-1"); + RunTicket t = tickets.findById(stale); + t.setExpiresAt(Instant.ofEpochMilli(System.currentTimeMillis() - 1000)); + tickets.save(t); + assertEquals(410, Api.statusOf(mvc, Api.as(Api.body(post("/api/runs"), + Api.run(stale, LevelPack.demo(0), r.getTicks(), r.getHash())), who))); + assertEquals(400, Api.statusOf(mvc, Api.as(Api.body(post("/api/runs/start"), + "{\"level\":\"9-9\"}"), who))); + } +} diff --git a/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/ShopTest.java b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/ShopTest.java new file mode 100644 index 00000000000..3af1897c734 --- /dev/null +++ b/scripts/ledge/backend/src/test/java/com/codenameone/examples/ledge/ShopTest.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.backend.annotations.Autowired; +import com.codename1.backend.test.BackendTest; +import com.codename1.backend.test.MockMvc; +import com.codenameone.examples.ledge.account.Accounts; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static com.codename1.backend.test.MockMvcRequestBuilders.get; +import static com.codename1.backend.test.MockMvcRequestBuilders.post; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/// Spending coins, store receipts and rewarded ads. The test profile +/// checks receipts with the simulated store, which accepts any of them. +@BackendTest +class ShopTest { + @Autowired + private MockMvc mvc; + @Autowired + private Accounts accounts; + + @Test + void scarvesAreBoughtOnceAndEquippedOnlyWhenOwned() throws Exception { + String who = Api.player(accounts, "shopper"); + List items = Api.list(mvc, Api.as(get("/api/shop"), who)); + assertEquals(9, items.size()); + assertEquals(402, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/buy"), + "{\"itemId\":\"scarf-teal\"}"), who))); + // Coin packs and ad-free cost real money and are never sold for coins. + assertEquals(404, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/buy"), + "{\"itemId\":\"coins-small\"}"), who))); + assertEquals(404, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/buy"), + "{\"itemId\":\"adfree\"}"), who))); + assertEquals(403, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/equip"), + "{\"scarf\":\"scarf-teal\"}"), who))); + Api.json(mvc, Api.as(Api.body(post("/api/shop/receipt"), "{\"store\":\"play\",\"sku\":" + + "\"ledge.coins.small\",\"transactionId\":\"tx-shopper\",\"receipt\":\"r\"}"), who)); + Map wallet = Api.json(mvc, Api.as(Api.body(post("/api/shop/buy"), "{\"itemId\":\"scarf-teal\"}"), who)); + assertEquals(Accounts.START_COINS + 500L - 150, Api.number(wallet, "coins")); + assertTrue(((List) wallet.get("owned")).contains("scarf-teal")); + assertEquals("scarf-ember", wallet.get("scarf")); + assertEquals(409, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/buy"), + "{\"itemId\":\"scarf-teal\"}"), who))); + Map equipped = Api.json(mvc, Api.as(Api.body(post("/api/shop/equip"), "{\"scarf\":\"scarf-teal\"}"), who)); + assertEquals("scarf-teal", equipped.get("scarf")); + } + + @Test + void adFreeIsOwnedOnceBought() throws Exception { + String who = Api.player(accounts, "adhater"); + Map wallet = Api.json(mvc, Api.as(Api.body(post("/api/shop/receipt"), "{\"store\":\"play\",\"sku\":" + + "\"ledge.adfree\",\"transactionId\":\"tx-adfree\",\"receipt\":\"r\"}"), who)); + assertTrue(((List) wallet.get("owned")).contains("adfree")); + assertEquals((long) Accounts.START_COINS, Api.number(wallet, "coins")); + // It is not a scarf to wear. + assertEquals(403, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/equip"), + "{\"scarf\":\"adfree\"}"), who))); + } + + @Test + void aReceiptIsRedeemedOnceAndOnlyByItsOwner() throws Exception { + String who = Api.player(accounts, "buyer"); + String thief = Api.player(accounts, "thief"); + String receipt = "{\"store\":\"itunes\",\"sku\":\"ledge.coins.large\"," + + "\"transactionId\":\"tx-1001\",\"receipt\":\"opaque\"}"; + Map first = Api.json(mvc, Api.as(Api.body(post("/api/shop/receipt"), receipt), who)); + assertEquals(Accounts.START_COINS + 3000L, Api.number(first, "coins")); + // The app retries after a lost answer: the same purchase, granted once. + Map again = Api.json(mvc, Api.as(Api.body(post("/api/shop/receipt"), receipt), who)); + assertEquals(Accounts.START_COINS + 3000L, Api.number(again, "coins")); + assertEquals(409, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/receipt"), receipt), thief))); + assertEquals(404, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/receipt"), + "{\"store\":\"itunes\",\"sku\":\"ledge.coins.huge\",\"transactionId\":\"tx-2\"," + + "\"receipt\":\"r\"}"), who))); + } + + @Test + void anAdNoncePaysOnce() throws Exception { + String who = Api.player(accounts, "watcher"); + Map paid = Api.json(mvc, Api.as(Api.body(post("/api/shop/ad-reward"), "{\"nonce\":\"ad-77\"}"), who)); + assertEquals(Accounts.START_COINS + 15L, Api.number(paid, "coins")); + assertEquals(409, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/ad-reward"), + "{\"nonce\":\"ad-77\"}"), who))); + assertFalse(Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/ad-reward"), "{}"), who)) == 200); + // A client mints its own nonces, so the day's count is what bounds it. + for (int i = 1; i < com.codenameone.examples.ledge.shop.Shop.AD_REWARDS_PER_DAY; i++) { + assertEquals(200, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/ad-reward"), + "{\"nonce\":\"cap-" + i + "\"}"), who))); + } + assertEquals(429, Api.statusOf(mvc, Api.as(Api.body(post("/api/shop/ad-reward"), + "{\"nonce\":\"cap-over\"}"), who))); + } +} diff --git a/scripts/ledge/check-template.sh b/scripts/ledge/check-template.sh new file mode 100755 index 00000000000..e6db47c32bf --- /dev/null +++ b/scripts/ledge/check-template.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# +# Builds what the Initializr generates from this project. +# +# check-template.sh [work-directory] +# +# The Initializr offers this application as a template, from resources that +# scripts/sync-initializr-template.py derives from it. That the resources match +# is one question; this is the other: whether a project generated from them, +# under another name and in another package, still builds. The real generator +# makes the project, and it is then built against this checkout: +# +# the server's tests pass against the contract module +# the app builds from common, without platform modules and with them, and +# the client half of the contract is generated into it +# +# Needs this checkout's artifacts installed (core, javase, css-compiler, the +# Maven plugin, backend, backend-test), a JDK 17 or newer as JAVA_HOME, python3 +# and unzip. +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/../.." && pwd)" +MVN="${MVN:-mvn}" +WORK="${1:-$HERE/target/template-check}" + +log() { echo "[ledge-template] $*" >&2; } + +python3 "$ROOT/scripts/sync-initializr-template.py" ledge +# LevelPack.java is generated from levels/*.json and levels/demo/*.log; a level +# edited without re-packing would ship the old one. +python3 "$HERE/tools/pack-levels.py" --check + +# The version this checkout installs, which the generated poms are pointed at: +# the release the Initializr generates against does not have this project's +# build support until one that follows this change. +VERSION="$(sed -n 's:.*\(.*\).*:\1:p' "$ROOT/maven/pom.xml" | head -n 1)" +[ -n "$VERSION" ] || { log "could not read the version from maven/pom.xml"; exit 1; } + +rm -rf "$WORK" +mkdir -p "$WORK" +log "generating the Initializr's downloads" +python3 "$ROOT/scripts/tests/generate-initializr-fixtures.py" "$WORK/fixtures" > "$WORK/fixtures.log" 2>&1 \ + || { tail -n 60 "$WORK/fixtures.log" >&2; log "the generator failed"; exit 1; } + +# extract -- a generated project, pointed at this checkout's version +extract() { + local dir="$WORK/$1" + mkdir -p "$dir" + unzip -q "$WORK/fixtures/LEDGE-$1-INTELLIJ.zip" -d "$dir" + python3 - "$dir/pom.xml" "$VERSION" <<'PY' +import re, sys +path, version = sys.argv[1], sys.argv[2] +text = open(path, encoding='utf-8').read() +for tag in ('cn1.plugin.version', 'cn1.version'): + text, count = re.subn(r'<%s>[^<]*' % (tag, tag), '<%s>%s' % (tag, version, tag), text) + assert count == 1, (tag, count) +open(path, 'w', encoding='utf-8').write(text) +PY + echo "$dir" +} + +# The fixtures are generated as com.example.probe.LauncherProbe. +PACKAGE=com/example/probe + +minimal="$(extract APP_WITH_BACKEND)" +log "running the generated server's tests" +(cd "$minimal" && "$MVN" -B -q -Dcodename1.platform=backend -pl shared,backend -am test) +ls "$minimal"/backend/target/surefire-reports/TEST-*.xml >/dev/null 2>&1 \ + || { log "the generated server's tests did not run"; exit 1; } +[ -f "$minimal/backend/target/generated-sources/cn1-annotations/$PACKAGE/api/AccountApiServer.java" ] \ + || { log "the server's half of the contract was not generated"; exit 1; } + +for layout in APP_WITH_BACKEND FULL; do + project="$WORK/$layout" + [ -d "$project" ] || project="$(extract "$layout")" + log "building the generated app ($layout)" + (cd "$project" && "$MVN" -B -q -Dcodename1.platform=javase -Djava.awt.headless=true -DskipTests package) + for built in "classes/theme.res" "classes/$PACKAGE/api/AccountApiImpl.class" "classes/cn1app/RestClientBootstrap.class"; do + [ -f "$project/common/target/$built" ] \ + || { log "$layout: common/target/$built was not built"; exit 1; } + done +done +log "passed" diff --git a/scripts/ledge/common/codenameone_settings.properties b/scripts/ledge/common/codenameone_settings.properties new file mode 100644 index 00000000000..b3f3435d919 --- /dev/null +++ b/scripts/ledge/common/codenameone_settings.properties @@ -0,0 +1,51 @@ +codename1.android.keystore= +codename1.android.keystoreAlias= +codename1.android.keystorePassword= +codename1.arg.and.themeMode=modern +# A server started on this machine is reached over plain HTTP, which Android +# refuses by default. Remove this once the game talks to a server with a +# certificate. +codename1.arg.android.xapplication_attr=android\:usesCleartextTraffic\="true" +# A game keeps its own title and back arrow on the desktop; "native" would +# hide the Toolbar and move Back into the OS menu bar. +codename1.arg.desktop.titleBar=toolbar +codename1.arg.ios.newStorageLocation=true +# Push notifications: the daily sheet, a beaten score, flags for an admin. +codename1.arg.ios.includePush=true +# ledge://daily opens today's sheet. +codename1.arg.ios.urlScheme=ledge +codename1.arg.android.xintent_filter= +# Android push is off until the game has its Firebase file: a build that +# uses PushClient without google-services.json stops with an error. Once +# native/android/google-services.json is in place, delete this line. +codename1.arg.android.messagingService=none +# The shop sells through Google Play, and an Android build that uses in-app +# purchase needs the app's licensing key. This is a placeholder that builds +# but verifies nothing: paste the Base64 RSA public key from the Play +# Console's "Monetization setup" before release. +codename1.arg.android.licenseKey=CN1TESTPLACEHOLDERKEYNOTFORPRODUCTIONxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxIDAQAB +# A twin-stick arena is played in landscape, a thumb on each side. +codename1.arg.android.xactivity=android:screenOrientation="sensorLandscape" +codename1.arg.ios.interface_orientation=UIInterfaceOrientationLandscapeLeft:UIInterfaceOrientationLandscapeRight +codename1.arg.ios.themeMode=modern +codename1.arg.java.version=17 +codename1.cssTheme=true +codename1.displayName=Ledge +codename1.icon=icon.png +codename1.ios.appid=Q5GHSKAL2F.com.codenameone.examples.ledge +codename1.ios.certificate= +codename1.ios.certificatePassword= +codename1.ios.debug.certificate= +codename1.ios.debug.certificatePassword= +codename1.ios.debug.provision= +codename1.ios.provision= +codename1.ios.release.certificate= +codename1.ios.release.certificatePassword= +codename1.ios.release.provision= +codename1.kotlin=false +codename1.languageLevel=5 +codename1.mainName=Ledge +codename1.packageName=com.codenameone.examples.ledge +codename1.secondaryTitle=Ledge +codename1.vendor=CodenameOne +codename1.version=1.0 diff --git a/scripts/ledge/common/icon.png b/scripts/ledge/common/icon.png new file mode 100644 index 00000000000..b75ded9e06e Binary files /dev/null and b/scripts/ledge/common/icon.png differ diff --git a/scripts/ledge/common/pom.xml b/scripts/ledge/common/pom.xml new file mode 100644 index 00000000000..5af046b29f1 --- /dev/null +++ b/scripts/ledge/common/pom.xml @@ -0,0 +1,1383 @@ + + + 4.0.0 + + com.codenameone.examples.ledge + ledge + 1.0-SNAPSHOT + + com.codenameone.examples.ledge + ledge-common + 1.0-SNAPSHOT + jar + + + + + com.codenameone + codenameone-core + provided + + + + com.codenameone + cn1-app-kit-lib + ${cn1.version} + pom + + + + ${project.groupId} + ledge-shared + ${project.version} + + + + + com.codenameone + codenameone-javase + test + + + org.junit.jupiter + junit-jupiter + 5.9.3 + test + + + + + + + + + + + install-codenameone + ${user.home}/.codenameone/guibuilder.jar + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + validate + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + android-compat + + + ${basedir}/src/main/android + + + + + com.codenameone + codenameone-android-compat + provided + + + + + + kotlin + + + + ${basedir}/src/main/kotlin + + + + 2.2.10 + true + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + + + + org.jetbrains + annotations + 13.0 + + + com.codenameone + java-runtime + provided + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + + process-resources + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + ${project.basedir}/src/main/android/kotlin + ${project.basedir}/src/main/android/java + ${project.build.directory}/generated-sources/android + + + -no-reflect + -no-jdk + + + + + test-compile + process-test-sources + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + + -no-reflect + -no-jdk + + + + + + + + + + + + + javase + + + codename1.platform + javase + + + + javase + + + + + org.codehaus.mojo + exec-maven-plugin + + java + true + + -Xmx1024M + + -classpath + + ${exec.mainClass} + ${cn1.mainClass} + + + + + + + + + + cn1-javase-natives + + + ${basedir}/../javase/pom.xml + + + + + + com.codenameone + codenameone-maven-plugin + + + compile-javase-natives + process-classes + + compile-javase-natives + + + javase + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + + org.apache.maven.surefire + surefire-junit-platform + 3.0.0-M5 + + + + ${skipTests} + + ${project.build.directory}/cn1-javase/classes + + + + + + + + + cn1-host-javase + + + codename1.platform + javase + + + ${basedir}/../javase/pom.xml + + + + javase + javase + none + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-javase + validate + + hosted-platform + + + javase + + + + build-javase + package + + build + + + javase + + + + + + + + + + cn1-host-android + + + codename1.platform + android + + + ${basedir}/../android/pom.xml + + + + android + android + android-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-android + validate + + hosted-platform + + + android + + + + build-android + package + + build + + + android + + + + + + + + + + cn1-host-ios + + + codename1.platform + ios + + + ${basedir}/../ios/pom.xml + + + + ios + ios + ios-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-ios + validate + + hosted-platform + + + ios + + + + build-ios + package + + build + + + ios + + + + + + + + + + cn1-host-javascript + + + codename1.platform + javascript + + + ${basedir}/../javascript/pom.xml + + + + javascript + javascript + local-javascript + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-javascript + validate + + hosted-platform + + + javascript + + + + build-javascript + package + + build + + + javascript + + + + + + + + + + cn1-host-win + + + codename1.platform + win + + + ${basedir}/../win/pom.xml + + + + win + win + windows-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-win + validate + + hosted-platform + + + win + + + + build-windows + package + + build + + + win + + + + + + + + + + cn1-host-linux + + + codename1.platform + linux + + + ${basedir}/../linux/pom.xml + + + + linux + linux + linux-device + + + + + com.codenameone + codenameone-maven-plugin + + + hosted-linux + validate + + hosted-platform + + + linux + + + + build-linux + package + + build + + + linux + + + + + + + + + + simulator + + javase + com.codename1.impl.javase.Simulator + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator + verify + + exec + + + ${cn1.hosted.javase.skip} + ${basedir} + java + + -Xmx1024M + -Dcodename1.css.compiler.args.input=${codename1.css.compiler.args.input} + -Dcodename1.css.compiler.args.output=${codename1.css.compiler.args.output} + -Dcodename1.css.compiler.args.merge=${codename1.css.compiler.args.merge} + ${codename1.exec.args.debug} + ${codename1.exec.args.runjdwp.transport} + + @${cn1.hosted.classpathArgFile} + ${exec.mainClass} + ${codename1.mainClass} + + + + + + + + + + + idea-simulator + + com.codename1.impl.javase.Simulator + true + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator-idea + verify + + java + + + ${cn1.hosted.javase.skip} + + ${project.build.directory}/cn1-javase/classes + + + ${codename1.mainClass} + + + + codename1.css.compiler.args.input + ${codename1.css.compiler.args.input} + + + codename1.css.compiler.args.output + ${codename1.css.compiler.args.output} + + + codename1.css.compiler.args.merge + ${codename1.css.compiler.args.merge} + + + + cn1.class.path + ${cn1.class.path} + + + + + + + + + + + + debug-simulator + + com.codename1.impl.javase.Simulator + true + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator + verify + + exec + + + ${cn1.hosted.javase.skip} + ${basedir} + java + + -Xdebug + -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} + -Xmx1024M + -Dcodename1.css.compiler.args.input=${codename1.css.compiler.args.input} + -Dcodename1.css.compiler.args.output=${codename1.css.compiler.args.output} + -Dcodename1.css.compiler.args.merge=${codename1.css.compiler.args.merge} + @${cn1.hosted.classpathArgFile} + ${exec.mainClass} + ${codename1.mainClass} + + + + + + + + + + + debug-eclipse + + com.codename1.impl.javase.Simulator + true + + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + prepare-simulator-environment + initialize + + prepare-simulator-classpath + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-in-simulator + verify + + exec + + + ${cn1.hosted.javase.skip} + ${basedir} + java + + -Xdebug + -Xrunjdwp:transport=dt_socket,server=y,address=${jpda.address},suspend=y + -Xmx1024M + -Dcodename1.css.compiler.args.input=${codename1.css.compiler.args.input} + -Dcodename1.css.compiler.args.output=${codename1.css.compiler.args.output} + -Dcodename1.css.compiler.args.merge=${codename1.css.compiler.args.merge} + @${cn1.hosted.classpathArgFile} + ${exec.mainClass} + ${codename1.mainClass} + + + + + + + + + + + run-desktop + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + generate-icons + generate-sources + + generate-desktop-app-wrapper + + + javase + + + + + + org.codehaus.mojo + exec-maven-plugin + + + run-desktop + verify + + java + + + ${cn1.hosted.javase.skip} + ${codename1.packageName}.${codename1.mainName}Stub + + + ${project.build.directory}/cn1-javase/classes + ${project.build.directory}/cn1-javase/desktop + ${basedir}/src/desktop/resources + ${basedir}/../javase/src/desktop/resources + + + + + + + + + + + executable-jar + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + generate-icons + generate-sources + + generate-desktop-app-wrapper + + + javase + + + + javase-executable-jar + package + + javase-executable-jar + + + javase + + + + + + + + + + test + + + com.codenameone + codenameone-core + compile + + + com.codenameone + codenameone-javase + runtime + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + + + + com.codenameone + codenameone-maven-plugin + + + cn1-tests + test + + test + + + javase + + + + + + + + + + run-android + + + + com.codenameone + codenameone-maven-plugin + + + + run-android-hosted + validate + + hosted-platform + + + android + + + + + + maven-antrun-plugin + + + adb-install + verify + + run + + + ${cn1.hosted.android.skip} + + Running adb install + + + + + + Trying to start app on device using adb + + + + + + + + + + + + + + + + + + + + ios-debug + + + iphone + + + ios + + + + + ios-release + + + iphone + true + + + ios + true + + + + + javascript + + javascript + javascript + + + + + android + + android + android + + + + + win + + windows + win + + + + + windows + + desktop_windows + javase + + + + + mac + + desktop_macosx + javase + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 17 + 17 + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + + com.codenameone + codenameone-maven-plugin + + + + + transcode-svg + generate-sources + + transcode-svg + + + + + compile-android-res + generate-sources + + compile-android-res + + + + generate-gui-sources + process-sources + + generate-gui-sources + + + + cn1-process-classes + process-classes + + + remap-android + bytecode-compliance + css + + process-annotations + + + + + attach-test-artifact + test + + attach-test-artifact + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + true + + + + + + + + + + diff --git a/scripts/ledge/common/src/desktop/resources/NativeTheme.res b/scripts/ledge/common/src/desktop/resources/NativeTheme.res new file mode 100644 index 00000000000..83e067b6969 Binary files /dev/null and b/scripts/ledge/common/src/desktop/resources/NativeTheme.res differ diff --git a/scripts/ledge/common/src/main/css/fonts/LilitaOne-Regular.ttf b/scripts/ledge/common/src/main/css/fonts/LilitaOne-Regular.ttf new file mode 100644 index 00000000000..fdec368cbd4 Binary files /dev/null and b/scripts/ledge/common/src/main/css/fonts/LilitaOne-Regular.ttf differ diff --git a/scripts/ledge/common/src/main/css/fonts/OFL.txt b/scripts/ledge/common/src/main/css/fonts/OFL.txt new file mode 100644 index 00000000000..055594f2f33 --- /dev/null +++ b/scripts/ledge/common/src/main/css/fonts/OFL.txt @@ -0,0 +1,94 @@ +Copyright (c) 2011 Juan Montoreano (juan@remolacha.biz), +with Reserved Font Name Lilita + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/scripts/ledge/common/src/main/css/theme.css b/scripts/ledge/common/src/main/css/theme.css new file mode 100644 index 00000000000..bddea3bebea --- /dev/null +++ b/scripts/ledge/common/src/main/css/theme.css @@ -0,0 +1,406 @@ +/* + * The whole look of Ledge. + * + * Every screen is built from ordinary Codename One widgets, and this file + * dresses them as the game: a twilight sky behind, chunky warm cards with a + * hard drop under them like a block standing on the ground, one rounded + * display face, ember orange (the hero's scarf) for whatever you should + * press next, teal for everything secondary and gold for stars. Change the + * palette below to re-skin the game. + * + * The level itself is not styled here: play/LedgeView.java draws it with + * com.codename1.gaming.platformer, and play/Hud.java writes over it. + */ +@font-face { + font-family: "Lilita One"; + src: url("fonts/LilitaOne-Regular.ttf"); +} +#Constants { + includeNativeBool: true; + defaultSourceDPIInt: "0"; + transitionSpeedInt: "250"; + dialogTransitionIn: "fade"; + dialogTransitionOut: "fade"; + dlgCommandGridBool: false; + dlgButtonCommandUIID: "DialogAction"; + tintColor: "a03a2a1a"; + scrollVisibleBool: false; + tabsSelectionCapsuleBool: false; + tabsAnimatedIndicatorBool: false; + /* tag::ledge-palette[] */ + --sky: #241f45; + --sky-dark: #17132f; + --card: #fff8ee; + --card-edge: #f0dfc6; + --ink: #2a1e30; + --ink-muted: #7a6b78; + --pen: #ff7648; + --pen-dark: #d9542a; + --ballpoint: #1f9e95; + --rule: #f0dfc6; + --good: #4fbf6a; + --gold: #ffc93c; + /* end::ledge-palette[] */ +} + +Default { + font-family: "Lilita One"; + font-size: 3.4mm; + color: var(--ink); +} + +Form { + background-color: var(--sky); +} +Container { + background-color: transparent; +} +ContentPane { + background-color: transparent; +} +Toolbar { + background-color: var(--sky-dark); + padding: 1mm 2mm 1mm 2mm; + border: none; +} +Title { + font-family: "Lilita One"; + font-size: 4.6mm; + color: var(--card); + background-color: transparent; +} +TitleCommand, BackCommand { + color: var(--card); + font-family: "Lilita One"; + font-size: 3.6mm; + background-color: transparent; +} + +Label { + font-family: "Lilita One"; + font-size: 4mm; + color: var(--ink); + background-color: transparent; +} +SpanLabel, SpanLabelText { + color: var(--ink); + background-color: transparent; +} + +/* The game's name on the home screen. */ +Logo { + font-family: "Lilita One"; + font-size: 14mm; + color: var(--pen); + text-align: center; + background-color: transparent; + text-shadow: 0 0.8mm 0 var(--pen-dark); +} +Tagline { + font-family: "Lilita One"; + font-size: 3.6mm; + color: #d9d2f0; + text-align: center; + background-color: transparent; +} + +/* A card: a warm block with a hard drop under it, for groups of content. */ +Card { + background-color: var(--card); + border-radius: 2.5mm; + box-shadow: 0 1mm 0 0 rgba(10, 6, 30, 0.55); + padding: 3mm; + margin: 1.5mm 2mm 1.5mm 2mm; +} +CardTitle { + font-family: "Lilita One"; + font-size: 5mm; + color: var(--ink); + background-color: transparent; +} +CardText { + color: var(--ink-muted); + background-color: transparent; +} + +/* The main action: an ember-orange pill. */ +Button, RaisedButton { + font-family: "Lilita One"; + font-size: 4.6mm; + color: #ffffff; + background-color: var(--pen); + border-radius: 3mm; + box-shadow: 0.3mm 0.7mm 0.8mm 0 rgba(10, 6, 30, 0.6); + padding: 1.8mm 4mm 1.8mm 4mm; + margin: 1mm; + text-align: center; +} +Button.pressed, RaisedButton.pressed { + background-color: var(--pen-dark); + box-shadow: 0.1mm 0.2mm 0.3mm 0 rgba(10, 6, 30, 0.4); +} +/* Everything secondary: a card-coloured pill with teal lettering. */ +Secondary { + font-family: "Lilita One"; + font-size: 3.8mm; + color: var(--ballpoint); + background-color: var(--card); + border-radius: 3mm; + box-shadow: 0.3mm 0.6mm 0.7mm 0 rgba(10, 6, 30, 0.55); + padding: 1.4mm 3mm 1.4mm 3mm; + margin: 1mm; + text-align: center; +} +Secondary.pressed { + background-color: var(--card-edge); + box-shadow: 0.1mm 0.2mm 0.3mm 0 rgba(10, 6, 30, 0.4); +} +/* A link-like button: just the lettering. */ +Plain { + font-family: "Lilita One"; + font-size: 3.6mm; + color: var(--ballpoint); + background-color: transparent; + padding: 1mm 2mm 1mm 2mm; + margin: 0; + text-align: center; +} +Plain.pressed { + color: var(--pen); +} +/* The small round buttons over the game: pause, the menu tools. */ +HudButton { + font-size: 4.2mm; + color: var(--ink); + background-color: rgba(255, 248, 238, 0.9); + border-radius: 50%; + padding: 1.4mm; + margin: 1.5mm; +} + +/* The overlay when a run ends or the game is paused. */ +Scrim { + background-color: rgba(16, 12, 36, 0.66); +} +BigScore { + font-family: "Lilita One"; + font-size: 11mm; + color: var(--ink); + text-align: center; + background-color: transparent; +} +Accent { + font-family: "Lilita One"; + font-size: 4mm; + color: var(--pen); + background-color: transparent; +} +Muted { + font-family: "Lilita One"; + font-size: 3.4mm; + color: var(--ink-muted); + background-color: transparent; +} +OnDesk { + color: var(--card); + background-color: transparent; +} + +TextField, TextHint { + font-family: "Lilita One"; + font-size: 4mm; + color: var(--ink); + background-color: #ffffff; + border: 0.3mm solid var(--card-edge); + border-radius: 0.8mm; + padding: 1.6mm; + margin: 1mm 0 1mm 0; +} +TextHint { + color: #a0a3ad; + border: none; + background-color: transparent; +} + +Dialog { + background-color: var(--card); + border-radius: 1.2mm; + padding: 3mm; +} +DialogTitle { + font-family: "Lilita One"; + font-size: 5mm; + color: var(--ink); + background-color: transparent; +} +DialogBody { + color: var(--ink); + background-color: transparent; +} +DialogAction { + font-family: "Lilita One"; + font-size: 4.2mm; + color: var(--pen); + background-color: transparent; + padding: 1.5mm 3mm 1.5mm 3mm; +} + +/* Tabs are a strip of the card, so they read on any backdrop. */ +Tab, TabSelected { + font-family: "Lilita One"; + font-size: 3.4mm; + color: var(--ink-muted); + background-color: var(--card); + padding: 1.5mm 1.2mm 1.5mm 1.2mm; +} +TabSelected { + color: var(--pen); + border-bottom: 0.6mm solid var(--pen); +} +Tabs { + background-color: transparent; +} +TabsContainer { + background-color: var(--card); +} + +/* List rows (boards, shop, console): strips of card, so they read on the + sky. */ +Row { + background-color: var(--card); + border-bottom: 0.2mm solid var(--rule); + padding: 1.4mm 2mm 1.4mm 2mm; +} +RowMe { + background-color: #ffe2d4; + border-bottom: 0.2mm solid var(--rule); + padding: 1.4mm 2mm 1.4mm 2mm; +} +Rank { + font-family: "Lilita One"; + font-size: 4.2mm; + color: var(--pen); + background-color: transparent; +} + +/* The play screen and the home screen: the level fills them, so no sky. */ +PlayForm { + background-color: var(--sky-dark); +} +Hud { + background-color: transparent; +} + +/* Stars on the result card and the map. */ +StarOn { + color: var(--gold); + background-color: transparent; + padding: 0 0.5mm 0 0.5mm; +} +StarOff { + color: rgba(42, 30, 48, 0.25); + background-color: transparent; + padding: 0 0.5mm 0 0.5mm; +} +/* An empty star on the world map, which is dark: StarOff is ink for a light card. */ +MapStarOff { + color: rgba(255, 255, 255, 0.35); + background-color: transparent; + padding: 0 0.5mm 0 0.5mm; +} + +/* The map: one card per world, painted with its backdrop. */ +WorldCard { + background-color: var(--sky-dark); + border-radius: 3mm; + box-shadow: 0 1mm 0 0 rgba(10, 6, 30, 0.55); + padding: 2.5mm; + margin: 1.5mm 2mm 1.5mm 2mm; +} +WorldTitle { + font-family: "Lilita One"; + font-size: 5.5mm; + color: #ffffff; + background-color: transparent; + text-shadow: 0 0.4mm 0 rgba(10, 6, 30, 0.7); +} +LevelCell { + background-color: transparent; + padding: 1mm; +} +LevelTile { + font-family: "Lilita One"; + font-size: 5mm; + color: var(--ink); + background-color: var(--card); + border-radius: 2.5mm; + box-shadow: 0 0.8mm 0 0 var(--pen-dark); + padding: 3mm 1mm 3mm 1mm; + margin: 0 0 0.6mm 0; + text-align: center; +} +LevelTile.pressed { + background-color: var(--card-edge); + box-shadow: 0 0.2mm 0 0 var(--pen-dark); +} +LevelTileLocked { + color: rgba(255, 255, 255, 0.8); + background-color: rgba(255, 255, 255, 0.12); + border: 1px solid rgba(255, 255, 255, 0.18); + border-radius: 2.5mm; + padding: 3mm 1mm 3mm 1mm; + margin: 0 0 0.6mm 0; + text-align: center; +} + +/* The level editor */ +EditorCanvas { + background-color: transparent; + padding: 0; + margin: 0; +} +EditorBar { + background-color: var(--card); + padding: 1mm 1mm 1.5mm 1mm; + margin: 0; + box-shadow: 0 -0.6mm 0 0 rgba(10, 6, 30, 0.35); +} +Brush { + background-color: rgba(30, 22, 60, 0.08); + border-radius: 1.5mm; + padding: 0.8mm; + margin: 0.6mm; + font-family: "Lilita One"; + font-size: 4mm; + color: var(--ink); +} +BrushOn { + background-color: rgba(255, 196, 64, 0.95); + border-radius: 1.5mm; + padding: 0.8mm; + margin: 0.6mm; + font-family: "Lilita One"; + font-size: 4mm; + color: var(--ink); +} +EditorTool { + font-family: "Lilita One"; + font-size: 2.6mm; + color: var(--ink); + background-color: transparent; + padding: 0.8mm 0.2mm 0.8mm 0.2mm; + margin: 0; + text-align: center; +} +EditorTool.disabled { + color: var(--ink-muted); + background-color: transparent; +} +EditorStatus { + font-family: "Lilita One"; + font-size: 3mm; + color: var(--ink-muted); + background-color: transparent; + text-align: center; + padding: 0.5mm; +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/AppConfig.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/AppConfig.java new file mode 100644 index 00000000000..4b23c4c2a05 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/AppConfig.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.io.Preferences; +import com.codename1.ui.CN; + +/// The few things about the app that are settings and not code. +public final class AppConfig { + /// Where the server is when nothing says otherwise: a server started on + /// this machine with `cn1:backend`. Change this to your deployment's address + /// before you ship; until then the settings screen can point a build at + /// another server, which is how a phone reaches a laptop on the same network. + public static final String DEFAULT_SERVER = "http://localhost:8080"; + /// The id the server knows this app by. The same constant is in the + /// server's `SecurityConfig`. + public static final String CLIENT_ID = "ledge-app"; + /// The address the server hands the authorization code back to. The app + /// reads the code out of the redirect itself and never opens this address, + /// so it only has to be one the server has on its list. + public static final String REDIRECT_URI = "http://127.0.0.1/callback"; + /// The path the server hands the code back on when the app runs in a + /// browser. The same constant is in the server's `SecurityConfig`. + public static final String WEB_REDIRECT_PATH = "/signin/code"; + // tag::ledge-push-key[] + /// The app's push key, from the Push section of the Codename One console. + /// Empty, the app registers for no notifications: everything still works, + /// and a phone in a pocket simply hears nothing until it is opened. + public static final String PUSH_APP_KEY = ""; + // end::ledge-push-key[] + + // tag::ledge-monetization-ids[] + /// Google's published test ad units. They always fill, never pay, and are + /// safe to click; replace them with your own AdMob units before release. + public static final String REWARDED_AD_UNIT = "ca-app-pub-3940256099942544/5224354917"; + public static final String INTERSTITIAL_AD_UNIT = "ca-app-pub-3940256099942544/1033173712"; + public static final String BANNER_AD_UNIT = "ca-app-pub-3940256099942544/6300978111"; + /// The store products, as configured in App Store Connect and the Play + /// Console. The server's `Catalog` names the same ones. + public static final String SKU_COINS_SMALL = "ledge.coins.small"; + public static final String SKU_COINS_LARGE = "ledge.coins.large"; + // end::ledge-monetization-ids[] + + private static final String SERVER_KEY = "ledge.server"; + private static final String MODE_KEY = "ledge.mode"; + private static final String MODE_OWNER_KEY = "ledge.mode.owner"; + + private AppConfig() { + } + + /// The server's address, with no trailing slash. A `ledge.server.url` + /// system property wins, which is what the tests use; then the address saved + /// from the settings screen; then, in a browser, the address the page came + /// from, since the server that hosts the app is the server it talks to; + /// then [#DEFAULT_SERVER]. + public static String serverUrl() { + String url = System.getProperty("ledge.server.url"); + if (url == null || url.length() == 0) { + String origin = pageOrigin(); + // In a browser it is always the page's own server: see + // serverSwitchable(). An address saved before that is ignored. + url = origin != null ? origin : Preferences.get(SERVER_KEY, DEFAULT_SERVER); + } + return clean(url); + } + + /// Whether the app may be pointed at another server. Not in a browser: + /// there the authorization code is sent back to the page's own server + /// ([#redirectUri]), and another server has not registered that address + /// as one of its own, so every sign-in after a switch would be refused. + /// The hosted app is the server's own, and talks to that server. + public static boolean serverSwitchable() { + return pageOrigin() == null; + } + + /// The address of the page the app is running in -- `https://host`, with + /// no path -- or null when it is not running in a browser. + public static String pageOrigin() { + String origin = CN.getProperty("browser.window.location.origin", null); + if (origin == null || !(origin.regionMatches(true, 0, "http://", 0, 7) + || origin.regionMatches(true, 0, "https://", 0, 8))) { + return null; + } + return clean(origin); + } + + /// Where the server is asked to send the authorization code. + /// + /// The installed app names the loopback address and reads the code off the + /// redirect without following it. A browser follows a redirect itself and + /// will not show the page an answer from another origin, so there the code + /// is sent to the server the page came from, which hands it back. + public static String redirectUri() { + String origin = pageOrigin(); + return origin == null ? REDIRECT_URI : origin + WEB_REDIRECT_PATH; + } + + public static void setServerUrl(String url) { + Preferences.set(SERVER_KEY, clean(url)); + } + + /// The mode the account `owner` (see + /// [com.codenameone.examples.ledge.net.Session#owner(String)]) chose last + /// -- `player` or `admin` -- or + /// empty when they have chosen none, or the choice on record is someone + /// else's. A choice recorded with no name is anyone's: that is how a test + /// puts the app in a mode before it signs in. + public static String mode(String owner) { + String chosenBy = Preferences.get(MODE_OWNER_KEY, ""); + if (chosenBy.length() > 0 && !chosenBy.equals(owner)) { + return ""; + } + return Preferences.get(MODE_KEY, ""); + } + + /// Records `mode` as chosen by whoever signs in next. + public static void setMode(String mode) { + setMode(mode, ""); + } + + public static void setMode(String mode, String username) { + Preferences.set(MODE_KEY, mode == null ? "" : mode); + Preferences.set(MODE_OWNER_KEY, username == null ? "" : username); + } + + /// Whether `url` names the server `current` does, as [#setServerUrl] + /// would store it. + public static boolean sameServer(String url, String current) { + return clean(url).equals(current); + } + + + + /// True when the app was opened from the daily-run push or a + /// `ledge://daily` link, so it should go straight to today's sheet. + public static boolean openedForDaily() { + String link = CN.getProperty("AppArg", null); + return link != null && link.indexOf("daily") >= 0; + } + + private static String clean(String url) { + String text = url == null ? "" : url.trim(); + while (text.endsWith("/")) { + text = text.substring(0, text.length() - 1); + } + if (text.length() == 0) { + return DEFAULT_SERVER; + } + // Compared without folding the case: a scheme is ASCII, and + // toLowerCase() follows the device's language. + if (!text.regionMatches(true, 0, "http://", 0, 7) + && !text.regionMatches(true, 0, "https://", 0, 8)) { + text = "http://" + text; + } + return text; + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/Ledge.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/Ledge.java new file mode 100644 index 00000000000..42a4f93e3a7 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/Ledge.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.payment.PurchaseCallback; +import com.codename1.system.Lifecycle; +import com.codenameone.examples.ledge.engage.Ads; +import com.codenameone.examples.ledge.engage.Notifications; +import com.codenameone.examples.ledge.engage.Store; +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.play.Sfx; +import com.codenameone.examples.ledge.ui.Nav; +import com.codenameone.examples.ledge.ui.Ui; + +/// A platformer: five worlds of hand-built levels, a daily challenge, and +/// boards the server checks by replaying every run. +/// +/// Where things are: +/// +/// - `play` -- the game on screen: [com.codenameone.examples.ledge.play.LedgeView] +/// is a `com.codename1.gaming.platformer.view.PlatformView` over the core +/// simulation, [com.codenameone.examples.ledge.play.LedgeArt] maps the +/// generated art onto it, and the HUD and sound sit beside them. The rules +/// are not here: they are the core `com.codename1.gaming.platformer` +/// package, which the server runs too. +/// - `ui` -- every other screen, ordinary widgets that `src/main/css/theme.css` +/// dresses as the game. +/// - `net` -- the session and the REST clients generated from `shared`. +/// - `engage` -- the store, ads and push. +/// - `admin` -- the console, for an account with the ADMIN role. +public class Ledge extends Lifecycle implements PurchaseCallback { + @Override + public void runApp() { + Ui.desktopFonts(); + Sfx.load(); + Ads.start(); + Session.start(AppConfig.serverUrl()); + Nav.launch(); + } + + @Override + public void start() { + super.start(); + Notifications.start(); + } + + @Override + public void itemPurchased(String sku) { + Store.purchased(sku); + } + + @Override + public void itemPurchaseError(String sku, String errorMessage) { + Ui.toast("The purchase did not go through: " + errorMessage); + } + + @Override + public void itemRefunded(String sku) { + // The server hears about refunds from the store itself. + } + + @Override + public void subscriptionStarted(String sku) { + Store.purchased(sku); + } + + @Override + public void subscriptionCanceled(String sku) { + // Ledge sells no subscriptions. + } + + @Override + public void paymentFailed(String paymentCode, String failureReason) { + // Not used: purchases go through the platform store. + } + + @Override + public void paymentSucceeded(String paymentCode, double amount, String currency) { + // Not used: purchases go through the platform store. + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/admin/AdminConsole.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/admin/AdminConsole.java new file mode 100644 index 00000000000..9fd1ce96507 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/admin/AdminConsole.java @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.admin; + +import com.codename1.appkit.Net; +import com.codename1.components.SpanLabel; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.Tabs; +import com.codename1.ui.TextArea; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.ledge.api.AdminActionDto; +import com.codenameone.examples.ledge.api.AuditDto; +import com.codenameone.examples.ledge.api.BroadcastDto; +import com.codenameone.examples.ledge.api.DailySeedDto; +import com.codenameone.examples.ledge.api.FlagDto; +import com.codenameone.examples.ledge.api.PlayerDto; +import com.codenameone.examples.ledge.api.ResolveDto; +import com.codenameone.examples.ledge.net.Api; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.play.Hud; +import com.codenameone.examples.ledge.ui.Nav; +import com.codenameone.examples.ledge.ui.Ui; +import java.util.List; + +/// The console, inside the game: the day at a glance, players, runs flagged +/// as suspicious, today's sheet and push, and the audit log. Every route is +/// ADMIN only on the server, which also writes every action to the log; this +/// screen is only a way to ask. +// tag::ledge-admin[] +public final class AdminConsole { + private AdminConsole() { + } + + public static void show() { + Form f = Ui.form("Console", "console"); + f.setLayout(new BorderLayout()); + f.setScrollable(false); + Ui.back(f, Nav::home); + Tabs tabs = new Tabs(); + tabs.addTab("Today", page(AdminConsole::overview)); + tabs.addTab("Players", page(AdminConsole::players)); + tabs.addTab("Flags", page(AdminConsole::flags)); + tabs.addTab("Daily", page(AdminConsole::sheet)); + tabs.addTab("Audit", page(AdminConsole::audit)); + tabs.addTab("Deaths", page(AdminConsole::deaths)); + // six tabs do not fit a phone's width as equal cells; let them scroll + tabs.getTabsContainer().setLayout(BoxLayout.x()); + tabs.getTabsContainer().setScrollableX(true); + // Tabs follow the platform's placement, which on a desktop is the + // bottom edge, far from the title; the console keeps them on top. + tabs.setTabPlacement(com.codename1.ui.Component.TOP); + f.add(BorderLayout.CENTER, tabs); + Ui.desktopColumn(f); + f.show(); + } + + interface Filler { + void fill(Container into); + } + + private static Container page(Filler filler) { + Container c = new Container(BoxLayout.y()); + c.setScrollableY(true); + filler.fill(c); + return c; + } + + // ---- deaths --------------------------------------------------------------------- + + /// Where players die, level by level, from the server's replays of their + /// runs: the place a level is too hard shows up as a bright spot. + static void deaths(final Container c) { + final Container map = new Container(BoxLayout.y()); + Container levels = new Container(BoxLayout.x()); + levels.setScrollableX(true); + for (int i = 0; i < LevelPack.IDS.length; i++) { + final String id = LevelPack.IDS[i]; + levels.add(Ui.secondary(id, "heat-" + id, e -> heat(map, id))); + } + c.add(levels).add(map); + heat(map, LevelPack.IDS[0]); + } + + static void heat(final Container map, final String level) { + Api.admin().heatmap(level, Net.to(h -> Ui.later(() -> { + map.removeAll(); + map.add(new Label(level + " " + LevelPack.NAMES[LevelPack.indexOf(level)], "Accent")); + Label summary = new Label(h.deaths() + " deaths in " + h.runs() + " replayed runs", "Muted"); + summary.setName("heatSummary"); + map.add(summary); + map.add(new HeatView(h)); + map.revalidate(); + }), Ui::failed)); + } + + // ---- today ---------------------------------------------------------------------- + + static void overview(final Container c) { + Api.admin().stats(Net.to(s -> Ui.later(() -> { + c.removeAll(); + Container grid = new Container(new GridLayout(2, 3)); + grid.add(stat("Players", s.players())).add(stat("Active today", s.activeToday())) + .add(stat("Runs today", s.runsToday())).add(stat("Open flags", s.flagsOpen())) + .add(stat("Purchases", s.purchases())).add(statText("Top score", Hud.format(s.topScore()))); + c.add(grid); + c.add(new Label("Today's seed " + s.dailySeed(), "Muted")); + c.revalidate(); + }), Ui::failed)); + } + + private static Container stat(String name, int value) { + return statText(name, String.valueOf(value)); + } + + private static Container statText(String name, String value) { + // On a card: BigScore is the result card's dark ink, unreadable on + // the console's own dark page. + Container card = BoxLayout.encloseY(new Label(value, "BigScore"), new Label(name, "CardText")); + card.setUIID("Card"); + return card; + } + + // ---- players -------------------------------------------------------------------- + + static void players(final Container c) { + final TextField q = new TextField("", "Search by name or email", 20, TextField.ANY); + q.setName("adminSearch"); + final Container rows = new Container(BoxLayout.y()); + q.setDoneListener(e -> search(rows, q.getText())); + c.add(Ui.panel(q, Ui.primary("Search", "adminSearchButton", e -> search(rows, q.getText())))); + c.add(rows); + search(rows, ""); + } + + static void search(final Container rows, String q) { + Api.admin().players(q, Net.to(list -> Ui.later(() -> { + rows.removeAll(); + for (PlayerDto p : list) { + rows.add(player(rows, p)); + } + rows.revalidate(); + }), Ui::failed)); + } + + private static Container player(final Container rows, final PlayerDto p) { + Container row = new Container(BoxLayout.y(), p.flagged() ? "RowMe" : "Row"); + String state = p.suspended() ? " (suspended)" : ""; + row.add(new Label(p.displayName() + " @" + p.username() + state)); + row.add(new Label(stars(p.progress()) + " stars daily " + Hud.format(p.bestDaily()) + + " runs " + p.runs(), "Muted")); + Container actions = new Container(new GridLayout(1, 4)); + actions.add(act(rows, p, "WARN", "Warn", 0)); + actions.add(act(rows, p, "SUSPEND", "7 days", 7)); + actions.add(act(rows, p, p.suspended() ? "UNBAN" : "BAN", p.suspended() ? "Unban" : "Ban", 0)); + actions.add(act(rows, p, "RESET_SCORES", "Reset", 0)); + row.add(actions); + return row; + } + + private static com.codename1.ui.Button act(final Container rows, final PlayerDto p, final String action, + String label, final int days) { + return Ui.button(label, "Plain", "act-" + action + "-" + p.username(), e -> Api.admin().act(p.username(), + new AdminActionDto(action, "From the console", days), + Net.to(after -> Ui.later(() -> search(rows, "")), Ui::failed))); + } + + // ---- flags ---------------------------------------------------------------------- + + static void flags(final Container c) { + Api.admin().flags(true, Net.to(list -> Ui.later(() -> fillFlags(c, list)), Ui::failed)); + } + + private static void fillFlags(final Container c, List list) { + c.removeAll(); + if (list.isEmpty()) { + c.add(new Label("Nothing to look at.", "Muted")); + } + for (final FlagDto fl : list) { + Container row = new Container(BoxLayout.y(), "Row"); + row.add(new Label(fl.displayName() + " " + fl.level() + " " + Hud.format(fl.score()))); + row.add(new SpanLabel("Cleared in " + Scoring.time(fl.ticks()) + ". " + fl.reason(), "Muted")); + Container both = new Container(new GridLayout(1, 2)); + both.add(Ui.secondary("Keep", "keep-" + fl.id(), e -> resolve(c, fl, "KEEP"))); + both.add(Ui.primary("Strike the run", "strike-" + fl.id(), e -> resolve(c, fl, "REMOVE"))); + row.add(both); + c.add(row); + } + c.revalidate(); + } + + private static void resolve(final Container c, FlagDto fl, String verdict) { + Api.admin().resolve(fl.id(), new ResolveDto(verdict), Net.to(done -> Ui.later(() -> flags(c)), + Ui::failed)); + } + + // ---- sheet and push ------------------------------------------------------------- + + static void sheet(final Container c) { + final TextField seed = new TextField("", "Seed for today's sheet", 20, TextField.NUMERIC); + seed.setName("dailySeed"); + c.add(Ui.panel(Ui.label("Today's sheet", "CardTitle"), + Ui.text("Every player is dealt the same creatures from this seed until midnight UTC.", "CardText"), + seed, Ui.primary("Deal this sheet", "setDaily", e -> { + long value; + try { + value = Long.parseLong(seed.getText().trim()); + } catch (NumberFormatException err) { + Ui.toast("A seed is a whole number"); + return; + } + Api.admin().setDaily(new DailySeedDto(value), Net.to(d -> Ui.later( + () -> Ui.toast("Today's sheet is seed " + d.seed())), Ui::failed)); + }))); + final TextField title = new TextField("Today's sheet is out", "Title", 30, TextField.ANY); + final TextArea body = new TextArea("New creatures, same page for everyone. Beat your friends."); + final TextField days = new TextField("0", "Only players away this many days (0 = all)", 4, + TextField.NUMERIC); + title.setName("pushTitle"); + body.setName("pushBody"); + c.add(Ui.panel(Ui.label("Push", "CardTitle"), title, body, days, + Ui.primary("Send", "sendPush", e -> { + int d = 0; + try { + d = Integer.parseInt(days.getText().trim()); + } catch (NumberFormatException err) { + d = 0; + } + Api.admin().broadcast(new BroadcastDto(null, title.getText(), body.getText(), d, 0, 0L), + Net.to(sent -> Ui.later(() -> Ui.toast("Sent to " + sent.targets() + " players")), + Ui::failed)); + }))); + } + + // ---- audit ---------------------------------------------------------------------- + + static void audit(final Container c) { + Api.admin().audit(Net.to(list -> Ui.later(() -> { + for (AuditDto a : list) { + c.add(BoxLayout.encloseY(new Label(a.admin() + " " + a.action() + " " + nz(a.username())), + new Label(nz(a.reason()), "Muted"))); + } + c.revalidate(); + }), Ui::failed)); + } + + private static String nz(String s) { + return s == null ? "" : s; + } + + private static int stars(String progress) { + int n = 0; + for (int i = 0; progress != null && i < progress.length(); i++) { + int d = progress.charAt(i) - '0'; + n += d >= 0 && d <= 3 ? d : 0; + } + return n; + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/admin/HeatView.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/admin/HeatView.java new file mode 100644 index 00000000000..138c149aec8 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/admin/HeatView.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.admin; + +import com.codename1.gaming.platformer.TileGrid; +import com.codename1.ui.CN; +import com.codenameone.examples.ledge.ui.Ui; +import com.codename1.ui.Component; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import com.codename1.ui.geom.Dimension; +import com.codenameone.examples.ledge.api.HeatmapDto; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.play.LedgeArt; + +/// A level drawn small with its own tiles, and a glow on every tile where +/// players died: the brighter, the more deaths. +final class HeatView extends Component { + private final TileGrid grid; + private final LedgeArt art; + private final int[] counts; + private final int max; + + HeatView(HeatmapDto map) { + int index = LevelPack.indexOf(map.level()); + grid = LevelPack.load(index).createWorld(1).getGrid(); + art = new LedgeArt(LevelPack.THEMES[index]); + counts = new int[grid.getCols() * grid.getRows()]; + String cells = map.cells() == null ? "" : map.cells(); + int at = 0; + int i = 0; + while (at < cells.length() && i < counts.length) { + int comma = cells.indexOf(',', at); + String one = comma < 0 ? cells.substring(at) : cells.substring(at, comma); + try { + counts[i] = Integer.parseInt(one.trim()); + } catch (NumberFormatException e) { + counts[i] = 0; + } + i++; + at = comma < 0 ? cells.length() : comma + 1; + } + int m = 0; + for (int c : counts) { + m = Math.max(m, c); + } + max = m; + setName("heatmap"); + setUIID("Container"); + } + + /// The first row with anything in it: the empty sky above a level is + /// not drawn. + private int top() { + for (int r = 0; r < grid.getRows(); r++) { + for (int c = 0; c < grid.getCols(); c++) { + if (grid.get(c, r) != 0 || counts[r * grid.getCols() + c] > 0) { + return Math.max(0, r - 1); + } + } + } + return 0; + } + + private int cell() { + return Math.max(6, Ui.mm(2.2f)); + } + + /// Columns per strip: a long level is wrapped into strips stacked down + /// the screen, so all of it is in view at a scale where a spike reads. + private int perStrip() { + int width = CN.isDesktop() ? Math.min(CN.getDisplayWidth(), Ui.desktopPage(CN.getDisplayWidth())) + : CN.getDisplayWidth(); + return Math.max(8, (width - Ui.mm(4)) / cell()); + } + + private int strips() { + return (grid.getCols() + perStrip() - 1) / perStrip(); + } + + private int stripHeight() { + return (grid.getRows() - top()) * cell() + Ui.mm(2); + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(perStrip() * cell(), strips() * stripHeight()); + } + + @Override + public void paint(Graphics g) { + int ts = cell(); + int per = perStrip(); + int top = top(); + int rows = grid.getRows() - top; + for (int s = 0; s < strips(); s++) { + int c0 = s * per; + int c1 = Math.min(grid.getCols(), c0 + per); + int x0 = getX(); + int y0 = getY() + s * stripHeight(); + g.setColor(0x9fd0ea); + g.fillRect(x0, y0, (c1 - c0) * ts, rows * ts); + for (int r = top; r < grid.getRows(); r++) { + for (int c = c0; c < c1; c++) { + Image img = art.tile(grid, c, r); + if (img != null) { + g.drawImage(img, x0 + (c - c0) * ts, y0 + (r - top) * ts, ts, ts); + } + } + } + if (max == 0) { + continue; + } + // a glow stays inside its own strip + int[] clip = g.getClip(); + g.clipRect(x0, y0, (c1 - c0) * ts, rows * ts); + g.setAntiAliased(true); + for (int r = top; r < grid.getRows(); r++) { + for (int c = c0; c < c1; c++) { + int n = counts[r * grid.getCols() + c]; + if (n == 0) { + continue; + } + // a soft glow in two passes: a wide red halo, then a hot core + int halo = ts * (8 + 12 * n / max) / 10; + int cx = x0 + (c - c0) * ts + ts / 2; + int cy = y0 + (r - top) * ts + ts / 2; + g.setColor(0xff3b2f); + g.setAlpha(70 + 90 * n / max); + g.fillArc(cx - halo, cy - halo, halo * 2, halo * 2, 0, 360); + g.setColor(0xffd23f); + g.setAlpha(140 + 115 * n / max); + g.fillArc(cx - halo / 2, cy - halo / 2, halo, halo, 0, 360); + } + } + g.setAlpha(255); + g.setClip(clip); + } + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Ads.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Ads.java new file mode 100644 index 00000000000..a52b4c9063c --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Ads.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.engage; + +import com.codename1.ads.AdConfig; +import com.codename1.ads.AdError; +import com.codename1.ads.AdFormat; +import com.codename1.ads.AdListener; +import com.codename1.ads.AdManager; +import com.codename1.ads.BannerAd; +import com.codename1.ads.InterstitialAd; +import com.codename1.ads.RewardedAd; +import com.codename1.ads.ServerSideVerificationOptions; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Dialog; +import com.codenameone.examples.ledge.AppConfig; +import com.codenameone.examples.ledge.net.Session; + +/// Advertising, through `com.codename1.ads`. Three placements, each the kind +/// players accept in a free game: +/// +/// - **Rewarded**: opt in, watch, get coins. The server grants the coins and +/// caps them per day, so a modified client gains nothing. +/// - **Interstitial**: between runs, at most every third one, never +/// during play and never for a player who has bought ink. +/// - **Banner**: on the home screen only. +/// +/// The ad network is a cn1lib (AdMob, AppLovin, ...) registered with +/// [AdManager]; this class names none of them. Where no network is installed +/// -- the simulator, the web build, a fork that has not added one yet -- a +/// rewarded ad is a short stand-in dialog, so the reward flow can be built and +/// tested end to end, and the other placements are simply absent. +// tag::ledge-ads[] +public final class Ads { + private static final int INTERSTITIAL_EVERY = 3; + private static int runsSinceAd; + + private Ads() { + } + + public static void start() { + if (AdManager.getProvider() != null) { + AdManager.initialize(new AdConfig().testMode(true), ready -> { }); + } + } + + /// Plays a rewarded ad and runs `granted` once the network says it was + /// watched to the end. + public static void rewarded(final Runnable granted, final Runnable unavailable) { + if (!AdManager.isInitialized() || !AdManager.isSupported(AdFormat.REWARDED)) { + standIn(granted); + return; + } + final RewardedAd ad = new RewardedAd(AppConfig.REWARDED_AD_UNIT); + // Server-side verification: the network calls the game's server with + // this user id, so a reward could be granted there and nowhere else. + String who = Session.user() == null ? "" : Session.user().username(); + ad.setServerSideVerificationOptions(new ServerSideVerificationOptions(who, "coins")); + ad.setAdListener(new AdListener() { + @Override + public void onLoaded() { + ad.show(reward -> CN.callSerially(granted)); + } + + @Override + public void onFailedToLoad(AdError error) { + CN.callSerially(unavailable); + } + }); + ad.load(); + } + + /// Called after every run; shows an interstitial every few. + public static void betweenRuns(boolean adFree) { + runsSinceAd++; + if (adFree || runsSinceAd < INTERSTITIAL_EVERY || !AdManager.isInitialized() + || !AdManager.isSupported(AdFormat.INTERSTITIAL)) { + return; + } + runsSinceAd = 0; + final InterstitialAd ad = new InterstitialAd(AppConfig.INTERSTITIAL_AD_UNIT); + ad.setAdListener(new AdListener() { + @Override + public void onLoaded() { + ad.show(); + } + }); + ad.load(); + } + + /// A banner for the home screen, or null where there is no network. + public static Component banner(boolean adFree) { + if (adFree || !AdManager.isInitialized() || !AdManager.isSupported(AdFormat.BANNER)) { + return null; + } + BannerAd banner = new BannerAd(AppConfig.BANNER_AD_UNIT); + banner.load(); + return banner; + } + + private static void standIn(final Runnable granted) { + Dialog d = new Dialog("Sponsored", new com.codename1.ui.layouts.BorderLayout()); + d.setUIID("AdDialog"); + d.add(com.codename1.ui.layouts.BorderLayout.CENTER, + new com.codename1.components.SpanLabel("An ad would play here. Install an ad network cn1lib " + + "to show real ones.")); + d.setTimeout(1500); + d.show(); + granted.run(); + } +} +// end::ledge-ads[] diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Notifications.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Notifications.java new file mode 100644 index 00000000000..2b286335bac --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Notifications.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.engage; + +import com.codename1.io.Log; +import com.codename1.io.Preferences; +import com.codename1.push.PushClient; +import com.codename1.push.PushError; +import com.codename1.push.PushListener; +import com.codename1.push.PushMessage; +import com.codename1.push.PushSubscription; +import com.codename1.ui.CN; +import com.codenameone.examples.ledge.AppConfig; +import com.codenameone.examples.ledge.api.PushDeviceDto; +import com.codenameone.examples.ledge.net.Api; +import com.codename1.appkit.Net; +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.ui.Nav; + +/// Push notifications, the game's way of bringing a player back: a friend +/// accepted your challenge, your daily rewards are ready, and -- for admins +/// -- a player was flagged. +/// +/// The device registers with `com.codename1.push`, then hands its token to +/// the server, which sends through the Codename One push service. A player +/// can turn them off in Settings; the server is told, and stops. +// tag::ledge-push[] +public final class Notifications { + private static final String ENABLED = "ledge.push"; + private static PushClient client; + private static PushSubscription subscription; + + private Notifications() { + } + + public static boolean enabled() { + return Preferences.get(ENABLED, true); + } + + public static void setEnabled(boolean on) { + Preferences.set(ENABLED, on); + if (on) { + start(); + } else { + signingOut(() -> { }); + } + } + + public static void start() { + if (!available() || !enabled()) { + return; + } + if (client == null) { + client = PushClient.builder(AppConfig.PUSH_APP_KEY).listener(new Listener()).build(); + } + client.register(); + } + + /// Tells the server where to reach this device; called after signing in. + public static void signedIn() { + PushDeviceDto device = device(); + if (device != null && Session.user() != null && enabled()) { + Api.account().registerPush(device, Net.to(saved -> { }, (s, m) -> { })); + } + } + + public static void signingOut(Runnable then) { + PushDeviceDto device = device(); + if (device == null || Session.user() == null) { + then.run(); + return; + } + Api.account().unregisterPush(device, Net.to(gone -> then.run(), (s, m) -> then.run())); + } + + /// Only on a phone with a push key configured; the simulator and the web + /// build simply never ask. + public static boolean available() { + if (AppConfig.PUSH_APP_KEY.length() == 0 || CN.isSimulator()) { + return false; + } + String platform = CN.getPlatformName(); + return "and".equals(platform) || "ios".equals(platform); + } + + private static PushDeviceDto device() { + if (subscription == null) { + return null; + } + return new PushDeviceDto(subscription.getTransportId(), subscription.getToken(), + CN.getPlatformName()); + } + + private static final class Listener implements PushListener { + @Override + public void onRegistration(PushSubscription registered) { + subscription = registered; + signedIn(); + } + + /// A tap on a notification opens the screen it is about. + @Override + public void onMessage(PushMessage message) { + if (Session.user() == null) { + return; + } + // The keys are the ones the server's Broadcasts puts in `data`. + Object screen = message.getData().get("screen"); + if ("admin".equals(screen) && Session.user().admin()) { + Nav.adminConsole(); + } else if ("daily".equals(screen)) { + Nav.daily(); + } else { + Nav.home(); + } + } + + @Override + public void onError(PushError error) { + Log.p("Push registration failed: " + error.getCode() + " " + error.getMessage()); + } + } +} +// end::ledge-push[] diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Store.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Store.java new file mode 100644 index 00000000000..d10befd8312 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/engage/Store.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.engage; + +import com.codename1.io.Log; +import com.codename1.payment.Product; +import com.codename1.payment.Purchase; +import com.codename1.payment.Receipt; +import com.codename1.ui.CN; +import com.codenameone.examples.ledge.api.ReceiptDto; +import com.codenameone.examples.ledge.api.WalletDto; +import com.codenameone.examples.ledge.net.Api; +import com.codename1.appkit.Net; +import java.util.List; + +/// In-app purchases, through `com.codename1.payment`. +/// +/// The store takes the money; the game's server grants what was bought. A +/// purchase the device reports is sent to the server as a receipt, the server +/// asks Apple or Google whether it is real, and only then adds the ink -- +/// once, however many times the receipt arrives. A client that claims a +/// purchase it did not make gets nothing. +/// +/// The main class implements `PurchaseCallback`, which is how Codename One +/// reports a finished purchase; it calls [#purchased]. +// tag::ledge-store[] +public final class Store { + /// Told about the wallet after the server granted a purchase. + public interface Granted { + void granted(WalletDto wallet); + } + + private static Granted listener; + + private Store() { + } + + public static void listen(Granted granted) { + listener = granted; + } + + /// Whether a real store takes the money. The simulator's own store stands + /// in for one only when the app's main class is running to hear back, so + /// here the simulator takes the simulated-receipt path instead, which + /// exercises the same server validation. + public static boolean available() { + Purchase p = Purchase.getInAppPurchase(); + return !CN.isSimulator() && p != null && p.isManagedPaymentSupported(); + } + + /// The store's own price for `sku`, in the player's currency, or null + /// where there is no store to ask (the simulator) or it has not said. + public static String price(String sku) { + if (!available()) { + return null; + } + Product[] products = Purchase.getInAppPurchase().getProducts(new String[] {sku}); + if (products == null || products.length == 0 || products[0] == null) { + return null; + } + String p = products[0].getLocalizedPrice(); + return p == null || p.length() == 0 ? null : p; + } + + /// Starts buying `sku` from the platform's store. In the simulator the + /// purchase completes at once with a simulated receipt, which the server + /// accepts on its development profiles only. + public static void buy(String sku) { + if (available()) { + Purchase.getInAppPurchase().purchase(sku); + } else { + redeem(new ReceiptDto(Receipt.STORE_CODE_SIMULATOR, sku, + "sim-" + System.currentTimeMillis(), "")); + } + } + + /// From `PurchaseCallback.itemPurchased`: finds the store's receipt and + /// sends it to the server. + public static void purchased(String sku) { + Purchase p = Purchase.getInAppPurchase(); + if (p == null) { + return; + } + Receipt[] receipts = p.getReceipts(sku); + if (receipts == null || receipts.length == 0) { + return; + } + Receipt r = receipts[receipts.length - 1]; + redeem(new ReceiptDto(r.getStoreCode(), sku, r.getTransactionId(), r.getOrderData())); + } + + /// Sends every receipt the store still holds. The server grants each only + /// once, so this is safe to repeat; it picks up a purchase whose first + /// report was lost when the app was killed mid-way. + public static void resend() { + Purchase p = Purchase.getInAppPurchase(); + if (p == null || !available()) { + return; + } + List all = p.getReceipts(); + for (int i = 0; i < all.size(); i++) { + Receipt r = all.get(i); + redeem(new ReceiptDto(r.getStoreCode(), r.getSku(), r.getTransactionId(), r.getOrderData())); + } + } + + private static void redeem(ReceiptDto receipt) { + Api.shop().receipt(receipt, Net.to(wallet -> { + if (listener != null) { + CN.callSerially(() -> listener.granted(wallet)); + } + }, (status, message) -> Log.p("Receipt refused: " + status + " " + message))); + } +} +// end::ledge-store[] diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/net/Api.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/net/Api.java new file mode 100644 index 00000000000..2b99aa55d57 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/net/Api.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.net; + +import com.codename1.io.rest.RestClients; +import com.codenameone.examples.ledge.api.AccountApi; +import com.codenameone.examples.ledge.api.AdminApi; +import com.codenameone.examples.ledge.api.FriendsApi; +import com.codenameone.examples.ledge.api.ProgressApi; +import com.codenameone.examples.ledge.api.LevelsApi; +import com.codenameone.examples.ledge.api.RunApi; +import com.codenameone.examples.ledge.api.ShopApi; + +/// The generated REST clients, one per contract in the shared module, all +/// pointed at the server [Session] is using. +public final class Api { + private static AccountApi account; + private static RunApi runs; + private static LevelsApi levels; + private static FriendsApi friends; + private static ShopApi shop; + private static ProgressApi progress; + private static AdminApi admin; + + private Api() { + } + + static void connect(String baseUrl) { + account = RestClients.create(AccountApi.class, baseUrl); + runs = RestClients.create(RunApi.class, baseUrl); + levels = RestClients.create(LevelsApi.class, baseUrl); + friends = RestClients.create(FriendsApi.class, baseUrl); + shop = RestClients.create(ShopApi.class, baseUrl); + progress = RestClients.create(ProgressApi.class, baseUrl); + admin = RestClients.create(AdminApi.class, baseUrl); + } + + public static AccountApi account() { + return account; + } + + public static LevelsApi levels() { + return levels; + } + + public static RunApi runs() { + return runs; + } + + public static FriendsApi friends() { + return friends; + } + + public static ShopApi shop() { + return shop; + } + + public static ProgressApi progress() { + return progress; + } + + public static AdminApi admin() { + return admin; + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/net/Session.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/net/Session.java new file mode 100644 index 00000000000..62c25e9d61c --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/net/Session.java @@ -0,0 +1,543 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.net; + +import com.codename1.appkit.Net; + +import com.codename1.io.ConnectionRequest; +import com.codename1.io.JSONParser; +import com.codename1.io.NetworkManager; +import com.codename1.io.RequestAuthorizer; +import com.codename1.io.Util; +import com.codename1.io.oidc.OidcClient; +import com.codename1.io.oidc.OidcConfiguration; +import com.codename1.io.oidc.OidcRequestAuthorizer; +import com.codename1.io.oidc.OidcTokens; +import com.codename1.io.oidc.PkceChallenge; +import com.codename1.io.oidc.SecureStorageTokenStore; +import com.codename1.io.oidc.TokenStore; +import com.codename1.ui.CN; +import com.codename1.util.SuccessCallback; +import com.codenameone.examples.ledge.AppConfig; +import com.codenameone.examples.ledge.api.PlayerDto; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Map; + +/// Who is signed in, and the tokens that say so. +/// +/// Signing in is OAuth's authorization-code flow with PKCE against the app's +/// own server, made without a browser: the app shows its own sign-in screen, +/// posts the password to the server for a short-lived session, exchanges the +/// session for an authorization code and the code for tokens. The password is +/// sent once, to the server that owns it, and is never stored; what is stored +/// is the token pair, in the device's secure storage. +/// +/// From then on [OidcRequestAuthorizer] does the work: it puts the access token +/// on every request under `/api`, renews it shortly before it expires, and +/// renews and retries when the server refuses one. When renewing fails -- the +/// refresh token ran out, or the account was suspended -- it says so, and the +/// app goes back to the welcome screen. +public final class Session { + private static final String STORE_PREFIX = "ledge"; + private static final String SESSION_COOKIE = "CN1SESSION"; + + private static String base; + private static OidcClient client; + private static OidcRequestAuthorizer authorizer; + private static TokenStore store; + private static PlayerDto user; + private static Runnable onSignedOut; + /// Counts the sessions: moved on whenever the server changes, an account + /// signs in, or the session ends. An answer to a request made in an + /// earlier session describes somebody who is no longer signed in here -- + /// another server's account, or the account before a sign-out on this + /// one -- and is dropped rather than installed for whoever is now. + private static int session; + + private Session() { + } + + /// Points the app at a server. Called at start-up, and again when the + /// server address is changed. + public static void start(String baseUrl) { + if (store == null) { + // Falls back to ordinary storage where the platform has no keystore + // to offer, which is the simulator. + store = new SecureStorageTokenStore().allowPlainStorageFallback(true); + } + if (base != null) { + NetworkManager.getInstance().setAuthorizer(base + "/api", null); + if (!base.equals(baseUrl)) { + // Changing the server ends the session with the old one, and + // its tokens go with it. + store.clear(storeKey(base)); + } + } + base = baseUrl; + setUser(null); + session++; + client = OidcClient.create(OidcConfiguration.newBuilder() + .issuer(base) + .authorizationEndpoint(base + "/oauth2/authorize") + .tokenEndpoint(base + "/oauth2/token") + .revocationEndpoint(base + "/oauth2/revoke") + .jwksUri(base + "/oauth2/jwks") + .build()) + .setClientId(AppConfig.CLIENT_ID) + .setRedirectUri(AppConfig.redirectUri()) + .setScopes("openid", "profile") + .setTokenStore(store) + .setStoreKey(storeKey(base)); + authorizer = new OidcRequestAuthorizer(client); + authorizer.install(base + "/api"); + // Not tied to this start(). A request to an earlier server still in + // flight when the app switched, answered 401 with its refresh refused, + // signs the new server out too: one more sign-in, after a server + // switch that already asked for one, and nothing of either account is + // exposed by it. + authorizer.addSignInRequiredListener((source, reason) -> { + setUser(null); + session++; + if (onSignedOut != null) { + onSignedOut.run(); + } + }); + Api.connect(base); + } + + /// Where the tokens issued by one server are kept: under a name made from + /// that server's address. + /// + /// One name for every server would hand the tokens of the last one to + /// whichever address is typed next -- the app would restore them and send + /// them, refresh token included, to a server that never issued them. + /// Every character that is not a letter or a digit is written as its code, + /// so two addresses never share a name and the name is one any platform's + /// storage accepts. + static String storeKey(String server) { + StringBuilder key = new StringBuilder(STORE_PREFIX).append('-'); + for (int iter = 0; iter < server.length(); iter++) { + char c = server.charAt(iter); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { + key.append(c); + } else { + key.append('_').append(Integer.toHexString(c)).append('_'); + } + } + return key.toString(); + } + + /// Keeps the tokens somewhere else. The tests keep them in memory, so one + /// run leaves nothing behind for the next. + public static void useStore(TokenStore tokens) { + store = tokens; + } + + /// What to do when the session ends without the user asking: go back to + /// the welcome screen. + public static void onSignedOut(Runnable handler) { + onSignedOut = handler; + } + + public static String serverUrl() { + return base; + } + + /// The signed-in user as the server last described them, or null. + public static PlayerDto user() { + return user; + } + + public static void setUser(PlayerDto described) { + user = described; + } + + /// Who what the device keeps belongs to: the signed-in account, or null. + /// See [#owner(String)]. + public static String owner() { + return user == null || user.username() == null ? null : owner(user.username()); + } + + /// The device's name for the account `username` on the server in use. A + /// name is unique on one server only: the same e-mail address signed in + /// to two servers is two accounts, and what one left -- recent places, + /// a change it has not sent yet -- is not the other's to see or send. + public static String owner(String username) { + return storeKey(base == null ? "" : base) + "/" + accountName(username); + } + + /// Picks up the session a previous run left, if it is still good. + /// + /// @param signedIn there is a session, and [#user] is set + /// @param signedOut there is none + /// @param unreachable there is one, but the server did not answer + public static void restore(final Runnable signedIn, final Runnable signedOut, + final Runnable unreachable) { + // Loading the tokens can outlast the session it was asked in -- the + // server is changed while it reads -- and then neither answer is this + // session's to act on: see [#session]. + final int asked = session; + authorizer.load().ready(new SuccessCallback() { + @Override + public void onSucess(OidcTokens tokens) { + if (asked != session) { + return; + } + if (tokens == null || tokens.getAccessToken() == null) { + signedOut.run(); + return; + } + refreshUser(signedIn, (status, message) -> { + if (status == 0) { + unreachable.run(); + } else { + signedOut.run(); + } + }); + } + }).except(new SuccessCallback() { + @Override + public void onSucess(Throwable err) { + if (asked == session) { + signedOut.run(); + } + } + }); + } + + /// Asks the server who this is. The roles in the answer decide which modes + /// the app offers, so it is asked again whenever that could have changed. + public static void refreshUser(final Runnable done, Net.Failed failed) { + // An answer from a session that has since ended -- the server was + // changed while an approval poll waited, or the account signed out + // and another signed in -- describes that account, not this one; + // it is dropped. See [#session]. + final int asked = session; + Api.account().me(Net.to(described -> { + if (asked != session) { + return; + } + setUser(described); + done.run(); + }, (status, message) -> { + if (asked == session) { + failed.failed(status, message); + } + })); + } + + /// Signs in with an e-mail address and password. + /// An e-mail address the way the server names its account: trimmed, with + /// its ASCII letters in lower case (`Accounts.email` on the server). Signing + /// in as `Player@Ledge.example` must reach, and record its mode under, the + /// same account as `player@ledge.example`. Folded by hand: `toLowerCase()` + /// follows the device locale, and under Turkish the `I` would not fold to `i`. + public static String accountName(String email) { + if (email == null) { + return null; + } + char[] chars = email.trim().toCharArray(); + for (int iter = 0; iter < chars.length; iter++) { + char c = chars[iter]; + if (c >= 'A' && c <= 'Z') { + chars[iter] = (char) (c + ('a' - 'A')); + } + } + return new String(chars); + } + + public static void signIn(String email, String password, final Runnable done, + final Net.Failed failed) { + // The server can be changed while the sign-in is under way, and + // start() then puts a new authorizer in place. Tokens the old server + // issued are dropped rather than installed in the new one, which would + // send them -- the refresh token too -- to a server that never issued + // them. See [#session]. + final int asked = session; + authenticate(email, password, tokens -> { + if (asked != session) { + return; + } + session++; + authorizer.setTokens(tokens); + store.save(storeKey(base), tokens); + refreshUser(done, failed); + }, failed); + } + + /// Exchanges an e-mail address and password for tokens, and does nothing + /// with them: [#signIn] is this, and then keeping what comes back. + public static void authenticate(final String email, final String password, + final Net.Ok got, final Net.Failed failed) { + final PkceChallenge pkce = PkceChallenge.generate(); + // Any unguessable value does for the state; this is one. + final String state = PkceChallenge.generate().getVerifier(); + // In a browser the app sees neither the session cookie nor a redirect: + // the browser keeps the first and follows the second. So there the + // password's answer is its status, and the code is read from the page + // the redirect ends on -- see AppConfig.redirectUri(). + final boolean web = AppConfig.pageOrigin() != null; + final String redirect = AppConfig.redirectUri(); + + // Every step goes to the server the sign-in started with, and none goes + // anywhere once the user has changed server: the session cookie of + // step 1 and the verifier of step 3 are only for the first server, and + // a new one that received them could replay them there for tokens. + final String server = base; + // 1. The password, for a session. + final Step login = new Step("POST", server + "/login"); + login.addArgument("username", accountName(email)); + login.addArgument("password", password); + login.send(() -> { + if (!server.equals(base)) { + failed.failed(0, "The server changed. Sign in again."); + return; + } + if (login.status == 0) { + failed.failed(0, "Could not reach the server. Check your connection."); + return; + } + if (login.status == 429) { + failed.failed(429, "Too many attempts. Wait a minute and try again."); + return; + } + if (web ? login.status != 200 : login.session == null) { + failed.failed(401, "That e-mail and password do not match an account."); + return; + } + // 2. The session, for an authorization code. + final Step authorize = new Step("GET", server + "/oauth2/authorize"); + if (web) { + // Or a session that did not take is answered with a page. + authorize.addRequestHeader("Accept", "application/json"); + } else { + authorize.addRequestHeader("Cookie", login.session); + } + authorize.addArgument("response_type", "code"); + authorize.addArgument("client_id", AppConfig.CLIENT_ID); + authorize.addArgument("redirect_uri", redirect); + authorize.addArgument("scope", "openid profile"); + authorize.addArgument("state", state); + authorize.addArgument("code_challenge", pkce.getChallenge()); + authorize.addArgument("code_challenge_method", pkce.getMethod()); + authorize.send(() -> { + if (!server.equals(base)) { + failed.failed(0, "The server changed. Sign in again."); + return; + } + String code = web ? authorize.answer("code") + : parameter(authorize.location, "code"); + String returned = web ? authorize.answer("state") + : parameter(authorize.location, "state"); + // The state has to come back as it went: a code that arrives + // with another was not issued for this sign-in. + if (code == null || !state.equals(returned)) { + failed.failed(authorize.status, "Signing in failed. Try again."); + return; + } + // 3. The code, for tokens. + final Step token = new Step("POST", server + "/oauth2/token"); + token.addArgument("grant_type", "authorization_code"); + token.addArgument("code", code); + token.addArgument("redirect_uri", redirect); + token.addArgument("code_verifier", pkce.getVerifier()); + token.addArgument("client_id", AppConfig.CLIENT_ID); + token.send(() -> { + if (!server.equals(base)) { + failed.failed(0, "The server changed. Sign in again."); + return; + } + OidcTokens tokens = token.status == 200 ? token.tokens() : null; + if (tokens == null || tokens.getAccessToken() == null) { + failed.failed(token.status, "Signing in failed. Try again."); + return; + } + // 4. The session has done its work, and is ended rather + // than left to run out: in a browser it is a cookie that + // would go on signing this user in to whoever sat down + // next. Nothing waits on the answer; the tokens stand + // without it. + Step end = new Step("POST", server + "/logout"); + if (!web) { + end.addRequestHeader("Cookie", login.session); + } + end.send(() -> { }); + got.got(tokens); + }); + }); + }); + } + + /// Signs out: the refresh token is revoked at the server, so the session + /// is over there too and not only forgotten here. + public static void signOut(final Runnable done) { + OidcTokens tokens = authorizer.getTokens(); + if (tokens != null && tokens.getRefreshToken() != null) { + // Sent and not waited for. Signing out is something the user does + // to this phone, and it is done here whether or not the server + // answers: the tokens are gone from the device either way. A + // revocation that is lost leaves a refresh token only someone who + // already copied it off the phone could use, and it expires on + // its own; holding the sign-out until the network allows would + // trap the user signed in on a phone with no connection. + client.revoke(tokens.getRefreshToken()); + } + setUser(null); + session++; + authorizer.signOut().ready(new SuccessCallback() { + @Override + public void onSucess(Boolean cleared) { + done.run(); + } + }).except(new SuccessCallback() { + @Override + public void onSucess(Throwable err) { + done.run(); + } + }); + } + + /// A parameter of the query string of `url`, or null. + static String parameter(String url, String name) { + int query = url == null ? -1 : url.indexOf('?'); + if (query < 0) { + return null; + } + int at = query + 1; + while (at < url.length()) { + int end = url.indexOf('&', at); + if (end < 0) { + end = url.length(); + } + if (url.startsWith(name + "=", at)) { + return Util.decode(url.substring(at + name.length() + 1, end), "UTF-8", false); + } + at = end + 1; + } + return null; + } + + /// One request of the sign-in. It follows no redirect and keeps no cookie + /// jar, because the redirect and the cookie are the answers it is after; + /// and it carries no bearer token, because there is not one yet. + private static final class Step extends ConnectionRequest { + int status; + String location; + String session; + private byte[] body; + private Runnable then; + private boolean reported; + + Step(String method, String url) { + setUrl(url); + setHttpMethod(method); + setPost(!"GET".equals(method)); + setFollowRedirects(false); + setCookiesEnabled(false); + setReadResponseForErrors(true); + setDuplicateSupported(true); + setFailSilently(true); + setAuthorizer(RequestAuthorizer.NONE); + } + + void send(Runnable next) { + then = next; + NetworkManager.getInstance().addToQueue(this); + } + + /// A text member of the JSON this request was answered with, or null. + String answer(String name) { + if (status != 200 || body == null) { + return null; + } + try { + Map json = new JSONParser().parseJSON(new InputStreamReader( + new ByteArrayInputStream(body), "UTF-8")); + Object value = json == null ? null : json.get(name); + return value instanceof String ? (String) value : null; + } catch (IOException malformed) { + return null; + } catch (RuntimeException malformed) { + return null; + } + } + + OidcTokens tokens() { + try { + Map json = new JSONParser().parseJSON(new InputStreamReader( + new ByteArrayInputStream(body == null ? new byte[0] : body), "UTF-8")); + return OidcTokens.fromTokenResponse(json, null); + } catch (IOException malformed) { + return null; + } catch (RuntimeException malformed) { + return null; + } + } + + @Override + protected void readHeaders(Object connection) throws IOException { + location = getHeader(connection, "Location"); + String[] cookies = getHeaders(connection, "Set-Cookie"); + for (int iter = 0; cookies != null && iter < cookies.length; iter++) { + if (cookies[iter] != null && cookies[iter].startsWith(SESSION_COOKIE + "=")) { + int end = cookies[iter].indexOf(';'); + session = end < 0 ? cookies[iter] : cookies[iter].substring(0, end); + } + } + } + + @Override + protected void handleErrorResponseCode(int code, String message) { + status = code; + } + + @Override + protected void readResponse(InputStream input) throws IOException { + if (status == 0) { + status = getResponseCode(); + } + body = Util.readInputStream(input); + } + + @Override + protected void postResponse() { + if (status == 0) { + status = getResponseCode(); + } + report(); + } + + @Override + protected void handleException(Exception err) { + status = 0; + report(); + } + + private void report() { + if (!reported) { + reported = true; + CN.callSerially(then); + } + } + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/Hud.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/Hud.java new file mode 100644 index 00000000000..1baceb6ce9a --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/Hud.java @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.play; + +import com.codenameone.examples.ledge.ui.Ui; +import com.codename1.gaming.platformer.Actor; +import com.codename1.gaming.platformer.PlatformWorld; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Font; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import com.codename1.ui.geom.Dimension; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; + +/// The strip over a run: hearts on the left, coins, the gem and the clock on +/// the right, all drawn with the game's own art so it reads as part of the +/// world rather than a form laid over it. +public final class Hud extends Component { + private final LedgeView view; + private final Image heart; + private final Image coin; + private final Image gem; + private final Image key; + private Font font; + private int rightInset; + private String banner; + private long bannerUntil; + + public Hud(LedgeView view) { + this.view = view; + setFocusable(false); + heart = LedgeArt.image("item_heart"); + coin = LedgeArt.image("item_coin").subImage(0, 0, LedgeArt.CELL, LedgeArt.CELL, true); + gem = LedgeArt.image("item_gem").subImage(0, 0, LedgeArt.CELL, LedgeArt.CELL, true); + key = LedgeArt.image("item_key"); + setUIID("Hud"); + } + + /// Keeps the right-hand readouts clear of a button in that corner. + public void setRightInset(int px) { + rightInset = px; + } + + /// Shows a line across the top for a few seconds, the level's name as it + /// starts. + public void banner(String text) { + banner = text; + bannerUntil = System.currentTimeMillis() + 2600; + repaint(); + } + + /// Formats a score with thin grouping, `12 345`. + public static String format(long n) { + String s = String.valueOf(Math.abs(n)); + StringBuilder b = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + if (i > 0 && (s.length() - i) % 3 == 0) { + b.append(' '); + } + b.append(s.charAt(i)); + } + return (n < 0 ? "-" : "") + b; + } + + private Font font() { + if (font == null) { + int px = Math.max(14, CN.convertToPixels(4.2f)); + Font ttf = Font.isTrueTypeFileSupported() ? Font.createTrueTypeFont("Lilita One", "LilitaOne-Regular.ttf") : null; + font = ttf != null ? ttf.derive(px, Font.STYLE_PLAIN) : Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE); + } + return font; + } + + @Override + public void paint(Graphics g) { + PlatformWorld w = view.getWorld(); + Actor p = w.getPlayer(); + Font f = font(); + g.setFont(f); + g.setAntiAliased(true); + g.setAntiAliasedText(true); + int icon = (int) (f.getHeight() * 1.15); + int pad = CN.convertToPixels(3f); + int top = getY() + pad + safeTop(); + int x = getX() + pad; + int hp = p != null && p.getHealth() != null ? p.getHealth().getCurrent() : 0; + int max = p != null && p.getHealth() != null ? p.getHealth().max : 0; + for (int i = 0; i < max; i++) { + g.setAlpha(i < hp ? 255 : 70); + g.drawImage(heart, x, top, icon, icon); + x += icon * 9 / 10; + } + g.setAlpha(255); + x += icon / 2; + if (w.getLives() > 0 && w.getLives() < 100) { + shadowed(g, "x" + w.getLives(), x, top + (icon - f.getHeight()) / 2); + } + for (int i = 0; i < w.getKeys().size(); i++) { + g.drawImage(key, x + f.stringWidth("x00") + i * icon, top, icon, icon); + } + // right side, laid out from the edge in; the clock gets a line of its + // own, centred, so a phone held upright never runs the two sides into + // each other + String time = Scoring.time(w.getTick()); + int rx = getX() + getWidth() - pad - rightInset; + int gems = view.getLevelIndex() >= 0 ? LevelPack.GEMS[view.getLevelIndex()] : 0; + if (gems > 0) { + rx -= icon; + g.setAlpha(w.getSecrets() > 0 ? 255 : 80); + g.drawImage(gem, rx, top, icon, icon); + g.setAlpha(255); + rx -= pad; + } + String coins = String.valueOf(w.getCoins()); + rx -= f.stringWidth(coins) + pad; + shadowed(g, coins, rx, top + (icon - f.getHeight()) / 2); + rx -= icon + pad / 3; + g.drawImage(coin, rx, top, icon, icon); + int clockY = top + icon + pad / 2; + shadowed(g, time, getX() + (getWidth() - f.stringWidth("0:00.00")) / 2, clockY); + if (banner != null && System.currentTimeMillis() < bannerUntil) { + int bw = f.stringWidth(banner); + shadowed(g, banner, getX() + (getWidth() - bw) / 2, clockY + f.getHeight() + pad); + } else { + banner = null; + String lead = lead(w); + if (lead != null) { + shadowed(g, lead, getX() + (getWidth() - f.stringWidth(lead)) / 2, clockY + f.getHeight() + pad); + } + } + } + + /// How far the hero is ahead of the ghost being raced, in tiles, or null + /// when there is no race. Distance rather than time: the two runs share a + /// clock, so the gap between them is where each one is now. + String lead(PlatformWorld w) { + java.util.List ghosts = view.getGhostWorlds(); + if (ghosts.isEmpty() || w.getPlayer() == null) { + return null; + } + PlatformWorld gw = ghosts.get(0); + if (gw.isComplete()) { + return w.isComplete() ? null : "Ghost is home"; + } + if (gw.getPlayer() == null) { + return null; + } + int tile = w.getGrid().getTileSize(); + int gap = w.getPlayer().getBody().x - gw.getPlayer().getBody().x; + // tenths of a tile, rounded half away from zero + int tenths = (int) (((long) Math.abs(gap) * 10 + tile / 2) / tile); + // a tile reads as a metre, the unit players think in + String n = (tenths / 10) + "." + (tenths % 10) + " m"; + if (tenths == 0) { + return "Level with the ghost"; + } + return gap > 0 ? "Ahead of the ghost by " + n : "Ghost leads by " + n; + } + + private int safeTop() { + return getComponentForm() == null ? 0 : getComponentForm().getSafeArea().getY(); + } + + private static void shadowed(Graphics g, String s, int x, int y) { + // An outline and a drop shadow, both at least two pixels: a one + // pixel shadow left white text unreadable over the skyway's light + // clouds. + int o = Math.max(2, Ui.mm(0.4f)); + g.setColor(0x2a1e30); + for (int dx = -1; dx <= 1; dx++) { + for (int dy = -1; dy <= 1; dy++) { + if (dx != 0 || dy != 0) { + g.drawString(s, x + dx * o / 2, y + dy * o / 2); + } + } + } + g.drawString(s, x + o, y + o); + g.setColor(0xffffff); + g.drawString(s, x, y); + } + + @Override + protected Dimension calcPreferredSize() { + // icons, the clock and one line under it for the banner or the race, + // below the safe area + int icon = font().getHeight(); + return new Dimension(CN.getDisplayWidth(), safeTop() + icon * 4 + CN.convertToPixels(4)); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/LedgeArt.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/LedgeArt.java new file mode 100644 index 00000000000..10d6a95dbbb --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/LedgeArt.java @@ -0,0 +1,335 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.play; + +import com.codename1.gaming.SpriteSheet; +import com.codename1.gaming.platformer.Actor; +import com.codename1.gaming.platformer.Entity; +import com.codename1.gaming.platformer.MovementState; +import com.codename1.gaming.platformer.MovingPlatform; +import com.codename1.gaming.platformer.Pickup; +import com.codename1.gaming.platformer.Projectile; +import com.codename1.gaming.platformer.Tile; +import com.codename1.gaming.platformer.TileGrid; +import com.codename1.gaming.platformer.view.ActorAnimator; +import com.codename1.gaming.platformer.view.PlatformArt; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +/// Ledge's look: the images `tools/make-art.py` draws, bound to the engine. +/// +/// This is the only class that knows file names and atlas layouts, so a new +/// skin is a new set of PNGs (or a subclass of this). Every image is in art +/// pixels -- `ART_SCALE` per world pixel -- and the view scales it down. +public class LedgeArt implements PlatformArt { + /// Art pixels per world pixel: a 16 px tile is drawn from a 64 px cell. + public static final int ART_SCALE = 4; + /// The side of an atlas cell. + public static final int CELL = 64; + + private static final int HERO_IDLE = 0; + private static final int HERO_RUN = 2; + private static final int HERO_JUMP = 6; + private static final int HERO_FALL = 7; + private static final int HERO_CROUCH = 8; + private static final int HERO_CLIMB = 9; + private static final int HERO_HURT = 11; + private static final int HERO_DASH = 12; + private static final int HERO_CLING = 13; + private static final int HERO_GLIDE = 14; + private static final int HERO_JET = 15; + private static final int HERO_SWIM = 16; + /// The hero's cheering frame, for the result screen. + public static final int HERO_CHEER = 17; + + private static final Map FILES = new HashMap(); + + private final String theme; + private final Image[] cells = new Image[32]; + private final Map sheets = new HashMap(); + private final Map animators = new HashMap(); + private final Map platforms = new HashMap(); + private final SpriteSheet coin; + private final SpriteSheet gem; + private final SpriteSheet goal; + + /// Creates the art for a world. + /// + /// #### Parameters + /// + /// - `theme`: `meadow`, `cavern`, `foundry`, `sky` or `forge` + public LedgeArt(String theme) { + this.theme = theme; + Image atlas = image("tiles_" + theme); + for (int i = 0; i < cells.length; i++) { + int x = (i % 8) * CELL; + int y = (i / 8) * CELL; + if (atlas != null && y + CELL <= atlas.getHeight()) { + cells[i] = atlas.subImage(x, y, CELL, CELL, true); + } + } + coin = new SpriteSheet(image("item_coin"), CELL, CELL); + gem = new SpriteSheet(image("item_gem"), CELL, CELL); + goal = new SpriteSheet(image("item_goal"), 96, 160); + } + + /// One cell of the world's tile atlas, in the order `tools/make-art.py` + /// lays it out: 0 to 15 solid ground by open sides, 16 to 21 slopes, 22 + /// to 25 ledges, then ladder, spikes and water. + /// + /// #### Parameters + /// + /// - `i`: the cell + /// + /// #### Returns + /// + /// the image, or null when the atlas is missing + public Image cell(int i) { + return i >= 0 && i < cells.length ? cells[i] : null; + } + + /// The world this art draws. + public String getTheme() { + return theme; + } + + /// Loads a PNG from the resources once; later calls share it. + /// + /// #### Parameters + /// + /// - `name`: the file name without `.png` + /// + /// #### Returns + /// + /// the image, or null if there is no such file + public static Image image(String name) { + Image img = FILES.get(name); + if (img == null && !FILES.containsKey(name)) { + // CN, not Class: on ParparVM (iOS) Class.getResourceAsStream does not + // read the application's bundled files and answers null. + InputStream in = com.codename1.ui.CN.getResourceAsStream("/" + name + ".png"); + if (in != null) { + try { + img = Image.createImage(in); + } catch (IOException e) { + com.codename1.io.Log.e(e); + img = null; + } finally { + try { + in.close(); + } catch (IOException ignored) { + // nothing more to do + } + } + } else { + com.codename1.io.Log.p("LedgeArt: no resource /" + name + ".png"); + } + FILES.put(name, img); + } + return img; + } + + private static boolean ground(int k) { + return k == Tile.SOLID || Tile.isSlope(k); + } + + @Override + public Image tile(TileGrid g, int c, int r) { + int k = g.get(c, r); + switch (k) { + case Tile.SOLID: { + int mask = 0; + if (!ground(g.get(c, r - 1))) { + mask |= 1; + } + if (!ground(g.get(c + 1, r))) { + mask |= 2; + } + if (g.get(c, r + 1) != Tile.SOLID && r + 1 < g.getRows()) { + mask |= 4; + } + if (!ground(g.get(c - 1, r))) { + mask |= 8; + } + return cells[mask]; + } + case Tile.SLOPE_UP: + return cells[16]; + case Tile.SLOPE_DOWN: + return cells[17]; + case Tile.SLOPE_UP_LOW: + return cells[18]; + case Tile.SLOPE_UP_HIGH: + return cells[19]; + case Tile.SLOPE_DOWN_HIGH: + return cells[20]; + case Tile.SLOPE_DOWN_LOW: + return cells[21]; + case Tile.ONE_WAY: { + int ends = (g.get(c - 1, r) != Tile.ONE_WAY ? 1 : 0) | (g.get(c + 1, r) != Tile.ONE_WAY ? 2 : 0); + return cells[22 + ends]; + } + case Tile.LADDER: + return cells[26]; + case Tile.HAZARD: + return cells[27]; + case Tile.WATER: + return cells[g.get(c, r - 1) == Tile.WATER ? 29 : 28]; + default: + return null; + } + } + + @Override + public SpriteSheet sheet(Actor actor) { + String kind = actor.getKind(); + SpriteSheet s = sheets.get(kind); + if (s == null) { + Image img = image("hero".equals(kind) ? "hero" : "enemy_" + kind); + if (img == null) { + img = image("enemy_slime"); + } + int h = img.getHeight(); + s = new SpriteSheet(img, h, h); + sheets.put(kind, s); + } + return s; + } + + @Override + public ActorAnimator animator(Actor actor) { + String kind = actor.getKind(); + ActorAnimator a = animators.get(kind); + if (a == null) { + a = "hero".equals(kind) ? heroAnimator() : enemyAnimator(kind, sheet(actor).getFrameCount()); + animators.put(kind, a); + } + return a; + } + + private static ActorAnimator heroAnimator() { + return new ActorAnimator() + .set(MovementState.IDLE, 32, true, HERO_IDLE, HERO_IDLE + 1) + .set(MovementState.WALKING, 7, true, HERO_RUN, HERO_RUN + 1, HERO_RUN + 2, HERO_RUN + 3) + .set(MovementState.RUNNING, 4, true, HERO_RUN, HERO_RUN + 1, HERO_RUN + 2, HERO_RUN + 3) + .set(MovementState.JUMPING, 1, false, HERO_JUMP) + .set(MovementState.FALLING, 1, false, HERO_FALL) + .set(MovementState.CROUCHING, 1, false, HERO_CROUCH) + .set(MovementState.CRAWLING, 10, true, HERO_CROUCH, HERO_IDLE) + .set(MovementState.WALL_CLINGING, 1, false, HERO_CLING) + .set(MovementState.DASHING, 1, false, HERO_DASH) + .set(MovementState.CLIMBING, 9, true, HERO_CLIMB, HERO_CLIMB + 1) + .set(MovementState.JETPACKING, 1, false, HERO_JET) + .set(MovementState.GLIDING, 1, false, HERO_GLIDE) + .set(MovementState.SWIMMING, 12, true, HERO_SWIM, HERO_FALL) + .set(MovementState.GRIPPING, 1, false, HERO_CLING) + .set(MovementState.PUSHING, 6, true, HERO_RUN, HERO_RUN + 1, HERO_RUN + 2, HERO_RUN + 3) + .set(MovementState.HURT, 1, false, HERO_HURT); + } + + private static ActorAnimator enemyAnimator(String kind, int frames) { + ActorAnimator a = new ActorAnimator(); + if ("frog".equals(kind)) { + return a.set(MovementState.IDLE, 20, true, 0, 1) + .set(MovementState.WALKING, 20, true, 0, 1) + .set(MovementState.JUMPING, 1, false, 2) + .set(MovementState.FALLING, 1, false, 2) + .set(MovementState.HURT, 1, false, 1); + } + int walk = "golem".equals(kind) ? 4 : frames; + int[] loop = new int[walk]; + for (int i = 0; i < walk; i++) { + loop[i] = i; + } + int speed = "bat".equals(kind) ? 5 : "turret".equals(kind) ? 10 : 9; + a.set(MovementState.IDLE, speed * 2, true, loop) + .set(MovementState.WALKING, speed, true, loop) + .set(MovementState.RUNNING, Math.max(3, speed / 2), true, loop) + .set(MovementState.JUMPING, speed, true, loop) + .set(MovementState.FALLING, speed, true, loop); + a.set(MovementState.HURT, 1, false, "golem".equals(kind) ? 5 : 0); + return a; + } + + @Override + public Image entity(Entity e, int tick) { + String t = e.getType(); + int phase = e.getPhase(); + if ("coin".equals(t)) { + return coin.getFrame((tick / 5) % coin.getFrameCount()); + } + if ("gem".equals(t)) { + return gem.getFrame((tick / 9) % gem.getFrameCount()); + } + if ("heart".equals(t) || "life".equals(t) || "key".equals(t)) { + return image("item_" + t); + } + if ("powerup".equals(t)) { + String name = e instanceof Pickup ? ((Pickup) e).getName() : null; + Image img = name == null ? null : image("item_power_" + name); + return img != null ? img : image("item_power_weapon"); + } + if ("spring".equals(t) || "checkpoint".equals(t) || "lever".equals(t) || "plate".equals(t)) { + return image("item_" + t + Math.min(1, phase)); + } + if ("door".equals(t) || "gate".equals(t)) { + return phase == 0 ? image("item_" + t) : null; + } + if ("crumble".equals(t)) { + return phase >= 3 ? null : image("item_crumble" + phase); + } + if (e instanceof Projectile) { + return image("orb".equals(t) ? "shot_orb" : "shot_bolt"); + } + return null; + } + + @Override + public Image platform(MovingPlatform p) { + int w = Math.max(CELL, (p.getWidth() >> 16) * ART_SCALE); + int h = Math.max(8, (p.getHeight() >> 16) * ART_SCALE); + String key = w + "x" + h; + Image img = platforms.get(key); + if (img == null) { + Image src = image("platform_" + theme); + img = Image.createImage(w, h, 0); + Graphics g = img.getGraphics(); + g.setAntiAliased(true); + int sh = src.getHeight(); + int cap = Math.min(CELL, w / 2); + // a three-slice: the two ends at their own size, the middle stretched + g.drawImage(src.subImage(0, 0, cap, sh, true), 0, 0, cap, h); + g.drawImage(src.subImage(src.getWidth() - cap, 0, cap, sh, true), w - cap, 0, cap, h); + if (w > cap * 2) { + g.drawImage(src.subImage(CELL, 0, CELL, sh, true), cap, 0, w - cap * 2, h); + } + platforms.put(key, img); + } + return img; + } + + @Override + public Image goal(int width, int height, int tick) { + return goal.getFrame((tick / 7) % goal.getFrameCount()); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/LedgeView.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/LedgeView.java new file mode 100644 index 00000000000..5acf6d4ade3 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/LedgeView.java @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.play; + +import com.codename1.gaming.TouchControls; +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.LevelData; +import com.codename1.gaming.platformer.PlatformWorld; +import com.codename1.gaming.platformer.WeaponAbility; +import com.codename1.gaming.platformer.WorldEvent; +import com.codename1.gaming.platformer.view.Feedback; +import com.codename1.gaming.platformer.view.PlatformView; +import com.codename1.ui.CN; +import com.codename1.ui.Image; +import com.codenameone.examples.ledge.levels.LevelPack; + +/// One level being played: the engine's `PlatformView` with Ledge's art, its +/// sounds, its touch controls, and a recorder. +/// +/// Every tick's input is written to an `InputLog`. That log is the run: the +/// server replays it to verify the score, and it becomes the ghost other +/// players race. An autopilot log can drive the hero instead of the player -- +/// the title screen's attract mode and the screenshot tests use the demo log +/// `LevelPack` ships for every level. +public class LedgeView extends PlatformView { + /// Told about a run as it goes. + public interface Host { + /// The score, coins, lives or keys changed. Called on the EDT. + void hudChanged(LedgeView view); + + /// The level was finished or the last life lost. Called on the EDT. + void finished(LedgeView view); + } + + /// Rows of tiles the screen shows top to bottom. + public static final double VISIBLE_ROWS = 11.5; + + private final int index; + private final long seed; + private final InputLog log = new InputLog(); + private Host host; + private int[] autopilot; + private boolean reported; + private int lastScore = -1; + private int lastCoins = -1; + private int lastLives = -1; + private int lastHealth = -1; + private int lastKeys = -1; + + /// Creates the view for a level. + /// + /// #### Parameters + /// + /// - `index`: the level index in `LevelPack` + /// - `seed`: the run's seed, from the server's ticket + public LedgeView(int index, long seed) { + this(index, seed, LevelPack.load(index), LevelPack.THEMES[index], LevelPack.DEPTH[index]); + } + + /// Creates the view for a level that is not in the pack, such as one + /// being play-tested in the editor. + /// + /// #### Parameters + /// + /// - `level`: the level + /// - `theme`: the world it is drawn as + /// - `depth`: true for 2.5D + /// - `seed`: the run's seed + public LedgeView(LevelData level, String theme, boolean depth, long seed) { + this(-1, seed, level, theme, depth); + } + + private LedgeView(int index, long seed, LevelData level, String theme, boolean depth) { + super(level.createWorld(seed), new LedgeArt(theme)); + this.index = index; + this.seed = seed; + setArtScale(LedgeArt.ART_SCALE); + setVisibleRows(VISIBLE_ROWS); + setFeedbackSink(new Feedback.Sink() { + @Override + public void sound(String name, double x, double y) { + if (!"pickup".equals(name)) { + // pickups are voiced by onEvent, which knows what was picked up + Sfx.play(name); + } + } + + @Override + public void burst(double x, double y, int count, int color) { + // The view draws its own sprite particles for every burst. + } + }); + double levelHeight = getWorld().getGrid().getRows() * (getWorld().getGrid().getTileSize() >> 16); + Image far = LedgeArt.image("bg_" + theme + "_0"); + if (far != null) { + // Clear to the far backdrop's own top colour, so a camera that + // looks above the backdrops -- the 2.5D view does, climbing -- + // sees more sky rather than black. + setClearColor(0xff000000 | far.subImage(0, 0, 1, 1, false).getRGB()[0]); + } + float[] factors = {0.08f, 0.3f, 0.55f}; + for (int i = 0; i < factors.length; i++) { + Image bg = LedgeArt.image("bg_" + theme + "_" + i); + if (bg != null) { + // Each backdrop is 1024 art pixels tall; rest its bottom on the + // level's floor so the far hills never show a gap under them. + addBackground(bg, factors[i], levelHeight - bg.getHeight() / (double) LedgeArt.ART_SCALE); + } + } + if (depth) { + // Blocks wear the world's own tiles: grass-topped ground (open on + // top only) and a ledge with both ends. Spikes and ladders are + // thin shapes that read better in flat colour. + LedgeArt a = (LedgeArt) getArt(); + // The ledge tile is a plank across the top quarter of the cell + // with pegs hanging under it; a ledge block is that quarter tall, + // so it wears the plank alone. The whole cell, squeezed onto it, + // drew the pegs as dark streaks. + Image ledge = a.cell(25); + if (ledge != null) { + ledge = ledge.subImage(0, 0, ledge.getWidth(), Math.max(1, ledge.getHeight() / 4), true); + } + setDepthTextures(a.cell(1), ledge, null, null); + setDepthColors(0xffffffff, 0xffffffff, 0xffe8ecf4, 0xffc9945a); + } + setDepth(depth); + setInputSource(new InputSource() { + private final int[] one = new int[1]; + + @Override + public int[] next(PlatformWorld world, int local) { + int t = world.getTick(); + int bits = autopilot != null ? (t < autopilot.length ? autopilot[t] : 0) : local; + log.add(bits); + one[0] = bits; + return one; + } + }); + if (!CN.isDesktop()) { + addTouchControls(); + } + } + + private void addTouchControls() { + TouchControls tc = getControls(); + float unit = Math.min(CN.getDisplayWidth(), CN.getDisplayHeight()) / 10f; + tc.addJoystick(unit * 1.15f, TouchControls.LEFT, TouchControls.BOTTOM, unit * 0.5f); + tc.addButton(' ', unit * 0.85f, TouchControls.RIGHT, TouchControls.BOTTOM, unit * 0.45f, unit * 0.5f) + .setLabel("JUMP"); + tc.addButton('z', unit * 0.6f, TouchControls.RIGHT, TouchControls.BOTTOM, unit * 2.4f, unit * 0.35f) + .setLabel("DASH"); + if (getWorld().getPlayer().getAbility(WeaponAbility.class) != null) { + tc.addButton('x', unit * 0.6f, TouchControls.RIGHT, TouchControls.BOTTOM, unit * 0.6f, unit * 2.25f) + .setLabel("FIRE"); + } + } + + /// Hands the hero to a recorded input instead of the player. + /// + /// #### Parameters + /// + /// - `encoded`: an `InputLog` encoding, or null to give control back + public void setAutopilot(String encoded) { + autopilot = encoded == null || encoded.length() == 0 ? null + : InputLog.decode(encoded, 1 << 20).toArray(); + getControls().setVisible(autopilot == null); + } + + /// Races a recorded run: the ghost plays the same level, from the same + /// seed, tick for tick beside the live hero. Add it before the run starts. + /// + /// #### Parameters + /// + /// - `seed`: the seed the ghost's run was played with + /// - `encoded`: its input, in `InputLog` encoding + public void race(long seed, String encoded) { + if (encoded == null || encoded.length() == 0 || index < 0) { + return; + } + addGhost(LevelPack.load(index).createWorld(seed), InputLog.decode(encoded, 1 << 20).toArray(), 110); + } + + public boolean isAutopilot() { + return autopilot != null; + } + + public void setHost(Host host) { + this.host = host; + } + + /// The level's index in `LevelPack`, or -1 for a level from the editor. + public int getLevelIndex() { + return index; + } + + public long getSeed() { + return seed; + } + + /// The input recorded so far. + public InputLog getLog() { + return log; + } + + @Override + protected void onTick(int localInput) { + PlatformWorld w = getWorld(); + int health = w.getPlayer() != null && w.getPlayer().getHealth() != null + ? w.getPlayer().getHealth().getCurrent() : 0; + if (w.getScore() != lastScore || w.getCoins() != lastCoins || w.getLives() != lastLives + || health != lastHealth || w.getKeys().size() != lastKeys) { + lastScore = w.getScore(); + lastCoins = w.getCoins(); + lastLives = w.getLives(); + lastHealth = health; + lastKeys = w.getKeys().size(); + if (host != null) { + CN.callSerially(() -> host.hudChanged(this)); + } + } + if (!reported && (w.isComplete() || w.isGameOver())) { + reported = true; + if (host != null) { + CN.callSerially(() -> host.finished(this)); + } + } + } + + @Override + protected void onEvent(WorldEvent e) { + if (e.getType() != WorldEvent.PICKUP) { + return; + } + String what = e.getDetail(); + if ("coin".equals(what)) { + // A rising pitch over a row of coins, as the genre expects. + Sfx.play("coin", 0.8f, 1f + (getWorld().getCoins() % 8) * 0.06f); + } else if ("gem".equals(what)) { + Sfx.play("gem"); + } else { + Sfx.play("pickup"); + } + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/Sfx.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/Sfx.java new file mode 100644 index 00000000000..7cdaaedd88a --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/play/Sfx.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.play; + +import com.codename1.gaming.SoundEffect; +import com.codename1.gaming.SoundPool; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +/// The game's sounds, by the names `com.codename1.gaming.platformer.view.Feedback` +/// asks for. Every one is synthesised by `tools/make-art.py`. +public final class Sfx { + private static final String[] NAMES = {"jump", "land", "coin", "gem", "hurt", "death", "stomp", "fire", + "impact", "checkpoint", "bounce", "open", "crumble", "dash", "complete", "gameover", "switch", + "pickup", "ui"}; + /// The shortest gap between two plays of one sound, in milliseconds, so a + /// row of coins sounds like a run of notes and not a buzz. + private static final int MIN_GAP = 45; + private static final Map EFFECTS = new HashMap(); + private static final Map LAST = new HashMap(); + private static SoundPool pool; + private static boolean muted; + + private Sfx() { + } + + /// Loads every sound once. Harmless to call again, and silent where the port + /// has no low-latency audio. + public static void load() { + if (pool != null) { + return; + } + try { + SoundPool created = SoundPool.create(12); + if (!created.isNativeAccelerated()) { + return; + } + for (String n : NAMES) { + // CN, not Class: on ParparVM (iOS) Class.getResourceAsStream does not + // read the application's bundled files and answers null. + InputStream in = com.codename1.ui.CN.getResourceAsStream("/sfx_" + n + ".wav"); + if (in != null) { + EFFECTS.put(n, created.load(in, "audio/wav")); + } + } + pool = created; + } catch (Throwable unavailable) { + pool = null; + } + } + + public static boolean isMuted() { + return muted; + } + + public static void setMuted(boolean m) { + muted = m; + } + + /// Plays a sound at full volume. + public static void play(String name) { + play(name, 1f, 1f); + } + + /// Plays a sound. Unknown names are ignored. + public static void play(String name, float volume, float rate) { + if (muted || pool == null) { + return; + } + SoundEffect fx = EFFECTS.get(name); + if (fx == null) { + return; + } + long now = System.currentTimeMillis(); + Long last = LAST.get(name); + if (last != null && now - last.longValue() < MIN_GAP) { + return; + } + LAST.put(name, Long.valueOf(now)); + try { + pool.play(fx, volume, 0f, rate, 0); + } catch (Throwable ignored) { + // Sound is decoration; a failure must never stop a run. + } + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/AchievementsForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/AchievementsForm.java new file mode 100644 index 00000000000..1f67e0b7763 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/AchievementsForm.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.appkit.Net; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.ledge.api.AchievementDto; +import com.codenameone.examples.ledge.net.Api; +import java.util.List; + +/// Goals, worked out by the server from the runs it accepted, so they cannot +/// be unlocked by a run it refused. +public final class AchievementsForm { + private AchievementsForm() { + } + + public static void show() { + Form f = Ui.form("Achievements", "achievements"); + Ui.desktopColumn(f); + Ui.back(f, Nav::home); + final Container list = new Container(BoxLayout.y()); + f.add(list); + Api.progress().achievements(Net.to(rows -> Ui.later(() -> fill(list, rows)), Ui::failed)); + f.show(); + } + + private static void fill(Container list, List rows) { + for (AchievementDto a : rows) { + Container row = new Container(new BorderLayout(), a.unlocked() ? "RowMe" : "Row"); + Label icon = new Label("", "Accent"); + FontImage.setMaterialIcon(icon, a.unlocked() ? FontImage.MATERIAL_EMOJI_EVENTS + : FontImage.MATERIAL_LOCK_OUTLINE, 5); + row.add(BorderLayout.WEST, icon); + Container text = BoxLayout.encloseY(new Label(a.name()), new Label(a.description(), "Muted")); + row.add(BorderLayout.CENTER, text); + if (!a.unlocked() && a.goal() > 0) { + row.add(BorderLayout.SOUTH, Ui.bar((int) Math.min(a.progress(), a.goal()), + (int) a.goal(), 0xd4483c)); + } + list.add(row); + } + list.revalidate(); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/EditorForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/EditorForm.java new file mode 100644 index 00000000000..7be7bcd5548 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/EditorForm.java @@ -0,0 +1,632 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.appkit.Net; +import com.codename1.gaming.platformer.Actor; +import com.codename1.gaming.platformer.Entity; +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.LevelData; +import com.codename1.gaming.platformer.PlatformWorld; +import com.codename1.gaming.platformer.TileGrid; +import com.codename1.io.Storage; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Command; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Dialog; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.ledge.api.GenerateDto; +import com.codenameone.examples.ledge.levels.LevelGenerator; +import com.codenameone.examples.ledge.levels.LevelSketch; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.net.Api; +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.play.LedgeArt; +import com.codenameone.examples.ledge.play.LedgeView; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/// The level editor. A level is a sketch -- sixteen rows of characters under a +/// JSON header, the format the shipped levels are written in -- painted with +/// the game's own art, play-tested in the real view, and proven finishable by +/// the same solver the server trusts. A description typed in becomes a level +/// through the server's model; offline, the piece generator makes one. +public final class EditorForm extends Form { + static final String STORE = "ledge-editor.sketch"; + static final long BUDGET = 20_000_000L; + static final String TILES = "#=/\\H^~."; + static final String[] THEMES = {"meadow", "cavern", "foundry", "sky", "forge"}; + + private String header; + private final List rows = new ArrayList(); + private char brush = '#'; + private boolean painting = true; + private PlatformWorld world; + private LedgeArt art; + private String proof; + private final Canvas canvas = new Canvas(); + private final com.codename1.components.SpanLabel status = Ui.text("", "EditorStatus"); + private final Container palette = new Container(BoxLayout.x()); + private Button modeButton; + private Button watchButton; + private int generation; + private final java.util.Map icons = new java.util.HashMap(); + + private EditorForm(String sketch) { + super("Level editor", new BorderLayout()); + setName("editor"); + setUIID("Form"); + getToolbar().setUIID("Toolbar"); + getToolbar().getTitleComponent().setUIID("Title"); + setTitle(Ui.caps("Level editor")); + setScrollable(false); + Ui.back(this, () -> { + save(); + Nav.home(); + }); + load(sketch); + canvas.setName("editorCanvas"); + palette.setScrollableX(true); + palette.setName("palette"); + buildPalette(); + + modeButton = tool(FontImage.MATERIAL_BRUSH, "Paint", "mode", e -> setPainting(!painting)); + Button theme = tool(FontImage.MATERIAL_PALETTE, "World", "theme", e -> nextTheme()); + Button wider = tool(FontImage.MATERIAL_ADD_BOX, "Wider", "wider", e -> widen(10)); + Button surprise = tool(FontImage.MATERIAL_CASINO, "Dice", "surprise", e -> surprise()); + Button ai = tool(FontImage.MATERIAL_AUTO_AWESOME, "Ask AI", "describe", e -> describe()); + Button check = tool(FontImage.MATERIAL_VERIFIED, "Check", "check", e -> check()); + watchButton = tool(FontImage.MATERIAL_SMART_DISPLAY, "Watch", "watch", e -> play(true)); + watchButton.setEnabled(false); + Button play = tool(FontImage.MATERIAL_PLAY_ARROW, "Play", "playTest", e -> play(false)); + Container actions = new Container(new GridLayout(1, 8)); + actions.addAll(modeButton, theme, wider, surprise, ai, check, watchButton, play); + + status.setName("editorStatus"); + Container south = BoxLayout.encloseY(palette, actions, status); + south.setUIID("EditorBar"); + add(BorderLayout.CENTER, canvas); + add(BorderLayout.SOUTH, south); + rebuild(); + say("Paint with the brushes; Check proves the level can be won"); + } + + /// Opens the editor on the level left in it last time, or a fresh one. + public static void open() { + String saved = null; + try { + Object o = Storage.getInstance().readObject(STORE); + saved = o instanceof String ? (String) o : null; + } catch (RuntimeException e) { + saved = null; + } + new EditorForm(saved != null ? saved : blank()).show(); + } + + /// A short field of grass with the start and the goal on it. + static String blank() { + StringBuilder sb = new StringBuilder(); + sb.append("{\"name\": \"My level\", \"theme\": \"meadow\", \"par\": 45, \"health\": 3, \"tuning\": {\"maxJumps\": 2},\n ") + .append("\"abilities\": [\"move\", \"jump\", \"crouch\", \"dash\", \"walljump\", \"ladder\"]}\n---\n"); + int width = 60; + for (int r = 0; r < LevelGenerator.ROWS; r++) { + for (int c = 0; c < width; c++) { + char ch = '.'; + if (r >= LevelGenerator.ROWS - 2) { + ch = '#'; + } else if (r == LevelGenerator.ROWS - 3 && c == 2) { + ch = 'S'; + } else if (r == LevelGenerator.ROWS - 3 && c == width - 4) { + ch = 'X'; + } + sb.append(ch); + } + sb.append('\n'); + } + return sb.toString(); + } + + private void load(String sketch) { + String text = sketch.replace("\r\n", "\n"); + int cut = text.indexOf("\n---\n"); + if (cut < 0) { + text = blank(); + cut = text.indexOf("\n---\n"); + } + header = text.substring(0, cut); + rows.clear(); + String body = text.substring(cut + 5); + int start = 0; + while (start < body.length() && rows.size() < LevelGenerator.ROWS) { + int nl = body.indexOf('\n', start); + rows.add(new StringBuilder(nl < 0 ? body.substring(start) : body.substring(start, nl))); + start = nl < 0 ? body.length() : nl + 1; + } + int width = 0; + for (StringBuilder r : rows) { + width = Math.max(width, r.length()); + } + while (rows.size() < LevelGenerator.ROWS) { + rows.add(new StringBuilder()); + } + for (StringBuilder r : rows) { + while (r.length() < width) { + r.append('.'); + } + } + proof = null; + if (watchButton != null) { + watchButton.setEnabled(false); + } + canvas.scroll = 0; + } + + /// The sketch as text. + String sketch() { + StringBuilder sb = new StringBuilder(header).append("\n---\n"); + for (StringBuilder r : rows) { + sb.append(r).append('\n'); + } + return sb.toString(); + } + + String theme() { + String key = "\"theme\": \""; + int at = header.indexOf(key); + if (at < 0) { + return "meadow"; + } + int end = header.indexOf('"', at + key.length()); + String t = end < 0 ? "meadow" : header.substring(at + key.length(), end); + for (String known : THEMES) { + if (known.equals(t)) { + return t; + } + } + return "meadow"; + } + + private void nextTheme() { + String now = theme(); + int i = 0; + while (i < THEMES.length && !THEMES[i].equals(now)) { + i++; + } + String next = THEMES[(i + 1) % THEMES.length]; + String key = "\"theme\": \""; + int at = header.indexOf(key); + if (at < 0) { + header = header.substring(0, 1) + key + next + "\", " + header.substring(1); + } else { + int end = header.indexOf('"', at + key.length()); + header = header.substring(0, at + key.length()) + next + header.substring(end); + } + art = null; + buildPalette(); + edited(); + say("World: " + Ui.caps(next) + ("sky".equals(next) ? " (2.5D)" : "")); + } + + private void setPainting(boolean on) { + painting = on; + modeButton.setText(on ? "Paint" : "Pan"); + FontImage.setMaterialIcon(modeButton, on ? FontImage.MATERIAL_BRUSH : FontImage.MATERIAL_PAN_TOOL, 3.5f); + modeButton.getParent().revalidate(); + } + + private void widen(int cols) { + for (int r = 0; r < rows.size(); r++) { + StringBuilder row = rows.get(r); + char fill = r >= rows.size() - 2 ? '#' : '.'; + for (int i = 0; i < cols; i++) { + row.append(fill); + } + } + edited(); + } + + /// Puts the brush at a cell. Only one start and one goal may exist, so + /// painting either moves it. + void put(int c, int r) { + if (r < 0 || r >= rows.size() || c < 0 || c >= rows.get(r).length() || rows.get(r).charAt(c) == brush) { + return; + } + if (brush == 'S' || brush == 'X') { + for (StringBuilder row : rows) { + for (int i = 0; i < row.length(); i++) { + if (row.charAt(i) == brush) { + row.setCharAt(i, '.'); + } + } + } + } + rows.get(r).setCharAt(c, brush); + edited(); + } + + private void edited() { + proof = null; + watchButton.setEnabled(false); + rebuild(); + canvas.repaint(); + } + + /// Recompiles the sketch into a world for drawing. A sketch the compiler + /// refuses keeps the last world on screen and says why. + private void rebuild() { + try { + world = LevelData.parse(LevelSketch.compile(sketch())).createWorld(7); + } catch (RuntimeException e) { + say("Not a level yet: " + e.getMessage()); + } + } + + private LedgeArt art() { + if (art == null) { + art = new LedgeArt(theme()); + } + return art; + } + + private void buildPalette() { + palette.removeAll(); + String all = TILES + LevelSketch.THINGS; + for (int i = 0; i < all.length(); i++) { + final char ch = all.charAt(i); + Button b = new Button("", ch == brush ? "BrushOn" : "Brush"); + b.setName("brush-" + (int) ch); + Image icon = icon(ch); + if (icon != null) { + b.setIcon(icon); + } else if (ch == '.') { + FontImage.setMaterialIcon(b, FontImage.MATERIAL_BACKSPACE, Ui.iconMm(4.5f)); + } else { + b.setText(String.valueOf(ch)); + } + b.addActionListener(e -> { + brush = ch; + setPainting(true); + for (int k = 0; k < palette.getComponentCount(); k++) { + Component other = palette.getComponentAt(k); + other.setUIID(other == b ? "BrushOn" : "Brush"); + } + palette.repaint(); + }); + palette.add(b); + } + palette.revalidate(); + } + + /// A brush's picture: the game's art for that tile, or for the thing the + /// letter places, read out of a one-cell level holding just it. + private Image icon(char ch) { + String key = theme() + ch; + if (!icons.containsKey(key)) { + icons.put(key, drawIcon(ch)); + } + return icons.get(key); + } + + private Image drawIcon(char ch) { + int size = Ui.mm(7); + Image img = null; + LedgeArt a = art(); + int t = TILES.indexOf(ch); + if (t >= 0) { + int[] cells = {1, 25, 16, 17, 26, 27, 29}; + img = t < cells.length ? a.cell(cells[t]) : null; + } else { + try { + StringBuilder sb = new StringBuilder(header).append("\n---\n"); + String marks = ch == 'S' ? "S...X" : ch == 'X' ? "S...X" : "S." + ch + ".X"; + // A full-height level: a tall thing such as a gate reaches + // up from its cell, and in a four-row probe it reached past + // the top and the level was refused. + for (int r = 0; r < 13; r++) { + sb.append("......\n"); + } + sb.append(marks).append(".\n######\n######\n"); + PlatformWorld w = LevelData.parse(LevelSketch.compile(sb.toString())).createWorld(1); + if (ch == 'S') { + img = a.sheet(w.getPlayer()).getFrame(0); + } else if (ch == 'X') { + img = a.goal(1, 1, 0); + } else { + for (Entity e : w.getEntities()) { + Image ei = a.entity(e, 0); + if (ei != null) { + img = ei; + break; + } + } + if (img == null) { + for (Actor actor : w.getActors()) { + if (actor != w.getPlayer()) { + img = a.sheet(actor).getFrame(0); + break; + } + } + } + } + } catch (RuntimeException e) { + com.codename1.io.Log.p("Editor: no icon for '" + ch + "': " + e); + img = null; + } + } + return img == null ? null : img.scaled(size, size); + } + + private Button tool(char icon, String text, String name, com.codename1.ui.events.ActionListener go) { + Button b = new Button(text, "EditorTool"); + b.setName(name); + b.setTextPosition(Component.BOTTOM); + FontImage.setMaterialIcon(b, icon, 3.5f); + b.addActionListener(go); + return b; + } + + void say(String text) { + status.setText(text); + if (status.getParent() != null) { + status.getParent().revalidate(); + } + } + + /// Runs the solver off the EDT; a later edit makes its answer stale, and a + /// stale answer is dropped. + private void check() { + final String sk = sketch(); + final int mine = ++generation; + say("Looking for a way through..."); + CN.startThread(() -> { + final InputLog run = LevelGenerator.check(sk, BUDGET); + CN.callSerially(() -> { + if (mine != generation || !sk.equals(sketch())) { + return; + } + if (run == null) { + say("No way through was found; open a gap or lower a wall"); + return; + } + proof = run.encode(); + watchButton.setEnabled(true); + say("It can be won: " + Scoring.time(run.length()) + " for the solver. Watch shows how"); + }); + }, "solver").start(); + } + + private void play(boolean watch) { + save(); + LevelData level; + try { + level = LevelData.parse(LevelSketch.compile(sketch())); + } catch (RuntimeException e) { + say("Not a level yet: " + e.getMessage()); + return; + } + final String keep = sketch(); + LedgeView view = new LedgeView(level, theme(), "sky".equals(theme()), 7); + if (watch && proof != null) { + view.setAutopilot(proof); + } + PlayForm.test(view, watch ? "The solver's run" : "Play-test", () -> new EditorForm(keep).showBack()).show(); + } + + private void surprise() { + generateOffline("", new Random().nextInt(1 << 30)); + } + + private void generateOffline(final String words, final long seed) { + final int mine = ++generation; + say("Building a level..."); + CN.startThread(() -> { + final String sk = LevelGenerator.solvable(words, seed, BUDGET); + CN.callSerially(() -> { + if (mine != generation) { + return; + } + if (sk == null) { + say("Nothing finishable came out of that; try again"); + return; + } + adopt(sk, "A new level, already proven finishable"); + }); + }, "generator").start(); + } + + private void adopt(String sk, String message) { + load(sk); + art = null; + buildPalette(); + rebuild(); + canvas.repaint(); + save(); + say(message); + } + + private void describe() { + final TextField field = new TextField("", "A long cave with ladders and spikes", 40, TextField.ANY); + field.setName("describeField"); + Command make = new Command("Make it"); + Command cancel = new Command("Cancel"); + Command picked = Dialog.show("Describe a level", field, make, cancel); + if (picked != make) { + return; + } + final String words = field.getText(); + final long seed = new Random().nextInt(1 << 30); + if (Session.user() == null) { + generateOffline(words, seed); + return; + } + final int mine = ++generation; + say("Asking for a level..."); + Api.levels().generate(new GenerateDto(words, seed), Net.to(dto -> Ui.later(() -> { + if (mine == generation) { + adopt(dto.sketch(), dto.note() != null ? dto.note() + : "ai".equals(dto.source()) ? "Drawn by the model and proven finishable" + : "Built from your words and proven finishable"); + } + }), (status, message) -> Ui.later(() -> { + if (mine == generation) { + generateOffline(words, seed); + } + }))); + } + + private void save() { + Storage.getInstance().writeObject(STORE, sketch()); + } + + /// The level, drawn cell by cell with the world's art; drag to paint or + /// pan. + final class Canvas extends Component { + int scroll; + private int lastX; + + Canvas() { + setFocusable(true); + setUIID("EditorCanvas"); + } + + int cell() { + return Math.max(8, getHeight() / LevelGenerator.ROWS); + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(CN.getDisplayWidth(), CN.convertToPixels(6) * LevelGenerator.ROWS); + } + + @Override + public void paint(Graphics g) { + int x0 = getX(); + int y0 = getY(); + int ts = cell(); + g.setColor(sky()); + g.fillRect(x0, y0, getWidth(), getHeight()); + int cols = rows.isEmpty() ? 0 : rows.get(0).length(); + int first = Math.max(0, scroll / ts); + int last = Math.min(cols - 1, (scroll + getWidth()) / ts + 1); + LedgeArt a = art(); + TileGrid grid = world == null ? null : world.getGrid(); + g.setColor(0x26ffffff & 0xffffff); + g.setAlpha(40); + for (int c = first; c <= last; c++) { + g.drawLine(x0 + c * ts - scroll, y0, x0 + c * ts - scroll, y0 + ts * LevelGenerator.ROWS); + } + for (int r = 0; r <= LevelGenerator.ROWS; r++) { + g.drawLine(x0, y0 + r * ts, x0 + getWidth(), y0 + r * ts); + } + g.setAlpha(255); + if (grid != null) { + for (int r = 0; r < grid.getRows(); r++) { + for (int c = first; c <= last && c < grid.getCols(); c++) { + Image img = a.tile(grid, c, r); + if (img != null) { + g.drawImage(img, x0 + c * ts - scroll, y0 + r * ts, ts, ts); + } + } + } + double k = ts / (double) (grid.getTileSize() >> 16); + int[] goal = world.getGoal(); + Image gi = a.goal(goal[2], goal[3], 0); + if (gi != null) { + sprite(g, gi, goal[0], goal[1], goal[2], goal[3], k); + } + for (Entity e : world.getEntities()) { + Image ei = a.entity(e, 0); + if (ei != null) { + sprite(g, ei, e.x, e.y, e.w, e.h, k); + } + } + for (Actor actor : world.getActors()) { + com.codename1.gaming.platformer.Body b = actor.getBody(); + sprite(g, a.sheet(actor).getFrame(0), b.x, b.y, b.w, b.h, k); + } + } + } + + /// Draws art over a fixed-point box: as wide as it is tall, standing on + /// the box's bottom edge and centred on it, as the game draws it. + private void sprite(Graphics g, Image img, int fx, int fy, int fw, int fh, double k) { + double w = (fw >> 16) * k; + double h = (fh >> 16) * k; + double size = Math.max(w, h) * 1.15; + int x = (int) (getX() + (fx >> 16) * k + w / 2 - size / 2) - scroll; + int y = (int) (getY() + (fy >> 16) * k + h - size); + g.drawImage(img, x, y, (int) size, (int) size); + } + + private int sky() { + String t = theme(); + if ("cavern".equals(t)) { + return 0x2b2540; + } + if ("foundry".equals(t)) { + return 0x3a3236; + } + if ("forge".equals(t)) { + return 0x40201c; + } + if ("sky".equals(t)) { + return 0x9fd4f2; + } + return 0xa8dcf0; + } + + private void touch(int x, int y) { + int ts = cell(); + put((x - getAbsoluteX() + scroll) / ts, (y - getAbsoluteY()) / ts); + } + + @Override + public void pointerPressed(int x, int y) { + lastX = x; + if (painting) { + touch(x, y); + } + } + + @Override + public void pointerDragged(int x, int y) { + if (painting) { + touch(x, y); + } else { + int cols = rows.isEmpty() ? 0 : rows.get(0).length(); + int max = Math.max(0, cols * cell() - getWidth()); + scroll = Math.max(0, Math.min(max, scroll + lastX - x)); + lastX = x; + repaint(); + } + } + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/FriendsForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/FriendsForm.java new file mode 100644 index 00000000000..c5729f6cbf3 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/FriendsForm.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.appkit.Net; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.TextField; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.ledge.api.FriendAddDto; +import com.codenameone.examples.ledge.api.FriendDto; +import com.codenameone.examples.ledge.net.Api; +import java.util.List; + +/// The people on the Friends board. Adding someone is one way: they appear on +/// your board, and you on theirs only if they add you back. +public final class FriendsForm { + private FriendsForm() { + } + + public static void show() { + Form f = Ui.form("Friends", "friends"); + Ui.desktopColumn(f); + Ui.back(f, Nav::home); + final Container list = new Container(BoxLayout.y()); + final TextField name = new TextField("", "Name or username", 20, TextField.ANY); + name.setName("friendName"); + f.add(Ui.panel(name, Ui.primary("Add", "addFriend", e -> Api.friends().add( + new FriendAddDto(name.getText().trim()), Net.to(rows -> Ui.later(() -> { + name.setText(""); + fill(list, rows); + }), Ui::failed))))); + f.add(list); + Api.friends().friends(Net.to(rows -> Ui.later(() -> fill(list, rows)), Ui::failed)); + f.show(); + } + + static void fill(final Container list, List rows) { + list.removeAll(); + if (rows.isEmpty()) { + list.add(new Label("No friends on your board yet.", "Muted")); + } + for (final FriendDto fr : rows) { + Container row = new Container(new BorderLayout(), "Row"); + row.add(BorderLayout.CENTER, BoxLayout.encloseY(new Label(fr.displayName()), + new Label(fr.stars() + " stars", "Muted"))); + row.add(BorderLayout.EAST, Ui.button("Remove", "Plain", "remove-" + fr.username(), + e -> Api.friends().remove(new FriendAddDto(fr.username()), + Net.to(after -> Ui.later(() -> fill(list, after)), Ui::failed)))); + list.add(row); + } + list.revalidate(); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/HomeForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/HomeForm.java new file mode 100644 index 00000000000..431d57c3a2e --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/HomeForm.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.ui.Button; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.layouts.LayeredLayout; +import com.codenameone.examples.ledge.api.PlayerDto; +import com.codenameone.examples.ledge.engage.Ads; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.play.LedgeView; + +/// The first screen: a shipped level playing itself behind the menu (the +/// solver's own run, replayed), the name, the way into the map and today's +/// challenge, and the way to everything else. +public final class HomeForm extends Form { + private final Container layers; + private LedgeView attract; + private int demo; + + public HomeForm() { + super(new BorderLayout()); + setName("home"); + setUIID("PlayForm"); + setScrollable(false); + getToolbar().setVisible(false); + layers = new Container(new LayeredLayout()); + demo = (int) (System.currentTimeMillis() / 1000 % LevelPack.IDS.length); + attract = attract(demo); + layers.add(attract); + + PlayerDto me = Session.user(); + Container menu = new Container(BoxLayout.y(), "Card"); + menu.setName("menu"); + Label title = new Label("LEDGE", "Logo"); + menu.add(FlowLayout.encloseCenter(title)); + menu.add(FlowLayout.encloseCenter(new Label(me == null ? "Run. Jump. Climb higher." + : "Hello, " + me.displayName(), "CardText"))); + menu.add(go("Play", "Button", "play", e -> WorldMapForm.show())); + menu.add(go("Daily challenge", "Secondary", "playDaily", e -> Runs.play(Runs.DAILY))); + Label stars = new Label(Runs.totalStars() + " / " + LevelPack.IDS.length * 3, "Muted"); + stars.setName("totalStars"); + FontImage.setMaterialIcon(stars, FontImage.MATERIAL_STAR, Ui.iconMm(3)); + String coins = me == null ? "" : " " + me.coins() + " coins"; + stars.setText(stars.getText() + coins); + menu.add(FlowLayout.encloseCenter(stars)); + + Container tools = new Container(new GridLayout(1, 6), "Container"); + tools.add(tool(FontImage.MATERIAL_LEADERBOARD, "boards", e -> LeaderboardForm.show())); + tools.add(tool(FontImage.MATERIAL_STOREFRONT, "shop", e -> ShopForm.show())); + tools.add(tool(FontImage.MATERIAL_EMOJI_EVENTS, "achievements", e -> AchievementsForm.show())); + tools.add(tool(FontImage.MATERIAL_GROUP, "friends", e -> FriendsForm.show())); + tools.add(tool(FontImage.MATERIAL_ARCHITECTURE, "editor", e -> EditorForm.open())); + tools.add(tool(FontImage.MATERIAL_SETTINGS, "settings", e -> SettingsForm.show())); + menu.add(tools); + if (me == null) { + menu.add(Ui.button("Sign in for the boards", "Plain", "signIn", e -> SignInForm.show())); + } else if (me.admin()) { + menu.add(Ui.button("Console", "Plain", "console", e -> Nav.adminConsole())); + } + + Container front = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_CENTER)); + front.add(BorderLayout.CENTER, menu); + Component banner = Ads.banner(Ui.adFree()); + if (banner != null) { + front.add(BorderLayout.SOUTH, FlowLayout.encloseCenter(banner)); + } + layers.add(front); + add(BorderLayout.CENTER, layers); + addShowListener(e -> attract.start()); + } + + /// The level behind the menu. It replays the solver's log with the seed + /// the log was recorded under, then moves on to the next level. + private LedgeView attract(int index) { + LedgeView v = new LedgeView(index, 1); + v.setName("attract"); + v.setFocusable(false); + v.setAutopilot(LevelPack.demo(index)); + v.setHost(new LedgeView.Host() { + @Override + public void hudChanged(LedgeView view) { + // The menu shows no HUD. + } + + @Override + public void finished(LedgeView view) { + next(); + } + }); + return v; + } + + private void next() { + if (getComponentForm() == null || attract.getParent() == null) { + return; + } + attract.stop(); + demo = (demo + 1) % LevelPack.IDS.length; + LedgeView fresh = attract(demo); + layers.replace(attract, fresh, null); + attract = fresh; + attract.start(); + } + + private Button go(String text, String uiid, String name, final ActionListener action) { + Button b = new Button(text, uiid); + b.setName(name); + b.addActionListener(e -> { + attract.stop(); + action.actionPerformed(e); + }); + return b; + } + + private Button tool(char icon, final String name, final ActionListener go) { + Button b = new Button("", "HudButton"); + b.setName(name); + FontImage.setMaterialIcon(b, icon, 4.5f); + b.addActionListener(e -> { + attract.stop(); + if (Session.user() == null && !"settings".equals(name) && !"editor".equals(name)) { + SignInForm.show(); + } else { + go.actionPerformed(e); + } + }); + return b; + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/LeaderboardForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/LeaderboardForm.java new file mode 100644 index 00000000000..4c202d8b8cf --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/LeaderboardForm.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.appkit.Net; +import com.codename1.ui.Button; +import com.codename1.ui.ButtonGroup; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.RadioButton; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.ledge.api.DailyDto; +import com.codenameone.examples.ledge.api.LeaderDto; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.net.Api; +import com.codenameone.examples.ledge.play.Hud; +import java.util.List; + +/// The boards: a level, or today's challenge, by a period (all time, this +/// week, today, friends). The daily board is always today's. Each row is a +/// replay the server verified, so its time is exact. +public final class LeaderboardForm { + private static final String[] PERIODS = {"ALL", "WEEK", "TODAY", "FRIENDS"}; + private static final String[] PERIOD_LABELS = {"All time", "Week", "Today", "Friends"}; + + private LeaderboardForm() { + } + + public static void show() { + Form f = Ui.form("Boards", "boards"); + Ui.desktopColumn(f); + Ui.back(f, Nav::home); + final Container list = new Container(BoxLayout.y()); + list.setName("boardRows"); + final int[] pick = {1, 0}; + Container modes = segmented(boardLabels(), 1, i -> { + pick[0] = i; + load(list, pick[0], pick[1]); + }); + Container periods = segmented(PERIOD_LABELS, 0, i -> { + pick[1] = i; + load(list, pick[0], pick[1]); + }); + modes.setScrollableX(true); + f.add(modes).add(periods).add(list); + load(list, pick[0], pick[1]); + f.show(); + } + + interface Pick { + void picked(int index); + } + + static Container segmented(String[] labels, int selected, final Pick pick) { + Container c = new Container(labels.length > 4 ? new BoxLayout(BoxLayout.X_AXIS) : new GridLayout(1, labels.length)); + ButtonGroup g = new ButtonGroup(); + for (int i = 0; i < labels.length; i++) { + final int index = i; + RadioButton b = RadioButton.createToggle(labels[i], g); + b.setUIID(i == selected ? "TabSelected" : "Tab"); + b.addActionListener(e -> { + for (int k = 0; k < c.getComponentCount(); k++) { + c.getComponentAt(k).setUIID(k == index ? "TabSelected" : "Tab"); + } + c.repaint(); + pick.picked(index); + }); + c.add(b); + } + g.setSelected(selected); + return c; + } + + /// The boards to pick from: today's challenge, then every level. + static String[] boardLabels() { + String[] labels = new String[LevelPack.IDS.length + 1]; + labels[0] = "Daily"; + System.arraycopy(LevelPack.IDS, 0, labels, 1, LevelPack.IDS.length); + return labels; + } + + static void load(final Container list, int board, int period) { + list.removeAll(); + list.add(new Label("Reading the board...", "Muted")); + list.revalidate(); + boolean daily = board == 0; + if (daily) { + Api.runs().daily(Net.to(d -> Ui.later(() -> dailyHeader(list, d)), Ui::failed)); + } + Api.runs().leaderboard(daily ? Runs.DAILY : LevelPack.IDS[board - 1], daily ? "TODAY" : PERIODS[period], + Net.to(rows -> Ui.later(() -> fill(list, rows, daily ? null : LevelPack.IDS[board - 1])), Ui::failed)); + } + + private static void dailyHeader(Container list, DailyDto d) { + Container card = new Container(BoxLayout.y(), "Card"); + card.add(new Label("Daily " + d.date(), "CardTitle")); + card.add(new Label(d.players() + " players - top " + Hud.format(d.topScore()) + + (d.topName() == null ? "" : " by " + d.topName()), "CardText")); + card.add(new Label("Your best today: " + Hud.format(d.myBest()), "Accent")); + Button go = Ui.primary("Play level " + d.level(), "playDailyFromBoard", e -> Nav.daily()); + card.add(go); + list.addComponent(0, card); + list.revalidate(); + } + + private static void fill(Container list, List rows, final String level) { + for (int i = list.getComponentCount() - 1; i >= 0; i--) { + if (list.getComponentAt(i) instanceof Label) { + list.removeComponent(list.getComponentAt(i)); + } + } + if (rows.isEmpty()) { + list.add(new Label("Nobody yet. Be the first.", "Muted")); + } + for (LeaderDto r : rows) { + Container row = new Container(new BorderLayout(), r.me() ? "RowMe" : "Row"); + row.add(BorderLayout.WEST, new Label("#" + r.rank(), "Rank")); + row.add(BorderLayout.CENTER, new Label(r.displayName())); + Label score = new Label(Hud.format(r.score()), "Accent"); + Label time = new Label(Scoring.time(r.ticks()), "Muted"); + // Right-aligned, so the digits of every row line up down the board. + score.getAllStyles().setAlignment(Component.RIGHT); + time.getAllStyles().setAlignment(Component.RIGHT); + Container right = BoxLayout.encloseY(score, time); + if (level != null) { + final String who = r.username(); + final String name = r.displayName(); + Button watch = Ui.button("", "HudButton", "watch-" + who, e -> Api.runs().ghost(level, who, + Net.to(g -> Ui.later(() -> Runs.watch(LevelPack.indexOf(g.level()), g.seed(), g.log(), name)), + Ui::failed))); + FontImage.setMaterialIcon(watch, FontImage.MATERIAL_PLAY_ARROW, Ui.iconMm(3.5f)); + Button race = Ui.button("", "HudButton", "race-" + who, e -> Api.runs().ghost(level, who, + Net.to(g -> Ui.later(() -> Runs.race(g.level(), g.seed(), g.log())), Ui::failed))); + FontImage.setMaterialIcon(race, FontImage.MATERIAL_DIRECTIONS_RUN, Ui.iconMm(3.5f)); + right = BoxLayout.encloseX(right, watch, race); + } + row.add(BorderLayout.EAST, right); + list.add(row); + } + list.revalidate(); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Nav.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Nav.java new file mode 100644 index 00000000000..19b33e25ecc --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Nav.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.ui.CN; +import com.codenameone.examples.ledge.AppConfig; +import com.codenameone.examples.ledge.admin.AdminConsole; +import com.codenameone.examples.ledge.engage.Notifications; +import com.codenameone.examples.ledge.engage.Store; +import com.codenameone.examples.ledge.net.Session; + +/// Where the game goes between screens, in one place. +public final class Nav { + private static boolean wantDaily; + + private Nav() { + } + + /// The first screen is always the page with the menu on it: nobody has to + /// sign in to play. A stored session is picked up behind it, quietly. + public static void launch() { + wantDaily = AppConfig.openedForDaily(); + Session.onSignedOut(() -> CN.callSerially(Nav::home)); + Session.restore(() -> CN.callSerially(Nav::enter), () -> CN.callSerially(Nav::home), + () -> CN.callSerially(Nav::home)); + } + + /// Signed in, from a stored session or the sign-in screen. An admin who + /// was last in the console goes back there. + public static void enter() { + Notifications.signedIn(); + Store.resend(); + if (wantDaily) { + wantDaily = false; + daily(); + return; + } + if (Session.user() != null && Session.user().admin() + && "admin".equals(AppConfig.mode(Session.user().username()))) { + adminConsole(); + return; + } + home(); + } + + public static void signedIn() { + enter(); + } + + public static void home() { + if (Session.user() != null) { + AppConfig.setMode("player", Session.user().username()); + } + new HomeForm().show(); + } + + /// Today's challenge: the server deals the level and seed, so every player + /// races the same run. + public static void daily() { + Runs.play(Runs.DAILY); + } + + public static void adminConsole() { + AppConfig.setMode("admin", Session.user().username()); + AdminConsole.show(); + } + + public static void signOut() { + Notifications.signingOut(() -> Session.signOut(() -> CN.callSerially(Nav::home))); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/PlayForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/PlayForm.java new file mode 100644 index 00000000000..3e4acf80564 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/PlayForm.java @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.components.SpanLabel; +import com.codename1.gaming.platformer.PlatformWorld; +import com.codename1.gaming.platformer.Replay; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.layouts.LayeredLayout; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.play.Hud; +import com.codenameone.examples.ledge.play.LedgeView; +import com.codenameone.examples.ledge.play.Sfx; + +/// A run: the [LedgeView] filling the screen, the [Hud] over it, a pause +/// button, and the card that comes up when the level is cleared or the +/// lives run out. +public final class PlayForm extends Form implements LedgeView.Host { + /// Told how a run ended, to submit it and move on. + public interface Outcome { + void finished(LedgeView view, PlayForm form); + } + + private final LedgeView view; + private final Hud hud; + private final Container layers; + private final boolean daily; + private final Outcome outcome; + private Container overlay; + private Runnable back; + + public PlayForm(int level, long seed, boolean daily, Outcome outcome) { + this(new LedgeView(level, seed), daily, outcome, + (daily ? "Daily " : LevelPack.IDS[level] + " ") + LevelPack.NAMES[level]); + } + + /// A play-test of a level from the editor: no scoring, no submission, and + /// every way out goes `back`. + public static PlayForm test(LedgeView view, String title, Runnable back) { + PlayForm f = new PlayForm(view, false, null, title); + f.back = back; + return f; + } + + private PlayForm(LedgeView view, boolean daily, Outcome outcome, String title) { + super(new BorderLayout()); + setName("play"); + this.daily = daily; + this.outcome = outcome; + setUIID("PlayForm"); + setScrollable(false); + getToolbar().setVisible(false); + getToolbar().setUIID("Container"); + this.view = view; + view.setName("level"); + view.setHost(this); + hud = new Hud(view); + Button pause = new Button("", "HudButton"); + pause.setName("pause"); + FontImage.setMaterialIcon(pause, FontImage.MATERIAL_PAUSE, Ui.iconMm(4.5f)); + pause.addActionListener(e -> pause()); + layers = new Container(new LayeredLayout()); + layers.add(view).add(BorderLayout.north(hud)); + layers.add(pause); + ((LayeredLayout) layers.getLayout()).setInsets(pause, "1mm 1mm auto auto"); + hud.setRightInset(CN.convertToPixels(12)); + add(BorderLayout.CENTER, layers); + hud.banner(title); + addShowListener(e -> view.start()); + } + + public LedgeView getView() { + return view; + } + + @Override + public void hudChanged(LedgeView v) { + hud.repaint(); + } + + @Override + public void finished(LedgeView v) { + if (outcome != null) { + outcome.finished(v, this); + } else { + showResult(v, -1, null); + } + } + + /// The end-of-run card. `stars` is the server's verdict when it has one, + /// -1 to work it out here (a guest's run, or the server unreachable). + public void showResult(LedgeView v, int stars, String note) { + PlatformWorld w = v.getWorld(); + int index = v.getLevelIndex(); + boolean cleared = w.isComplete(); + if (back != null) { + showTestResult(w); + return; + } + Container card = new Container(BoxLayout.y(), "Card"); + card.setName("result"); + card.add(new Label(cleared ? "Cleared!" : "Out of lives", "CardTitle")); + if (cleared) { + Replay.Result r = new Replay.Result(w); + card.add(starRow(stars >= 0 ? stars : Scoring.stars(index, r))); + card.add(new Label(Hud.format(Scoring.points(index, r)), "BigScore")); + String line = Scoring.time(w.getTick()) + " par " + Scoring.time(LevelPack.PAR[index] * Scoring.TICKS_PER_SECOND) + + " " + w.getCoins() + " coins"; + card.add(new Label(line, "CardText")); + Sfx.play("complete"); + } else { + card.add(new Label("Reached " + Scoring.time(w.getTick()) + " in", "CardText")); + Sfx.play("gameover"); + } + if (note != null) { + SpanLabel n = new SpanLabel(note, "Accent"); + n.setName("resultNote"); + card.add(n); + } + Button again = new Button("Again"); + again.setName("again"); + again.addActionListener(e -> Runs.play(daily ? Runs.DAILY : LevelPack.IDS[index])); + Container buttons = new Container(new GridLayout(1, 1)); + buttons.add(again); + if (cleared && !daily && index + 1 < LevelPack.IDS.length) { + Button next = new Button("Next"); + next.setName("next"); + next.addActionListener(e -> Runs.play(LevelPack.IDS[index + 1])); + buttons.setLayout(new GridLayout(1, 2)); + buttons.add(next); + } + Button home = new Button(daily ? "Home" : "World map", "Secondary"); + home.setName("menuFromResult"); + home.addActionListener(e -> { + if (daily) { + Nav.home(); + } else { + WorldMapForm.show(); + } + }); + card.add(buttons).add(home); + showOverlay(card); + } + + private void showTestResult(PlatformWorld w) { + Container card = new Container(BoxLayout.y(), "Card"); + card.setName("result"); + card.add(new Label(w.isComplete() ? "It can be won" : "Out of lives", "CardTitle")); + card.add(new Label(Scoring.time(w.getTick()) + " " + w.getCoins() + " coins", "CardText")); + Sfx.play(w.isComplete() ? "complete" : "gameover"); + Button edit = new Button("Back to editing"); + edit.setName("backToEditor"); + edit.addActionListener(e -> back.run()); + card.add(FlowLayout.encloseCenter(edit)); + showOverlay(card); + } + + private static Container starRow(int stars) { + Container row = new Container(new FlowLayout(CENTER)); + row.setName("stars"); + for (int i = 0; i < 3; i++) { + Label l = new Label("", i < stars ? "StarOn" : "StarOff"); + FontImage.setMaterialIcon(l, FontImage.MATERIAL_STAR, Ui.iconMm(9)); + row.add(l); + } + return row; + } + + private void pause() { + if (overlay != null || view.getWorld().isComplete() || view.getWorld().isGameOver()) { + return; + } + view.pause(); + Container card = new Container(BoxLayout.y(), "Card"); + card.add(new Label("Paused", "CardTitle")); + Button resume = new Button("Resume"); + resume.setName("resume"); + resume.addActionListener(e -> { + hideOverlay(); + view.resume(); + }); + Button sound = new Button(Sfx.isMuted() ? "Sound on" : "Sound off", "Secondary"); + sound.addActionListener(e -> { + Sfx.setMuted(!Sfx.isMuted()); + sound.setText(Sfx.isMuted() ? "Sound on" : "Sound off"); + }); + Button restart = new Button("Restart", "Secondary"); + restart.addActionListener(e -> { + view.stop(); + if (back != null) { + back.run(); + } else { + Runs.play(daily ? Runs.DAILY : LevelPack.IDS[view.getLevelIndex()]); + } + }); + Button quit = new Button("Quit", "Secondary"); + quit.setName("quit"); + quit.addActionListener(e -> { + view.stop(); + if (back != null) { + back.run(); + } else { + Nav.home(); + } + }); + card.add(resume).add(restart).add(sound).add(quit); + showOverlay(card); + } + + /// An in-form overlay rather than a Dialog: a dialog over a GPU view + /// paints grey on some ports, and this keeps the level visible behind it. + private void showOverlay(Container card) { + hideOverlay(); + overlay = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_CENTER), "Scrim"); + overlay.add(BorderLayout.CENTER, card); + layers.add(overlay); + layers.revalidate(); + // A wrapping note only knows its height once it has a width, which + // the first pass gives it; the second sizes the card around it, or + // the last button falls off the bottom. + CN.callSerially(layers::revalidate); + } + + private void hideOverlay() { + if (overlay != null) { + overlay.remove(); + overlay = null; + layers.revalidate(); + } + } + + @Override + protected void onShowCompleted() { + super.onShowCompleted(); + CN.callSerially(view::requestFocus); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Runs.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Runs.java new file mode 100644 index 00000000000..4140f9e3a0c --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Runs.java @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.gaming.platformer.PlatformWorld; +import com.codename1.gaming.platformer.Replay; +import com.codename1.io.Preferences; +import com.codenameone.examples.ledge.api.RunDto; +import com.codenameone.examples.ledge.api.RunResultDto; +import com.codenameone.examples.ledge.api.RunTicketDto; +import com.codenameone.examples.ledge.api.StartRunDto; +import com.codenameone.examples.ledge.engage.Ads; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.levels.Scoring; +import com.codenameone.examples.ledge.net.Api; +import com.codename1.appkit.Net; +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.play.Hud; +import com.codenameone.examples.ledge.play.LedgeView; + +/// A run from the server's side: a ticket before it, the result after it. +/// +/// The ticket fixes the seed the level is played with and can be spent once. +/// After the run the app sends its input log -- not its score. The server +/// replays the log through the same simulation and scores what it saw, so a +/// patched client gains nothing. A guest, or a player whose server does not +/// answer, still plays; the run is simply not submitted, and the stars are +/// kept on the device. +// tag::ledge-run-flow[] +public final class Runs { + /// The level argument that means today's challenge. + public static final String DAILY = "daily"; + + private static final String LOCAL = "ledge.progress"; + + private static String pilot; + private static long ghostSeed; + private static String ghostLog; + + private Runs() { + } + + /// Drives the next run from a recorded input log instead of the player, + /// from its very first tick. The end-to-end tests play real levels this + /// way; the run is submitted like any other, and the server replays it + /// like any other. + public static void pilotNext(String log) { + pilot = log; + } + + /// Starts a level with a recorded run raced beside the player. + public static void race(String level, long seed, String log) { + ghostSeed = seed; + ghostLog = log; + play(level); + } + + /// Plays a recorded run back, start to finish, with nothing submitted: + /// the best run on a board, a friend's, or the shipped solution. + public static void watch(int index, long seed, String log, final String who) { + PlayForm f = new PlayForm(index, seed, false, (view, form) -> form.showResult(view, -1, who + "'s run")); + f.getView().setAutopilot(log); + f.show(); + } + + private static PlayForm form(int index, long seed, boolean daily, PlayForm.Outcome outcome) { + PlayForm f = new PlayForm(index, seed, daily, outcome); + if (pilot != null) { + f.getView().setAutopilot(pilot); + pilot = null; + } + if (ghostLog != null) { + f.getView().race(ghostSeed, ghostLog); + ghostLog = null; + } + return f; + } + + /// Starts a level by id, or the daily challenge. + public static void play(final String level) { + if (Session.user() == null) { + offline(level); + return; + } + Api.runs().start(new StartRunDto(level), Net.to(ticket -> Ui.later(() -> start(ticket)), + (status, message) -> Ui.later(() -> { + Ui.toast("Playing offline: this run will not reach the boards."); + offline(level); + }))); + } + + private static void offline(String level) { + boolean daily = DAILY.equals(level); + long day = System.currentTimeMillis() / 86400000L; + int index = daily ? Scoring.dailyLevel(day) : Math.max(0, LevelPack.indexOf(level)); + form(index, daily ? day : System.currentTimeMillis(), daily, + (view, form) -> finished(view, form, null)).show(); + } + + private static void start(final RunTicketDto ticket) { + int index = Math.max(0, LevelPack.indexOf(ticket.level())); + form(index, ticket.seed(), ticket.daily(), (view, form) -> finished(view, form, ticket)).show(); + } + + private static void finished(final LedgeView view, final PlayForm form, RunTicketDto ticket) { + Ads.betweenRuns(Ui.adFree()); + PlatformWorld w = view.getWorld(); + final Replay.Result local = new Replay.Result(w); + if (local.isComplete()) { + remember(view.getLevelIndex(), Scoring.stars(view.getLevelIndex(), local)); + } + if (ticket == null || !local.isComplete()) { + form.showResult(view, -1, Session.user() == null && local.isComplete() + ? "Sign in to put your runs on the boards" : null); + return; + } + // A run whose submission fails is not kept for later: its ticket is + // single use and short lived, so a retry after the app restarts would + // be refused anyway. A live game that wants one would queue it here. + RunDto run = new RunDto(ticket.token(), view.getLog().encode(), local.getTicks(), local.getHash()); + Api.runs().submit(run, Net.to(result -> Ui.later(() -> { + Session.refreshUser(() -> { }, (s, m) -> { }); + form.showResult(view, result.accepted() ? result.stars() : -1, note(result)); + }), (status, message) -> Ui.later(() -> form.showResult(view, -1, "Not submitted: " + message)))); + } + + static String note(RunResultDto r) { + if (!r.accepted()) { + return r.message() == null ? "The server did not take this run" : r.message(); + } + StringBuilder b = new StringBuilder(); + if (r.newBest()) { + b.append("New best! "); + } + if (r.rank() > 0) { + b.append("#").append(r.rank()).append(" on the board "); + } + if (r.coinsEarned() > 0) { + b.append("+").append(r.coinsEarned()).append(" coins"); + } + if (b.length() == 0) { + b.append("Best ").append(Hud.format(r.best())); + } + return b.toString().trim(); + } + + /// Stars earned on a level, the better of the server's record and this + /// device's. + public static int stars(int index) { + int best = digit(Preferences.get(LOCAL, ""), index); + if (Session.user() != null) { + best = Math.max(best, digit(Session.user().progress(), index)); + } + return best; + } + + /// Whether a level can be played: the first always, the rest once the + /// level before has been cleared. + public static boolean unlocked(int index) { + return index == 0 || stars(index - 1) > 0; + } + + /// Stars over every level. + public static int totalStars() { + int n = 0; + for (int i = 0; i < LevelPack.IDS.length; i++) { + n += stars(i); + } + return n; + } + + private static int digit(String progress, int index) { + if (progress == null || index >= progress.length()) { + return 0; + } + int d = progress.charAt(index) - '0'; + return d < 0 || d > 3 ? 0 : d; + } + + private static void remember(int index, int stars) { + String p = Preferences.get(LOCAL, ""); + StringBuilder b = new StringBuilder(p); + while (b.length() < LevelPack.IDS.length) { + b.append('0'); + } + if (stars > digit(p, index)) { + b.setCharAt(index, (char) ('0' + stars)); + Preferences.set(LOCAL, b.toString()); + } + } +} +// end::ledge-run-flow[] diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/SettingsForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/SettingsForm.java new file mode 100644 index 00000000000..78a6df0978b --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/SettingsForm.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.appkit.Net; +import com.codename1.ui.CheckBox; +import com.codename1.ui.Form; +import com.codename1.ui.TextField; +import com.codenameone.examples.ledge.AppConfig; +import com.codenameone.examples.ledge.api.ProfileDto; +import com.codenameone.examples.ledge.engage.Notifications; +import com.codenameone.examples.ledge.net.Api; +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.play.Sfx; + +/// Sound, the daily-sheet notification, the name on the boards, the server +/// (so a phone can reach a laptop on the same network), and signing out. +public final class SettingsForm { + private SettingsForm() { + } + + public static void show() { + Form f = Ui.form("Settings", "settings"); + Ui.desktopColumn(f); + Ui.back(f, Nav::home); + final CheckBox sound = CheckBox.createToggle("Sound"); + sound.setName("sound"); + sound.setSelected(!Sfx.isMuted()); + sound.addActionListener(e -> Sfx.setMuted(!sound.isSelected())); + f.add(Ui.panel(Ui.label("Sound", "CardTitle"), sound)); + if (Notifications.available()) { + final CheckBox push = CheckBox.createToggle("Tell me when today's sheet is out"); + push.setName("push"); + push.setSelected(Notifications.enabled()); + push.addActionListener(e -> Notifications.setEnabled(push.isSelected())); + f.add(Ui.panel(push)); + } + if (Session.user() != null) { + final TextField name = new TextField(Session.user().displayName(), "Name on the boards", 20, + TextField.ANY); + name.setName("displayName"); + f.add(Ui.panel(Ui.label("You", "CardTitle"), name, + Ui.primary("Save", "saveProfile", e -> Api.account().saveProfile( + new ProfileDto(name.getText().trim(), Session.user().scarf()), + Net.to(p -> Ui.later(() -> { + Session.setUser(p); + Ui.toast("Saved"); + }), Ui::failed))), + Ui.secondary("Sign out", "signOut", e -> Nav.signOut()))); + } + if (AppConfig.serverSwitchable()) { + final TextField server = new TextField(AppConfig.serverUrl(), "Server", 30, TextField.URL); + server.setName("server"); + f.add(Ui.panel(Ui.label("Server", "CardTitle"), server, Ui.secondary("Use this server", + "useServer", e -> { + AppConfig.setServerUrl(server.getText()); + Session.start(AppConfig.serverUrl()); + Nav.launch(); + }))); + } + f.show(); + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/ShopForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/ShopForm.java new file mode 100644 index 00000000000..14f4a38236f --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/ShopForm.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.appkit.Net; +import com.codename1.ui.Button; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codenameone.examples.ledge.api.AdRewardDto; +import com.codenameone.examples.ledge.api.BuyDto; +import com.codenameone.examples.ledge.api.EquipDto; +import com.codenameone.examples.ledge.api.ShopItemDto; +import com.codenameone.examples.ledge.api.WalletDto; +import com.codenameone.examples.ledge.engage.Ads; +import com.codenameone.examples.ledge.engage.Store; +import com.codenameone.examples.ledge.net.Api; +import com.codenameone.examples.ledge.net.Session; +import java.util.List; + +/// The shop: scarves for the hero, coins for real money, and coins for +/// watching an ad. Nothing here changes how the game plays -- a run is +/// replayed by the server, so it could not anyway. Everything is +/// granted by the server; this screen only asks. +public final class ShopForm { + private ShopForm() { + } + + public static void show() { + final Form f = Ui.form("Shop", "shop"); + Ui.desktopColumn(f); + Ui.back(f, Nav::home); + final Container body = new Container(BoxLayout.y()); + f.add(body); + Store.listen(wallet -> Ui.later(() -> { + com.codename1.io.Preferences.set("ledge.paid", true); + reload(body); + })); + reload(body); + f.show(); + } + + static void reload(final Container body) { + Api.shop().wallet(Net.to(wallet -> Api.shop().items(Net.to(items -> Ui.later(() -> fill(body, wallet, + items)), Ui::failed)), Ui::failed)); + } + + private static void fill(final Container body, WalletDto w, List items) { + body.removeAll(); + Container top = new Container(new BorderLayout(), "Card"); + top.add(BorderLayout.WEST, Ui.wallet(w.coins())); + body.add(top); + body.add(Ui.button("Watch an ad for 15 coins", "Secondary", "adReward", e -> Ads.rewarded( + () -> Api.shop().adReward(new AdRewardDto("ad-" + System.currentTimeMillis()), + Net.to(after -> Ui.later(() -> reload(body)), Ui::failed)), + () -> Ui.toast("No ad right now. Try again later.")))); + for (final ShopItemDto item : items) { + Container row = new Container(new BorderLayout(), "Row"); + Label name = new Label(item.name()); + if (item.colour() != null && item.colour().startsWith("#")) { + int c = Integer.parseInt(item.colour().substring(1), 16); + // The scarf's own colour, unless it is too dark to read on the card. + int lum = ((c >> 16) & 0xff) * 3 + ((c >> 8) & 0xff) * 6 + (c & 0xff); + if (lum > 600) { + name.getAllStyles().setFgColor(c); + } + } + row.add(BorderLayout.CENTER, name); + row.add(BorderLayout.EAST, action(body, w, item)); + body.add(row); + } + body.revalidate(); + } + + private static Button action(final Container body, WalletDto w, final ShopItemDto item) { + if (item.sku() != null && item.sku().length() > 0) { + String price = Store.price(item.sku()); + return Ui.primary(price == null ? "Buy" : price, "buy-" + item.id(), e -> Store.buy(item.sku())); + } + boolean owned = w.owned() != null && w.owned().contains(item.id()); + if ("scarf".equalsIgnoreCase(item.kind()) && owned) { + boolean on = item.id().equals(w.scarf()); + Button b = Ui.secondary(on ? "In use" : "Use", "equip-" + item.id(), e -> Api.shop().equip( + new EquipDto(item.id()), Net.to(after -> Ui.later(() -> { + Session.refreshUser(() -> { }, Ui::failed); + reload(body); + }), Ui::failed))); + b.setEnabled(!on); + return b; + } + Button b = Ui.primary(item.priceCoins() + " coins", "buy-" + item.id(), e -> Api.shop().buy( + new BuyDto(item.id()), Net.to(after -> Ui.later(() -> reload(body)), Ui::failed))); + b.setEnabled(w.coins() >= item.priceCoins()); + return b; + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/SignInForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/SignInForm.java new file mode 100644 index 00000000000..b867e2d52de --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/SignInForm.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.appkit.Net; +import com.codename1.ui.Container; +import com.codename1.ui.Form; +import com.codename1.ui.TextField; +import com.codenameone.examples.ledge.api.RegisterDto; +import com.codenameone.examples.ledge.net.Api; +import com.codenameone.examples.ledge.net.Session; + +/// Signing in, and opening an account. Neither is needed to play: a guest +/// plays every mode, and signs in only to put a run on the boards. +public final class SignInForm { + private SignInForm() { + } + + // tag::ledge-signin[] + public static void show() { + Form f = Ui.form("Sign in", "signin"); + Ui.desktopColumn(f); + Ui.back(f, Nav::home); + final TextField email = field("Email", TextField.EMAILADDR, "email"); + final TextField password = field("Password", TextField.PASSWORD, "password"); + Container card = Ui.panel(Ui.label("Ledge", "CardTitle"), + Ui.label("Sign in to put your runs on the boards.", "CardText"), + email, password, + Ui.primary("Sign in", "signInButton", e -> Session.signIn(email.getText().trim(), + password.getText(), () -> Ui.later(Nav::signedIn), Ui::failed)), + Ui.secondary("New here? Open an account", "registerButton", e -> register())); + f.add(Ui.centeredColumn(Ui.column(card))); + f.show(); + } + // end::ledge-signin[] + + /// A new account: the name on the boards, then the sign-in details. + public static void register() { + Form f = Ui.form("New account", "register"); + Ui.desktopColumn(f); + Ui.back(f, SignInForm::show); + final TextField name = field("Name on the boards", TextField.ANY, "displayName"); + final TextField email = field("Email", TextField.EMAILADDR, "email"); + final TextField password = field("Password", TextField.PASSWORD, "password"); + Container card = Ui.panel(Ui.label("Pick a pen name", "CardTitle"), name, email, password, + Ui.primary("Open account", "createButton", e -> { + final String mail = email.getText().trim(); + final String pass = password.getText(); + Api.account().register(new RegisterDto(mail, pass, name.getText().trim()), + Net.to(player -> Session.signIn(mail, pass, () -> Ui.later(Nav::signedIn), + Ui::failed), Ui::failed)); + })); + f.add(Ui.centeredColumn(Ui.column(card))); + f.show(); + } + + static TextField field(String hint, int constraint, String name) { + TextField t = new TextField("", hint, 20, constraint); + t.setName(name); + return t; + } +} diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Ui.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Ui.java new file mode 100644 index 00000000000..eb519d9b747 --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/Ui.java @@ -0,0 +1,388 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.components.SpanLabel; +import com.codename1.components.ToastBar; +import com.codename1.io.Log; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Command; +import com.codename1.ui.Component; +import com.codename1.ui.Container; +import com.codename1.ui.Font; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Graphics; +import com.codename1.ui.Label; +import com.codename1.ui.Toolbar; +import com.codename1.ui.events.ActionEvent; +import com.codename1.ui.events.ActionListener; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codename1.ui.plaf.Style; +import com.codename1.ui.plaf.UIManager; +import com.codename1.ui.util.Resources; +import com.codenameone.examples.ledge.api.PlayerDto; +import com.codenameone.examples.ledge.net.Session; +import java.io.IOException; +import java.util.Enumeration; +import java.util.Hashtable; + +/// The few building blocks every screen is made of. None of them draws +/// anything itself: each one only names a UIID, and `theme.css` decides what a +/// `PrimaryButton`, a `Panel` or a `Banner` looks like. Re-skinning the game is +/// editing that file, not this one. +// tag::ledge-ui[] +public final class Ui { + /// The widest a column of fields and buttons grows, in millimetres. + public static final int MAX_COLUMN_MM = 90; + + private Ui() { + } + + /// A screen: a scrolling column on the game's backdrop, its name reported + /// to analytics and given to the form so tests can find it. + public static Form form(String title, String name) { + Form f = new Form(title, BoxLayout.y()); + f.setName(name); + f.setUIID("Form"); + f.getToolbar().setUIID("Toolbar"); + f.getToolbar().getTitleComponent().setUIID("Title"); + f.setTitle(caps(title)); + f.setScrollableY(true); + return f; + } + + /// On a desktop, lifts every theme font to the floor `Type` keeps for the + /// HUD. The stylesheet sizes its small print in millimetres, and a monitor + /// reports so few pixels to the millimetre that a 2mm caption -- a menu + /// item's subtitle, a store row's tag -- came out at seven pixels. Call it + /// once, before the first form shows. Does nothing on a phone or tablet. + public static void desktopFonts() { + if (!CN.isDesktop()) { + return; + } + float perMm = CN.convertToPixels(100f) / 100f; + if (perMm <= 0 || perMm >= 5.5f) { + return; + } + float scale = 5.5f / perMm; + try { + Resources r = Resources.openLayered("/theme"); + String[] names = r.getThemeResourceNames(); + if (names == null || names.length == 0) { + return; + } + Hashtable theme = r.getTheme(names[0]); + Hashtable lifted = new Hashtable(); + Enumeration keys = theme.keys(); + while (keys.hasMoreElements()) { + Object k = keys.nextElement(); + Object v = theme.get(k); + if (v instanceof Font && ((Font) v).isTTFNativeFont()) { + Font f = (Font) v; + v = f.derive(f.getPixelSize() * scale, f.getStyle()); + } else if (v instanceof String && k instanceof String) { + v = liftSpacing(theme, (String) k, (String) v, scale); + } + lifted.put(k, v); + } + UIManager.getInstance().setThemeProps(lifted); + } catch (IOException e) { + Log.e(e); + } + } + + /// A padding or margin written in millimetres, lifted by `scale` like + /// the type: left alone, a tile kept its phone-sized padding under + /// desktop-sized text and flattened into a bar. + private static Object liftSpacing(Hashtable theme, String key, String value, float scale) { + String unitKey; + if (key.endsWith(".padding")) { + unitKey = key.substring(0, key.length() - ".padding".length()) + ".padUnit"; + } else if (key.endsWith(".margin")) { + unitKey = key.substring(0, key.length() - ".margin".length()) + ".marUnit"; + } else { + return value; + } + Object units = theme.get(unitKey); + if (!(units instanceof byte[])) { + return value; + } + byte[] u = (byte[]) units; + String[] parts = com.codename1.util.StringUtil.tokenize(value, ',').toArray(new String[0]); + if (parts.length != 4 || u.length != 4) { + return value; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 4; i++) { + float f; + try { + f = Float.parseFloat(parts[i].trim()); + } catch (NumberFormatException e) { + return value; + } + if (u[i] == Style.UNIT_TYPE_DIPS) { + f = f * scale; + } + if (i > 0) { + sb.append(','); + } + sb.append(f); + } + return sb.toString(); + } + + /// The widest a list screen reads on a desktop, in pixels: a row with its + /// label at one edge of a monitor and its button at the other is two + /// things, not one. + static final int DESKTOP_PAGE_PX = 1000; + + /// `mm` millimetres in pixels, with the same desktop floor `desktopFonts` + /// gives the type. A monitor reports so few pixels to the millimetre that + /// a panel sized for a phone came out as a phone-sized box in the middle + /// of a large window; sized through this it grows with its text. + public static int mm(float mm) { + int px = CN.convertToPixels(mm); + if (!CN.isDesktop()) { + return px; + } + float perMm = CN.convertToPixels(100f) / 100f; + return perMm > 0 && perMm < 5.5f ? (int) (mm * 5.5f) : px; + } + + /// An icon size in millimetres, lifted on a desktop like `mm`: a 3.5mm + /// play button came out as a glyph a few pixels wide on a monitor. + public static float iconMm(float mm) { + float perMm = CN.convertToPixels(100f) / 100f; + return CN.isDesktop() && perMm > 0 && perMm < 5.5f ? mm * 5.5f / perMm : mm; + } + + /// The column a desktop list screen keeps to: wide enough to fill a large + /// window with something, never so wide that a row splits in two. + public static int desktopPage(int width) { + return Math.max(DESKTOP_PAGE_PX, width * 3 / 5); + } + + /// On a desktop, keeps a list screen to a column in the middle of the + /// window, however wide the window is. Does nothing on a phone or tablet. + public static void desktopColumn(final Form f) { + if (!CN.isDesktop()) { + return; + } + final Container c = f.getContentPane(); + final Runnable fit = () -> { + int side = Math.max(0, (f.getWidth() - desktopPage(f.getWidth())) / 2); + Style s = c.getUnselectedStyle(); + s.setPaddingUnitLeft(Style.UNIT_TYPE_PIXELS); + s.setPaddingUnitRight(Style.UNIT_TYPE_PIXELS); + s.setPadding(Component.LEFT, side); + s.setPadding(Component.RIGHT, side); + }; + f.addShowListener(e -> { + fit.run(); + f.revalidate(); + }); + f.addSizeChangedListener(e -> { + fit.run(); + f.revalidateLater(); + }); + } + + /// Adds a back command that leaves through `leave`. + public static void back(Form f, final Runnable leave) { + Command back = new Command("") { + @Override + public void actionPerformed(ActionEvent evt) { + leave.run(); + } + }; + // The toolbar draws its arrow in millimetres, which on a monitor came + // out as a speck beside the title: there it gets the same desktop + // floor as the fonts. + float mm = 3f; + float perMm = CN.convertToPixels(100f) / 100f; + if (CN.isDesktop() && perMm > 0 && perMm < 5.5f) { + mm = mm * 5.5f / perMm; + } + f.getToolbar().setBackCommand(back, Toolbar.BackCommandPolicy.AS_ARROW, mm); + } + + public static Label label(String text, String uiid) { + return new Label(text, uiid); + } + + public static SpanLabel text(String text, String uiid) { + SpanLabel l = new SpanLabel(text); + l.setUIID("Container"); + l.setTextUIID(uiid); + return l; + } + + public static Button button(String text, String uiid, String name, ActionListener onClick) { + Button b = new Button(text, uiid); + b.setName(name); + if (onClick != null) { + b.addActionListener(onClick); + } + return b; + } + + /// The bright, rounded call to action of a screen. + public static Button primary(String text, String name, ActionListener onClick) { + return button(text, "Button", name, onClick); + } + + /// The outlined button for everything secondary. + public static Button secondary(String text, String name, ActionListener onClick) { + return button(text, "Plain", name, onClick); + } + + /// Sets a material icon drawn on nothing, so a label with a translucent + /// background doesn't get a darker square behind its icon. + public static void glyph(com.codename1.ui.Label l, char icon, float mm) { + com.codename1.ui.plaf.Style st = new com.codename1.ui.plaf.Style(l.getUnselectedStyle()); + st.setBgTransparency(0); + st.setBorder(null); + l.setIcon(com.codename1.ui.FontImage.createMaterial(icon, st, mm)); + } + + public static Container panel(Component... children) { + Container c = BoxLayout.encloseY(children); + c.setUIID("Card"); + return c; + } + + /// Equal cells side by side, with a gap between them and none at the + /// outer edges, so a row lines up with the full-width buttons above it. + public static Container row(Component... children) { + Container c = new Container(new GridLayout(1, children.length)); + for (int i = 0; i < children.length; i++) { + Style s = children[i].getAllStyles(); + s.setMarginUnitLeft(Style.UNIT_TYPE_DIPS); + s.setMarginUnitRight(Style.UNIT_TYPE_DIPS); + s.setMarginLeft(i == 0 ? 0f : 0.8f); + s.setMarginRight(i == children.length - 1 ? 0f : 0.8f); + c.add(children[i]); + } + return c; + } + + /// A column no wider than a phone held upright, centred on wider screens, + /// with the same gutter on both sides. Fields and buttons inside it all + /// fill its width, so they line up. + public static Container column(Component... children) { + Container col = new Container(BoxLayout.y()) { + @Override + protected Dimension calcPreferredSize() { + Dimension d = super.calcPreferredSize(); + int gutter = CN.convertToPixels(4) * 2; + d.setWidth(Math.min(CN.convertToPixels(MAX_COLUMN_MM), CN.getDisplayWidth() - gutter)); + return d; + } + }; + for (Component child : children) { + col.add(child); + } + return col; + } + + /// `column` centred in the space it is given. + public static Container centeredColumn(Container column) { + return BorderLayout.centerCenter(column); + } + + /// A rounded bar filled to `value` of `max`, for experience and quests. + public static Component bar(final int value, final int max, final int color) { + return new Component() { + @Override + public void paint(Graphics g) { + // Segmented, the way a game shows a stat. + int h = getHeight(); + int w = getWidth(); + int segs = 10; + int gap = Math.max(1, CN.convertToPixels(0.3f)); + int sw = Math.max(1, (w - gap * (segs - 1)) / segs); + int lit = max <= 0 ? 0 : (int) ((long) Math.max(0, Math.min(value, max)) * segs * 2 / max + 1) / 2; + for (int i = 0; i < segs; i++) { + g.setColor(i < lit ? color : 0x2a3038); + g.fillRect(getX() + i * (sw + gap), getY(), sw, h); + } + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(CN.convertToPixels(26), CN.convertToPixels(1.4f)); + } + }; + } + + public static Container centered(Component... children) { + return FlowLayout.encloseCenter(children); + } + + /// The coins at the top of the menus. + public static Label wallet(int coins) { + Label l = new Label(String.valueOf(coins), "Accent"); + l.setName("Coins"); + // the game's own coin, the one collected in the levels, sized to the text + com.codename1.ui.Image art = com.codenameone.examples.ledge.play.LedgeArt.image("item_coin"); + if (art != null) { + int px = l.getStyle().getFont().getHeight(); + l.setIcon(art.subImage(0, 0, com.codenameone.examples.ledge.play.LedgeArt.CELL, + com.codenameone.examples.ledge.play.LedgeArt.CELL, true).scaled(px, px)); + l.setGap(com.codename1.ui.CN.convertToPixels(1)); + } else { + l.setMaterialIcon(FontImage.MATERIAL_MONETIZATION_ON); + } + return l; + } + + /// Menu labels are set as written; the display face is already bold. + public static String caps(String s) { + return s == null ? "" : s; + } + + public static void toast(String text) { + ToastBar.showMessage(text, FontImage.MATERIAL_INFO, 2500); + } + + public static void failed(int status, String message) { + toast(message == null || message.length() == 0 ? "Something went wrong (" + status + ")" : message); + } + + public static PlayerDto me() { + return Session.user(); + } + + /// True once the player has bought coins with real money: a paying + /// player is not shown interstitials. + public static boolean adFree() { + return com.codename1.io.Preferences.get("ledge.paid", false); + } + + public static void later(Runnable r) { + CN.callSerially(r); + } +} +// end::ledge-ui[] diff --git a/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/WorldMapForm.java b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/WorldMapForm.java new file mode 100644 index 00000000000..492f4f23b5e --- /dev/null +++ b/scripts/ledge/common/src/main/java/com/codenameone/examples/ledge/ui/WorldMapForm.java @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.ui; + +import com.codename1.ui.plaf.UIManager; +import com.codename1.ui.plaf.Style; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Container; +import com.codename1.ui.FontImage; +import com.codename1.ui.Form; +import com.codename1.ui.Graphics; +import com.codename1.ui.Image; +import com.codename1.ui.Label; +import com.codename1.ui.geom.Dimension; +import com.codename1.ui.layouts.BorderLayout; +import com.codename1.ui.layouts.BoxLayout; +import com.codename1.ui.layouts.FlowLayout; +import com.codename1.ui.layouts.GridLayout; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.play.LedgeArt; + +/// The map: one card per world, painted with that world's far backdrop, and +/// a tile per level showing its stars. A level opens once the one before it +/// is cleared. +public final class WorldMapForm { + private static final String[] WORLD_NAMES = { + "Meadow", "Cavern", "Foundry", "Sky", "Forge" + }; + private static final String[] WORLD_THEMES = { + "meadow", "cavern", "foundry", "sky", "forge" + }; + + private WorldMapForm() { + } + + public static void show() { + Form f = Ui.form("Worlds", "worlds"); + Ui.back(f, Nav::home); + Label total = new Label(Runs.totalStars() + " / " + LevelPack.IDS.length * 3, "Accent"); + FontImage.setMaterialIcon(total, FontImage.MATERIAL_STAR, Ui.iconMm(3.5f)); + f.add(FlowLayout.encloseRight(total)); + for (int w = 0; w < WORLD_THEMES.length; w++) { + f.add(world(w)); + } + Ui.desktopColumn(f); + f.show(); + } + + private static Container world(int w) { + final Image bg = LedgeArt.image("bg_" + WORLD_THEMES[w] + "_0"); + Container card = new Container(BoxLayout.y(), "WorldCard") { + @Override + public void paint(Graphics g) { + // Drawn here rather than in paintBackground: a style with a + // rounded border paints the background itself and the + // component never calls paintBackground, so the world's art + // was never seen. + if (bg != null) { + int cw = getWidth(); + int ch = getHeight(); + float s = Math.max(cw / (float) bg.getWidth(), ch / (float) bg.getHeight()); + int iw = (int) (bg.getWidth() * s); + int ih = (int) (bg.getHeight() * s); + int r = Ui.mm(3); + int[] clip = g.getClip(); + boolean shaped = g.isShapeClipSupported(); + if (shaped) { + com.codename1.ui.geom.GeneralPath p = new com.codename1.ui.geom.GeneralPath(); + p.moveTo(getX() + r, getY()); + p.lineTo(getX() + cw - r, getY()); + p.quadTo(getX() + cw, getY(), getX() + cw, getY() + r); + p.lineTo(getX() + cw, getY() + ch - r); + p.quadTo(getX() + cw, getY() + ch, getX() + cw - r, getY() + ch); + p.lineTo(getX() + r, getY() + ch); + p.quadTo(getX(), getY() + ch, getX(), getY() + ch - r); + p.lineTo(getX(), getY() + r); + p.quadTo(getX(), getY(), getX() + r, getY()); + p.closePath(); + g.setClip(p); + } else { + g.clipRect(getX() + r / 2, getY() + r / 2, cw - r, ch - r); + } + // Bottom-aligned: a backdrop's horizon is near its foot. + g.drawImage(bg, getX() + (cw - iw) / 2, getY() + ch - ih, iw, ih); + // A scrim, so the title and the tiles keep their contrast. + int alpha = g.getAlpha(); + g.setColor(0x120e28); + g.setAlpha(110); + g.fillRect(getX(), getY(), cw, ch); + g.setAlpha(alpha); + g.setClip(clip); + } + super.paint(g); + } + }; + card.setName("world-" + WORLD_THEMES[w]); + card.add(new Label((w + 1) + " " + WORLD_NAMES[w], "WorldTitle")); + Container tiles = new Container(new GridLayout(1, 4)); + for (int i = 0; i < LevelPack.IDS.length; i++) { + if (WORLD_THEMES[w].equals(LevelPack.THEMES[i])) { + tiles.add(tile(i)); + } + } + // Keep tiles the same width in a world with fewer levels. + while (tiles.getComponentCount() < 4) { + tiles.add(new Label()); + } + card.add(tiles); + return card; + } + + private static Container tile(final int index) { + boolean open = Runs.unlocked(index); + int stars = Runs.stars(index); + Button b = new Button(open ? LevelPack.IDS[index] : "", open ? "LevelTile" : "LevelTileLocked"); + b.setName("level-" + LevelPack.IDS[index]); + if (!open) { + b.setIcon(FontImage.createMaterial(FontImage.MATERIAL_LOCK, clear(b.getUnselectedStyle()), + Ui.mm(4) * 25.4f / CN.convertToPixels(25.4f))); + b.setDisabledIcon(b.getIcon()); + b.setEnabled(false); + } + b.addActionListener(e -> Runs.play(LevelPack.IDS[index])); + Container stack = BoxLayout.encloseY(b, new StarStrip(stars)); + stack.setUIID("LevelCell"); + return stack; + } + + /// Three small stars under a tile, drawn rather than laid out so the row + /// stays the tile's width at every density. + /// A copy of `style` with no background, so an icon drawn with it is the + /// glyph alone and never a square of the style's colour. + static Style clear(Style style) { + Style s = new Style(style); + s.setBgTransparency(0); + s.setBorder(null); + return s; + } + + private static final class StarStrip extends com.codename1.ui.Component { + private final int stars; + private int cachedSize = -1; + private Image on; + private Image off; + + StarStrip(int stars) { + this.stars = stars; + } + + @Override + public void paint(Graphics g) { + int size = Math.min(getHeight(), getWidth() / 3); + if (size <= 0) { + return; + } + if (size != cachedSize) { + // Made once per size, not on every paint. + cachedSize = size; + float mm = size * 25.4f / CN.convertToPixels(25.4f); + UIManager m = UIManager.getInstance(); + on = FontImage.createMaterial(FontImage.MATERIAL_STAR, clear(m.getComponentStyle("StarOn")), mm); + off = FontImage.createMaterial(FontImage.MATERIAL_STAR, clear(m.getComponentStyle("MapStarOff")), mm); + } + int x = getX() + (getWidth() - size * 3) / 2; + for (int i = 0; i < 3; i++) { + g.drawImage(i < stars ? on : off, x + i * size, getY()); + } + } + + @Override + protected Dimension calcPreferredSize() { + return new Dimension(Ui.mm(12), Ui.mm(3.5f)); + } + } +} diff --git a/scripts/ledge/common/src/main/resources/LilitaOne-Regular.ttf b/scripts/ledge/common/src/main/resources/LilitaOne-Regular.ttf new file mode 100644 index 00000000000..fdec368cbd4 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/LilitaOne-Regular.ttf differ diff --git a/scripts/ledge/common/src/main/resources/app_icon.png b/scripts/ledge/common/src/main/resources/app_icon.png new file mode 100644 index 00000000000..f14cdbca9cb Binary files /dev/null and b/scripts/ledge/common/src/main/resources/app_icon.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_cavern_0.png b/scripts/ledge/common/src/main/resources/bg_cavern_0.png new file mode 100644 index 00000000000..e3c0770aefe Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_cavern_0.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_cavern_1.png b/scripts/ledge/common/src/main/resources/bg_cavern_1.png new file mode 100644 index 00000000000..d3fd9e7b77a Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_cavern_1.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_cavern_2.png b/scripts/ledge/common/src/main/resources/bg_cavern_2.png new file mode 100644 index 00000000000..272c949b6a1 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_cavern_2.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_forge_0.png b/scripts/ledge/common/src/main/resources/bg_forge_0.png new file mode 100644 index 00000000000..457cc5f8eb5 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_forge_0.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_forge_1.png b/scripts/ledge/common/src/main/resources/bg_forge_1.png new file mode 100644 index 00000000000..ce22b8d6cdb Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_forge_1.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_forge_2.png b/scripts/ledge/common/src/main/resources/bg_forge_2.png new file mode 100644 index 00000000000..2022d47ed5c Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_forge_2.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_foundry_0.png b/scripts/ledge/common/src/main/resources/bg_foundry_0.png new file mode 100644 index 00000000000..eaea07da58c Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_foundry_0.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_foundry_1.png b/scripts/ledge/common/src/main/resources/bg_foundry_1.png new file mode 100644 index 00000000000..bfec875a6dd Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_foundry_1.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_foundry_2.png b/scripts/ledge/common/src/main/resources/bg_foundry_2.png new file mode 100644 index 00000000000..8a40c5b5b2b Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_foundry_2.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_meadow_0.png b/scripts/ledge/common/src/main/resources/bg_meadow_0.png new file mode 100644 index 00000000000..e87c3f82d86 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_meadow_0.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_meadow_1.png b/scripts/ledge/common/src/main/resources/bg_meadow_1.png new file mode 100644 index 00000000000..0304e9a1f78 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_meadow_1.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_meadow_2.png b/scripts/ledge/common/src/main/resources/bg_meadow_2.png new file mode 100644 index 00000000000..b6b95da4310 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_meadow_2.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_sky_0.png b/scripts/ledge/common/src/main/resources/bg_sky_0.png new file mode 100644 index 00000000000..033ac4f3899 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_sky_0.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_sky_1.png b/scripts/ledge/common/src/main/resources/bg_sky_1.png new file mode 100644 index 00000000000..ec878b1157f Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_sky_1.png differ diff --git a/scripts/ledge/common/src/main/resources/bg_sky_2.png b/scripts/ledge/common/src/main/resources/bg_sky_2.png new file mode 100644 index 00000000000..00e3c8fa6dc Binary files /dev/null and b/scripts/ledge/common/src/main/resources/bg_sky_2.png differ diff --git a/scripts/ledge/common/src/main/resources/enemy_bat.png b/scripts/ledge/common/src/main/resources/enemy_bat.png new file mode 100644 index 00000000000..7dd1ee122a2 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/enemy_bat.png differ diff --git a/scripts/ledge/common/src/main/resources/enemy_beetle.png b/scripts/ledge/common/src/main/resources/enemy_beetle.png new file mode 100644 index 00000000000..50dfe1a9630 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/enemy_beetle.png differ diff --git a/scripts/ledge/common/src/main/resources/enemy_brute.png b/scripts/ledge/common/src/main/resources/enemy_brute.png new file mode 100644 index 00000000000..ff4eb894778 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/enemy_brute.png differ diff --git a/scripts/ledge/common/src/main/resources/enemy_frog.png b/scripts/ledge/common/src/main/resources/enemy_frog.png new file mode 100644 index 00000000000..46869e23e03 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/enemy_frog.png differ diff --git a/scripts/ledge/common/src/main/resources/enemy_golem.png b/scripts/ledge/common/src/main/resources/enemy_golem.png new file mode 100644 index 00000000000..4966cb4a12e Binary files /dev/null and b/scripts/ledge/common/src/main/resources/enemy_golem.png differ diff --git a/scripts/ledge/common/src/main/resources/enemy_slime.png b/scripts/ledge/common/src/main/resources/enemy_slime.png new file mode 100644 index 00000000000..d4693dbf5aa Binary files /dev/null and b/scripts/ledge/common/src/main/resources/enemy_slime.png differ diff --git a/scripts/ledge/common/src/main/resources/enemy_turret.png b/scripts/ledge/common/src/main/resources/enemy_turret.png new file mode 100644 index 00000000000..490b93ad3a5 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/enemy_turret.png differ diff --git a/scripts/ledge/common/src/main/resources/fx_spark.png b/scripts/ledge/common/src/main/resources/fx_spark.png new file mode 100644 index 00000000000..a2aaa080899 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/fx_spark.png differ diff --git a/scripts/ledge/common/src/main/resources/hero.png b/scripts/ledge/common/src/main/resources/hero.png new file mode 100644 index 00000000000..b32ba190283 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/hero.png differ diff --git a/scripts/ledge/common/src/main/resources/item_checkpoint0.png b/scripts/ledge/common/src/main/resources/item_checkpoint0.png new file mode 100644 index 00000000000..171bb8e59d8 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_checkpoint0.png differ diff --git a/scripts/ledge/common/src/main/resources/item_checkpoint1.png b/scripts/ledge/common/src/main/resources/item_checkpoint1.png new file mode 100644 index 00000000000..63571f0d663 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_checkpoint1.png differ diff --git a/scripts/ledge/common/src/main/resources/item_coin.png b/scripts/ledge/common/src/main/resources/item_coin.png new file mode 100644 index 00000000000..a94757c90b1 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_coin.png differ diff --git a/scripts/ledge/common/src/main/resources/item_crumble0.png b/scripts/ledge/common/src/main/resources/item_crumble0.png new file mode 100644 index 00000000000..5833eec60a7 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_crumble0.png differ diff --git a/scripts/ledge/common/src/main/resources/item_crumble1.png b/scripts/ledge/common/src/main/resources/item_crumble1.png new file mode 100644 index 00000000000..bb67c80f549 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_crumble1.png differ diff --git a/scripts/ledge/common/src/main/resources/item_crumble2.png b/scripts/ledge/common/src/main/resources/item_crumble2.png new file mode 100644 index 00000000000..9f5accec7d8 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_crumble2.png differ diff --git a/scripts/ledge/common/src/main/resources/item_door.png b/scripts/ledge/common/src/main/resources/item_door.png new file mode 100644 index 00000000000..0633f9ac798 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_door.png differ diff --git a/scripts/ledge/common/src/main/resources/item_gate.png b/scripts/ledge/common/src/main/resources/item_gate.png new file mode 100644 index 00000000000..94e2924d49d Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_gate.png differ diff --git a/scripts/ledge/common/src/main/resources/item_gem.png b/scripts/ledge/common/src/main/resources/item_gem.png new file mode 100644 index 00000000000..0719a7f4da8 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_gem.png differ diff --git a/scripts/ledge/common/src/main/resources/item_goal.png b/scripts/ledge/common/src/main/resources/item_goal.png new file mode 100644 index 00000000000..c8f20bc975f Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_goal.png differ diff --git a/scripts/ledge/common/src/main/resources/item_heart.png b/scripts/ledge/common/src/main/resources/item_heart.png new file mode 100644 index 00000000000..4b509254976 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_heart.png differ diff --git a/scripts/ledge/common/src/main/resources/item_key.png b/scripts/ledge/common/src/main/resources/item_key.png new file mode 100644 index 00000000000..82b9c5a6ebd Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_key.png differ diff --git a/scripts/ledge/common/src/main/resources/item_lever0.png b/scripts/ledge/common/src/main/resources/item_lever0.png new file mode 100644 index 00000000000..434ce078514 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_lever0.png differ diff --git a/scripts/ledge/common/src/main/resources/item_lever1.png b/scripts/ledge/common/src/main/resources/item_lever1.png new file mode 100644 index 00000000000..db3f045f15a Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_lever1.png differ diff --git a/scripts/ledge/common/src/main/resources/item_life.png b/scripts/ledge/common/src/main/resources/item_life.png new file mode 100644 index 00000000000..407fca899eb Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_life.png differ diff --git a/scripts/ledge/common/src/main/resources/item_plate0.png b/scripts/ledge/common/src/main/resources/item_plate0.png new file mode 100644 index 00000000000..0f4f7554951 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_plate0.png differ diff --git a/scripts/ledge/common/src/main/resources/item_plate1.png b/scripts/ledge/common/src/main/resources/item_plate1.png new file mode 100644 index 00000000000..985c8206e8c Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_plate1.png differ diff --git a/scripts/ledge/common/src/main/resources/item_power_glide.png b/scripts/ledge/common/src/main/resources/item_power_glide.png new file mode 100644 index 00000000000..d1e7fff607a Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_power_glide.png differ diff --git a/scripts/ledge/common/src/main/resources/item_power_jetpack.png b/scripts/ledge/common/src/main/resources/item_power_jetpack.png new file mode 100644 index 00000000000..cbf5d9bc3a9 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_power_jetpack.png differ diff --git a/scripts/ledge/common/src/main/resources/item_power_weapon.png b/scripts/ledge/common/src/main/resources/item_power_weapon.png new file mode 100644 index 00000000000..7afa17a7555 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_power_weapon.png differ diff --git a/scripts/ledge/common/src/main/resources/item_spring0.png b/scripts/ledge/common/src/main/resources/item_spring0.png new file mode 100644 index 00000000000..7d74fa9cece Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_spring0.png differ diff --git a/scripts/ledge/common/src/main/resources/item_spring1.png b/scripts/ledge/common/src/main/resources/item_spring1.png new file mode 100644 index 00000000000..50de8a27a3e Binary files /dev/null and b/scripts/ledge/common/src/main/resources/item_spring1.png differ diff --git a/scripts/ledge/common/src/main/resources/platform_cavern.png b/scripts/ledge/common/src/main/resources/platform_cavern.png new file mode 100644 index 00000000000..a3a1cdea01e Binary files /dev/null and b/scripts/ledge/common/src/main/resources/platform_cavern.png differ diff --git a/scripts/ledge/common/src/main/resources/platform_forge.png b/scripts/ledge/common/src/main/resources/platform_forge.png new file mode 100644 index 00000000000..aa312eea63b Binary files /dev/null and b/scripts/ledge/common/src/main/resources/platform_forge.png differ diff --git a/scripts/ledge/common/src/main/resources/platform_foundry.png b/scripts/ledge/common/src/main/resources/platform_foundry.png new file mode 100644 index 00000000000..c7f184945a3 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/platform_foundry.png differ diff --git a/scripts/ledge/common/src/main/resources/platform_meadow.png b/scripts/ledge/common/src/main/resources/platform_meadow.png new file mode 100644 index 00000000000..c666ad30b3d Binary files /dev/null and b/scripts/ledge/common/src/main/resources/platform_meadow.png differ diff --git a/scripts/ledge/common/src/main/resources/platform_sky.png b/scripts/ledge/common/src/main/resources/platform_sky.png new file mode 100644 index 00000000000..24baf65bac0 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/platform_sky.png differ diff --git a/scripts/ledge/common/src/main/resources/sfx_bounce.wav b/scripts/ledge/common/src/main/resources/sfx_bounce.wav new file mode 100644 index 00000000000..76f7453abe3 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_bounce.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_checkpoint.wav b/scripts/ledge/common/src/main/resources/sfx_checkpoint.wav new file mode 100644 index 00000000000..52d93b30801 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_checkpoint.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_coin.wav b/scripts/ledge/common/src/main/resources/sfx_coin.wav new file mode 100644 index 00000000000..ed07532b7e0 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_coin.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_complete.wav b/scripts/ledge/common/src/main/resources/sfx_complete.wav new file mode 100644 index 00000000000..7e8e6d8b64f Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_complete.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_crumble.wav b/scripts/ledge/common/src/main/resources/sfx_crumble.wav new file mode 100644 index 00000000000..a563846606c Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_crumble.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_dash.wav b/scripts/ledge/common/src/main/resources/sfx_dash.wav new file mode 100644 index 00000000000..02b0123dac2 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_dash.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_death.wav b/scripts/ledge/common/src/main/resources/sfx_death.wav new file mode 100644 index 00000000000..d8921431b01 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_death.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_fire.wav b/scripts/ledge/common/src/main/resources/sfx_fire.wav new file mode 100644 index 00000000000..8afece77e2d Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_fire.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_gameover.wav b/scripts/ledge/common/src/main/resources/sfx_gameover.wav new file mode 100644 index 00000000000..9ba02dd1291 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_gameover.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_gem.wav b/scripts/ledge/common/src/main/resources/sfx_gem.wav new file mode 100644 index 00000000000..6237aab0ce6 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_gem.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_hurt.wav b/scripts/ledge/common/src/main/resources/sfx_hurt.wav new file mode 100644 index 00000000000..6b51314512d Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_hurt.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_impact.wav b/scripts/ledge/common/src/main/resources/sfx_impact.wav new file mode 100644 index 00000000000..c68c0b4f03a Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_impact.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_jump.wav b/scripts/ledge/common/src/main/resources/sfx_jump.wav new file mode 100644 index 00000000000..e4cbf94eac3 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_jump.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_land.wav b/scripts/ledge/common/src/main/resources/sfx_land.wav new file mode 100644 index 00000000000..4593752fea0 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_land.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_open.wav b/scripts/ledge/common/src/main/resources/sfx_open.wav new file mode 100644 index 00000000000..2c0f02eca32 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_open.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_pickup.wav b/scripts/ledge/common/src/main/resources/sfx_pickup.wav new file mode 100644 index 00000000000..e07c4e5e670 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_pickup.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_stomp.wav b/scripts/ledge/common/src/main/resources/sfx_stomp.wav new file mode 100644 index 00000000000..ddc096656aa Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_stomp.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_switch.wav b/scripts/ledge/common/src/main/resources/sfx_switch.wav new file mode 100644 index 00000000000..1c624a76a3b Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_switch.wav differ diff --git a/scripts/ledge/common/src/main/resources/sfx_ui.wav b/scripts/ledge/common/src/main/resources/sfx_ui.wav new file mode 100644 index 00000000000..f0b97fef77e Binary files /dev/null and b/scripts/ledge/common/src/main/resources/sfx_ui.wav differ diff --git a/scripts/ledge/common/src/main/resources/shot_bolt.png b/scripts/ledge/common/src/main/resources/shot_bolt.png new file mode 100644 index 00000000000..f7f0f29ae22 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/shot_bolt.png differ diff --git a/scripts/ledge/common/src/main/resources/shot_orb.png b/scripts/ledge/common/src/main/resources/shot_orb.png new file mode 100644 index 00000000000..d6f5b154b25 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/shot_orb.png differ diff --git a/scripts/ledge/common/src/main/resources/tiles_cavern.png b/scripts/ledge/common/src/main/resources/tiles_cavern.png new file mode 100644 index 00000000000..47547cc0f41 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/tiles_cavern.png differ diff --git a/scripts/ledge/common/src/main/resources/tiles_forge.png b/scripts/ledge/common/src/main/resources/tiles_forge.png new file mode 100644 index 00000000000..39de9ebfe37 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/tiles_forge.png differ diff --git a/scripts/ledge/common/src/main/resources/tiles_foundry.png b/scripts/ledge/common/src/main/resources/tiles_foundry.png new file mode 100644 index 00000000000..be5f401050b Binary files /dev/null and b/scripts/ledge/common/src/main/resources/tiles_foundry.png differ diff --git a/scripts/ledge/common/src/main/resources/tiles_meadow.png b/scripts/ledge/common/src/main/resources/tiles_meadow.png new file mode 100644 index 00000000000..718274eddd9 Binary files /dev/null and b/scripts/ledge/common/src/main/resources/tiles_meadow.png differ diff --git a/scripts/ledge/common/src/main/resources/tiles_sky.png b/scripts/ledge/common/src/main/resources/tiles_sky.png new file mode 100644 index 00000000000..5412dddb40d Binary files /dev/null and b/scripts/ledge/common/src/main/resources/tiles_sky.png differ diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/AccountTest.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/AccountTest.java new file mode 100644 index 00000000000..5b1be59dd32 --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/AccountTest.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.play.LedgeView; +import com.codenameone.examples.ledge.ui.SettingsForm; + +/// A new player opens an account, plays a run the server accepts, and finds +/// it on the boards; then signs out again. +public class AccountTest extends E2e { + @Override + protected boolean run() throws Exception { + click("signIn"); + waitForForm("signin"); + shot("signin"); + click("registerButton"); + waitForForm("register"); + String stamp = String.valueOf(System.currentTimeMillis() % 100000); + type("displayName", "Hopper" + stamp); + type("email", "new" + stamp + "@ledge.example"); + type("password", "a-long-password"); + click("createButton"); + until(() -> Session.user() != null, 30000, "the new account"); + waitForForm("home"); + assertEqual("Hopper" + stamp, Session.user().displayName()); + + click("play"); + waitForForm("worlds"); + pilot("1-1"); + click("level-1-1"); + waitForForm("play"); + LedgeView view = level(); + assertTrue(playFor(view, 60000), "the run reaches the end of 1-1"); + awaitResult("the submitted run"); + // The server replays the log; its verdict is what the card shows. + until(() -> has("resultNote"), 20000, "the server's verdict"); + String note = ((com.codename1.components.SpanLabel) findByName("resultNote")).getText(); + assertTrue(note.startsWith("New best") || note.startsWith("#"), "the server took the run: " + note); + shot("result-submitted"); + click("menuFromResult"); + waitForForm("worlds"); + onEdt(() -> com.codenameone.examples.ledge.ui.Nav.home()); + waitForForm("home"); + + click("boards"); + waitForForm("boards"); + until(() -> has("boardRows"), 10000, "the board"); + shot("boards"); + // Race the best run on the board: the ghost sets off, the hero (left + // standing) falls behind, and the HUD says by how much. + until(() -> findByNamePrefix("race-") != null, 10000, "a run to race"); + click(findByNamePrefix("race-").getName()); + waitForForm("play"); + shot("race", level(), 5000); + onEdt(() -> com.codenameone.examples.ledge.ui.Nav.home()); + waitForForm("home"); + onEdt(SettingsForm::show); + waitForForm("settings"); + shot("settings"); + click("signOut"); + until(() -> Session.user() == null, 20000, "signing out"); + waitForForm("home"); + return true; + } +} diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/AdminTest.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/AdminTest.java new file mode 100644 index 00000000000..9eb7889eb8f --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/AdminTest.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.ui.Tabs; + +/// The admin opens the console, reads the day, finds the flagged run the demo +/// data carries and strikes it, and deals a sheet of their own. +public class AdminTest extends E2e { + @Override + protected boolean run() throws Exception { + click("signIn"); + waitForForm("signin"); + signIn(ADMIN); + waitForForm("home"); + click("console"); + waitForForm("console"); + shot("console-today"); + final Tabs tabs = (Tabs) findByType(Tabs.class); + onEdt(() -> tabs.setSelectedIndex(2)); + until(() -> findStrike() != null, 15000, "the flagged run"); + shot("console-flags"); + click(findStrike()); + until(() -> findStrike() == null, 15000, "the run to be struck"); + onEdt(() -> tabs.setSelectedIndex(3)); + type("dailySeed", "424242"); + click("setDaily"); + waitFor(1500); + onEdt(() -> tabs.setSelectedIndex(4)); + waitFor(1500); + shot("console-audit"); + onEdt(() -> tabs.setSelectedIndex(5)); + until(() -> has("heatmap"), 15000, "the death map"); + waitFor(500); + shot("console-deaths"); + return true; + } + + private String findStrike() { + com.codename1.ui.Component c = findByNamePrefix("strike-"); + return c == null ? null : c.getName(); + } +} diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/DesktopTest.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/DesktopTest.java new file mode 100644 index 00000000000..258641f94d1 --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/DesktopTest.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.components.SpanLabel; +import com.codename1.io.Storage; +import com.codename1.ui.Button; +import com.codename1.ui.Tabs; +import com.codenameone.examples.ledge.play.LedgeView; +import com.codenameone.examples.ledge.ui.EditorForm; +import com.codenameone.examples.ledge.ui.Nav; +import com.codenameone.examples.ledge.ui.Runs; + +/// The desktop pass, and the tour the demo recording follows: the app in a +/// laptop-sized window -- a level and the 2.5D sky, the editor proving a +/// generated level and watching the solver finish it, a race against the +/// best run on the boards, and the console's death heat map. +public class DesktopTest extends E2e { + @Override + protected boolean desktop() { + return true; + } + + @Override + protected boolean run() throws Exception { + shot("desktop-home"); + waitFor(3000); + click("play"); + waitForForm("worlds"); + shot("desktop-worlds"); + pilot("2-1"); + onEdt(() -> Runs.play("2-1")); + waitForForm("play"); + LedgeView view = level(); + shot("desktop-level-2-1", view, 8000); + pilot("4-1"); + onEdt(() -> Runs.play("4-1")); + waitForForm("play"); + view = level(); + shot("desktop-level-4-1-depth", view, 9000); + + onEdt(() -> Storage.getInstance().deleteStorageFile("ledge-editor.sketch")); + onEdt(EditorForm::open); + waitForForm("editor"); + shot("desktop-editor"); + click("surprise"); + until(() -> status().startsWith("A new level"), 120000, "a generated level"); + waitFor(1500); + click("check"); + until(() -> ((Button) findByName("watch")).isEnabled(), 120000, "the solver's proof"); + shot("desktop-editor-proven"); + waitFor(1500); + click("watch"); + waitForForm("play"); + shot("desktop-editor-watch", level(), 8000); + + onEdt(Nav::home); + waitForForm("home"); + click("signIn"); + waitForForm("signin"); + signIn(ADMIN); + waitForForm("home"); + shot("desktop-home-signed-in"); + click("boards"); + waitForForm("boards"); + until(() -> has("boardRows"), 10000, "the board"); + shot("desktop-boards"); + waitFor(1500); + until(() -> findByNamePrefix("race-") != null, 10000, "a run to race"); + pilot("1-1"); + click(findByNamePrefix("race-").getName()); + waitForForm("play"); + shot("desktop-race", level(), 8000); + + onEdt(Nav::home); + waitForForm("home"); + click("console"); + waitForForm("console"); + shot("desktop-console-today"); + waitFor(1500); + final Tabs tabs = (Tabs) findByType(Tabs.class); + onEdt(() -> tabs.setSelectedIndex(5)); + until(() -> has("heatmap"), 15000, "the death map"); + waitFor(2500); + shot("desktop-console-deaths"); + return true; + } + + private String status() { + SpanLabel l = (SpanLabel) findByName("editorStatus"); + return l == null ? "" : l.getText(); + } +} diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/E2e.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/E2e.java new file mode 100644 index 00000000000..d3b97edad94 --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/E2e.java @@ -0,0 +1,368 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.io.FileSystemStorage; +import com.codename1.io.oidc.OidcTokens; +import com.codename1.io.oidc.TokenStore; +import com.codename1.testing.AbstractTest; +import com.codename1.ui.Button; +import com.codename1.ui.CN; +import com.codename1.ui.Component; +import com.codename1.ui.Display; +import com.codename1.ui.Form; +import com.codename1.ui.Image; +import com.codename1.ui.TextArea; +import com.codename1.ui.util.ImageIO; +import com.codename1.util.AsyncResource; +import com.codenameone.examples.ledge.levels.LevelPack; +import com.codenameone.examples.ledge.play.LedgeView; +import com.codenameone.examples.ledge.ui.Runs; +import com.codenameone.examples.ledge.play.Sfx; +import com.codenameone.examples.ledge.net.Session; +import com.codenameone.examples.ledge.ui.Nav; +import java.io.OutputStream; + +/// What every end-to-end test shares: a fresh session against the test +/// server, ways to press and type by component name, and screenshots. +/// +/// The screenshots are the ones the developer guide's "Make it your own" +/// chapter shows; `run-e2e.sh` writes them to `target/e2e-shots`. +public abstract class E2e extends AbstractTest { + public static final String PASSWORD = "ledge-demo"; + public static final String PLAYER = "player@ledge.example"; + public static final String RIVAL = "rival@ledge.example"; + public static final String ADMIN = "admin@ledge.example"; + + protected interface Check { + boolean ok(); + } + + @Override + public boolean shouldExecuteOnEDT() { + return false; + } + + @Override + public int getTimeoutMillis() { + return 180000; + } + + protected abstract boolean run() throws Exception; + + /// Whether this run of the tests is the one in a desktop window. + /// + /// `run-e2e.sh` runs the tests twice: on the simulator's phone, and then, + /// with the simulator as a desktop, where the admin console is + /// a side bar and a page. A test belongs to one of the two -- see + /// [#desktop()] -- and passes without doing anything in the other. + static boolean desktopRun() { + return "true".equals(System.getProperty("ledge.e2e.desktop")); + } + + /// Whether this test is one for the desktop window. The phone's are not. + protected boolean desktop() { + return false; + } + + private boolean mine() { + // ledge.e2e.only names the test classes a run is for, by comma (the demo + // recordings); the runner itself has no way to pick a test. + String only = System.getProperty("ledge.e2e.only"); + if (only != null && only.length() > 0 + && ("," + only + ",").indexOf("," + getClass().getSimpleName() + ",") < 0) { + return false; + } + return desktop() == desktopRun(); + } + + @Override + public final boolean runTest() throws Exception { + if (!mine()) { + log("Not a test for this run; skipped"); + return true; + } + if (desktopRun()) { + desktopWindow(1440, 900); + } + return run(); + } + + /// The desktop pass shoots a laptop-sized window. The simulator opens a + /// desktop at whatever size the content asks for, which for a phone app + /// is small; the window is sized here, and the form lays itself out again + /// at the new size as it would after a user resized it. + private void desktopWindow(int width, int height) throws Exception { + javax.swing.SwingUtilities.invokeAndWait(() -> { + for (java.awt.Frame f : java.awt.Frame.getFrames()) { + if (f.isShowing()) { + f.setExtendedState(java.awt.Frame.NORMAL); + f.setSize(width, height); + f.validate(); + } + } + }); + waitFor(1200); + } + + @Override + public void prepare() { + if (!mine()) { + return; + } + Session.useStore(new MemoryStore()); + onEdt(() -> { + Sfx.setMuted(true); + AppConfig.setMode("player"); + Session.start(AppConfig.serverUrl()); + Nav.launch(); + }); + waitForForm("home"); + } + + @Override + public void cleanup() { + if (!mine()) { + return; + } + onEdt(() -> Session.start(AppConfig.serverUrl())); + } + + protected void onEdt(Runnable work) { + CN.callSeriallyAndWait(work); + } + + /// Presses a button, or taps anything else by that name -- a list row is + /// a `MultiButton`, which is a container holding its button. + protected void click(final String name) { + until(() -> findByName(name) != null, 20000, "a button called " + name); + if (!(findByName(name) instanceof Button)) { + touch(name); + return; + } + onEdt(() -> { + Button button = (Button) findByName(name); + button.pressed(); + button.released(); + }); + } + + protected void type(final String name, final String text) { + until(() -> findByName(name) instanceof TextArea, 20000, "a field called " + name); + onEdt(() -> ((TextArea) findByName(name)).setText(text)); + } + + protected boolean has(String name) { + return findByName(name) != null; + } + + protected void until(Check check, int timeoutMillis, String what) { + long deadline = System.currentTimeMillis() + timeoutMillis; + while (!check.ok()) { + if (System.currentTimeMillis() > deadline) { + Form current = Display.getInstance().getCurrent(); + shot("timed-out-" + (current == null ? "no-form" : current.getName())); + throw new RuntimeException("Timed out waiting for " + what + " (on " + + (current == null ? "no form" : current.getName()) + ")"); + } + waitFor(100); + } + } + + protected void waitForForm(final String name) { + until(() -> { + Form current = Display.getInstance().getCurrent(); + return current != null && name.equals(current.getName()); + }, 30000, "the " + name + " screen"); + waitFor(150); + } + + protected void signIn(String email) { + type("email", email); + type("password", PASSWORD); + click("signInButton"); + until(() -> Session.user() != null, 30000, "the sign-in"); + } + + protected LedgeView level() { + until(() -> findByName("level") instanceof LedgeView, 20000, "the level"); + return (LedgeView) findByName("level"); + } + + /// Arranges for the next level started to be played by the solver's own + /// recorded run of it, from its first tick. A test asserts that the + /// level was cleared and the server took the run, never what it scored. + protected void pilot(String levelId) { + Runs.pilotNext(LevelPack.demo(LevelPack.indexOf(levelId))); + } + + /// Lets a run play for `millis` of real time, or until it ends. Answers + /// whether it ended. + protected boolean playFor(final LedgeView view, int millis) { + long end = System.currentTimeMillis() + millis; + while (System.currentTimeMillis() < end) { + final boolean[] over = new boolean[1]; + onEdt(() -> over[0] = view.getWorld().isComplete() || view.getWorld().isGameOver()); + if (over[0]) { + return true; + } + waitFor(16); + } + return false; + } + + /// Waits for the end-of-run card. + protected void awaitResult(String what) { + until(() -> has("again"), 30000, what); + } + + /// The first component on the current form of `type`, or null. + protected Component findByType(Class type) { + return walk(Display.getInstance().getCurrent(), type, null); + } + + /// The first component on the current form whose name starts `prefix`. + protected Component findByNamePrefix(String prefix) { + return walk(Display.getInstance().getCurrent(), null, prefix); + } + + private static Component walk(Component c, Class type, String prefix) { + if (c == null) { + return null; + } + if (type != null && type.isInstance(c)) { + return c; + } + if (prefix != null && c.getName() != null && c.getName().startsWith(prefix)) { + return c; + } + if (c instanceof com.codename1.ui.Container) { + com.codename1.ui.Container k = (com.codename1.ui.Container) c; + for (int i = 0; i < k.getComponentCount(); i++) { + Component found = walk(k.getComponentAt(i), type, prefix); + if (found != null) { + return found; + } + } + } + return null; + } + + /// A real touch: press and release at a point on the screen, the way a + /// finger would, so it reaches the form's pointer listeners. + protected void touch(final int x, final int y) { + onEdt(() -> { + Form f = Display.getInstance().getCurrent(); + f.pointerPressed(x, y); + f.pointerReleased(x, y); + }); + } + + protected void touch(String name) { + until(() -> findByName(name) != null, 20000, name); + // A tap lands only on what is on screen: scroll a row below the fold + // into view first. + onEdt(() -> { + Component k = findByName(name); + if (k.getComponentForm() != null) { + k.getComponentForm().scrollComponentToVisible(k); + } + }); + waitFor(600); + Component c = findByName(name); + touch(c.getAbsoluteX() + c.getWidth() / 2, c.getAbsoluteY() + c.getHeight() / 2); + } + + // -------------------------------------------------------- screenshots + + protected void shot(String name) { + String dir = System.getProperty("ledge.shots.dir"); + if (dir == null || dir.length() == 0) { + return; + } + waitFor(1200); + capture(dir, name); + } + + /// A shot of a run in progress, after it has played on for `millis`. + protected void shot(String name, LedgeView view, int millis) { + String dir = System.getProperty("ledge.shots.dir"); + if (dir == null || dir.length() == 0) { + return; + } + playFor(view, millis); + capture(dir, name); + } + + /// A shot of this very moment, for a frame that would not survive the + /// bot driving on: a stamp, a replay, a clear view down the field. + protected void shotNow(String name) { + String dir = System.getProperty("ledge.shots.dir"); + if (dir == null || dir.length() == 0) { + return; + } + waitFor(150); + capture(dir, name); + } + + private void capture(String dir, String name) { + String out = dir.startsWith("file:") ? dir : "file://" + dir; + final Image[] captured = new Image[1]; + onEdt(() -> captured[0] = Display.getInstance().captureScreen()); + FileSystemStorage files = FileSystemStorage.getInstance(); + try { + files.mkdir(out); + OutputStream png = files.openOutputStream(out + "/" + name + ".png"); + try { + ImageIO.getImageIO().save(captured[0], png, ImageIO.FORMAT_PNG, 1f); + } finally { + png.close(); + } + } catch (java.io.IOException err) { + log("Could not save " + name + ": " + err); + } + } + + static final class MemoryStore implements TokenStore { + private OidcTokens kept; + + @Override + public AsyncResource load(String key) { + AsyncResource out = new AsyncResource(); + out.complete(kept); + return out; + } + + @Override + public AsyncResource save(String key, OidcTokens tokens) { + kept = tokens; + AsyncResource out = new AsyncResource(); + out.complete(Boolean.TRUE); + return out; + } + + @Override + public AsyncResource clear(String key) { + kept = null; + AsyncResource out = new AsyncResource(); + out.complete(Boolean.TRUE); + return out; + } + } +} diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/EditorTest.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/EditorTest.java new file mode 100644 index 00000000000..a8e9cbc0cfa --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/EditorTest.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codename1.io.Storage; +import com.codename1.ui.Button; +import com.codename1.components.SpanLabel; +import com.codenameone.examples.ledge.play.LedgeView; +import com.codenameone.examples.ledge.ui.EditorForm; + +/// The level editor: a fresh level painted on, a generated one proven +/// finishable by the solver, and the solver's own run watched in the game's +/// view before going back to editing. +public class EditorTest extends E2e { + @Override + protected boolean run() throws Exception { + onEdt(() -> Storage.getInstance().deleteStorageFile("ledge-editor.sketch")); + onEdt(EditorForm::open); + waitForForm("editor"); + shot("editor"); + click("brush-94"); + touch("editorCanvas"); + click("theme"); + shot("editor-cavern"); + click("surprise"); + until(() -> status().startsWith("A new level"), 120000, "a generated level"); + shot("editor-generated"); + click("check"); + until(() -> ((Button) findByName("watch")).isEnabled(), 120000, "the solver's proof"); + shot("editor-proven"); + click("watch"); + waitForForm("play"); + LedgeView view = level(); + shot("editor-watch", view, 3000); + assertTrue(playFor(view, 90000), "the solver's run finishes the generated level"); + until(() -> has("backToEditor"), 30000, "the play-test card"); + shot("editor-test-result"); + click("backToEditor"); + waitForForm("editor"); + onEdt(() -> com.codenameone.examples.ledge.ui.Nav.home()); + waitForForm("home"); + return true; + } + + private String status() { + SpanLabel l = (SpanLabel) findByName("editorStatus"); + return l == null ? "" : l.getText(); + } +} diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/GuestTest.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/GuestTest.java new file mode 100644 index 00000000000..341c3bb8b14 --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/GuestTest.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codenameone.examples.ledge.play.LedgeView; +import com.codenameone.examples.ledge.ui.Runs; + +/// A guest plays with no account: the map, the first level cleared by the +/// solver's recorded run, the result card with its stars, and the sky world +/// in 2.5D. Nothing is submitted, and the card says how to get on the boards. +public class GuestTest extends E2e { + @Override + protected boolean run() throws Exception { + shot("home"); + click("play"); + waitForForm("worlds"); + shot("worlds"); + pilot("1-1"); + click("level-1-1"); + waitForForm("play"); + LedgeView view = level(); + shot("level-1-1-start", view, 900); + shot("level-1-1-run", view, 4000); + shot("level-1-1-later", view, 9000); + assertTrue(playFor(view, 60000), "the solver's run reaches the end of 1-1"); + awaitResult("the end of the guest run"); + assertTrue(has("stars"), "a cleared level shows its stars"); + shot("result-cleared"); + click("menuFromResult"); + waitForForm("worlds"); + + pilot("4-1"); + onEdt(() -> Runs.play("4-1")); + waitForForm("play"); + view = level(); + shot("level-4-1-depth", view, 5000); + shot("level-4-1-depth-later", view, 6000); + onEdt(() -> com.codenameone.examples.ledge.ui.Nav.home()); + waitForForm("home"); + return true; + } +} diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/MemoryPreferences.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/MemoryPreferences.java new file mode 100644 index 00000000000..5448e32b292 --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/MemoryPreferences.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import java.util.HashMap; +import java.util.Map; +import java.util.prefs.AbstractPreferences; +import java.util.prefs.Preferences; +import java.util.prefs.PreferencesFactory; + +/// Preferences that live in memory and die with the JVM, for recording the +/// desktop demo on a Mac. The simulator becomes a desktop only through its +/// "desktopSkin" preference, and outside Linux the JDK keeps preferences +/// where the developer's own simulator reads them (the macOS plist), so the +/// run swaps the whole store for this one with +/// `-Djava.util.prefs.PreferencesFactory=com.codenameone.examples.ledge.MemoryPreferences`. +/// Every key named in `ledge.prefs.seed` (comma separated `key=value`) starts +/// out set on every node. +public class MemoryPreferences implements PreferencesFactory { + private static final Preferences USER = new Node(null, ""); + private static final Preferences SYSTEM = new Node(null, ""); + + @Override + public Preferences userRoot() { + return USER; + } + + @Override + public Preferences systemRoot() { + return SYSTEM; + } + + private static final class Node extends AbstractPreferences { + private final Map values = new HashMap<>(); + private final Map children = new HashMap<>(); + + Node(Node parent, String name) { + super(parent, name); + String seed = System.getProperty("ledge.prefs.seed", ""); + for (String kv : seed.split(",")) { + int eq = kv.indexOf('='); + if (eq > 0) { + values.put(kv.substring(0, eq).trim(), kv.substring(eq + 1).trim()); + } + } + } + + @Override + protected void putSpi(String key, String value) { + values.put(key, value); + } + + @Override + protected String getSpi(String key) { + return values.get(key); + } + + @Override + protected void removeSpi(String key) { + values.remove(key); + } + + @Override + protected void removeNodeSpi() { + values.clear(); + } + + @Override + protected String[] keysSpi() { + return values.keySet().toArray(new String[0]); + } + + @Override + protected String[] childrenNamesSpi() { + return children.keySet().toArray(new String[0]); + } + + @Override + protected AbstractPreferences childSpi(String name) { + return children.computeIfAbsent(name, n -> new Node(this, n)); + } + + @Override + protected void syncSpi() { + } + + @Override + protected void flushSpi() { + } + } +} diff --git a/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/ShopTest.java b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/ShopTest.java new file mode 100644 index 00000000000..59ce3982a91 --- /dev/null +++ b/scripts/ledge/common/src/test/java/com/codenameone/examples/ledge/ShopTest.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge; + +import com.codenameone.examples.ledge.net.Session; + +/// The demo player buys a scarf for the hero with coins, wears it, and buys +/// coins through the simulated store. +public class ShopTest extends E2e { + @Override + protected boolean run() throws Exception { + click("signIn"); + waitForForm("signin"); + signIn(PLAYER); + waitForForm("home"); + click("shop"); + waitForForm("shop"); + until(() -> has("buy-scarf-teal") || has("equip-scarf-teal"), 15000, "the shop"); + shot("shop"); + if (has("buy-scarf-teal")) { + click("buy-scarf-teal"); + until(() -> has("equip-scarf-teal"), 15000, "the teal scarf to be owned"); + } + click("equip-scarf-teal"); + until(() -> "scarf-teal".equals(Session.user().scarf()), 15000, "the teal scarf worn"); + click("buy-coins-small"); + waitFor(1500); + shot("shop-after"); + return true; + } +} diff --git a/scripts/ledge/ios/pom.xml b/scripts/ledge/ios/pom.xml new file mode 100644 index 00000000000..15bc445e408 --- /dev/null +++ b/scripts/ledge/ios/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + com.codenameone.examples.ledge + ledge + 1.0-SNAPSHOT + + com.codenameone.examples.ledge + ledge-ios + 1.0-SNAPSHOT + + ledge-ios + + + UTF-8 + 17 + 17 + ios + ios + ios-device + + + + + src/main/objectivec + + + src/main/resources + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + build-ios + package + + build + + + + + + + + + + + ${project.groupId} + ${cn1app.name}-common + ${project.version} + + + ${project.groupId} + ${cn1app.name}-common + ${project.version} + tests + test + + + + + + + + + diff --git a/scripts/ledge/ios/src/main/objectivec/.gitkeep b/scripts/ledge/ios/src/main/objectivec/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/scripts/ledge/levels/1-1.json b/scripts/ledge/levels/1-1.json new file mode 100644 index 00000000000..90fb0652ff1 --- /dev/null +++ b/scripts/ledge/levels/1-1.json @@ -0,0 +1,52 @@ +{ + "name": "First Light", + "theme": "meadow", + "par": 40, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [134, 8, 1, 2], + "spawn": [5, 12], + "tiles": [ + "...............................................................................................................................................", + "...............................................................................................................................................", + "...............................................................................................................................................", + "...............................................................................................................................................", + "...............................................................................................................................................", + "...............................................................................................................................................", + ".........................................................======................................................................................", + "...............................................................................................................................................", + "...........................................................................=====...............................................................", + "...............................................................................................................................................", + "..............................................................................................#####......................................#####.", + ".......................ab####...............................................................######.......................######.......######...", + "...................ab########b.........................................#######...........#########....................#######.......#######....", + "...............ab#############b.........#############..........##############c..........##########.....###########....########^^^^^^^########..", + "###############################.......################.....#####################d.....##############...############....########################", + "###############################.......################.....########################...##############...############....########################" + ], + "entities": [ + {"type": "gem", "at": [59, 5]}, + {"type": "coin", "at": [76, 7]}, + {"type": "coin", "at": [77, 7]}, + {"type": "coin", "at": [78, 7]}, + {"type": "coin", "at": [43, 8]}, + {"type": "coin", "at": [44, 8]}, + {"type": "coin", "at": [45, 8]}, + {"type": "coin", "at": [106, 8]}, + {"type": "coin", "at": [108, 8]}, + {"type": "coin", "at": [110, 8]}, + {"type": "coin", "at": [17, 9]}, + {"type": "coin", "at": [18, 9]}, + {"type": "coin", "at": [19, 9]}, + {"type": "coin", "at": [124, 10]}, + {"type": "coin", "at": [125, 10]}, + {"type": "coin", "at": [126, 10]}, + {"type": "coin", "at": [14, 12]}, + {"type": "coin", "at": [15, 12]}, + {"type": "coin", "at": [16, 12]}, + {"type": "coin", "at": [43, 12]}, + {"type": "coin", "at": [45, 12]}, + {"type": "enemy", "at": [51, 12], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [104, 12], "kind": "slime", "brain": "patrol", "speed": 0.6} + ] +} diff --git a/scripts/ledge/levels/1-2.json b/scripts/ledge/levels/1-2.json new file mode 100644 index 00000000000..a0bad94626a --- /dev/null +++ b/scripts/ledge/levels/1-2.json @@ -0,0 +1,54 @@ +{ + "name": "Ladder Hill", + "theme": "meadow", + "par": 55, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [119, 3, 1, 2], + "spawn": [7, 10], + "tiles": [ + "......................................................................................................................................", + "......................................................................................................................................", + "..........................................=========.....................................####..........................................", + ".......................................................................................##..##.........................................", + ".....................................H.................H..............................................................................", + ".........................=======.....H.................H................................................=====........#####............", + ".....................................H#################H.........=======............................................######............", + ".....................................H.................H..........................####.............................#######............", + ".....................................H.................H.........................######.............=====.........########............", + "................=====................H.................H.............############################################.#########...........", + ".....................................H.................H...........................................................##########.........", + "...............................=========.........=========........................................................###########.........", + "######################.......##########.............########.....................................................############.........", + "######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############...........", + "######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############...........", + "######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############..........." + ], + "entities": [ + {"type": "coin", "at": [45, 1]}, + {"type": "coin", "at": [46, 1]}, + {"type": "coin", "at": [47, 1]}, + {"type": "gem", "at": [89, 1]}, + {"type": "coin", "at": [27, 4]}, + {"type": "coin", "at": [28, 4]}, + {"type": "coin", "at": [29, 4]}, + {"type": "coin", "at": [105, 4]}, + {"type": "coin", "at": [106, 4]}, + {"type": "coin", "at": [107, 4]}, + {"type": "enemy", "at": [45, 5], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "coin", "at": [67, 5]}, + {"type": "coin", "at": [68, 5]}, + {"type": "coin", "at": [69, 5]}, + {"type": "checkpoint", "at": [82, 6]}, + {"type": "coin", "at": [17, 8]}, + {"type": "coin", "at": [18, 8]}, + {"type": "coin", "at": [19, 8]}, + {"type": "enemy", "at": [76, 8], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [94, 8], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "coin", "at": [43, 10]}, + {"type": "coin", "at": [45, 10]}, + {"type": "coin", "at": [47, 10]}, + {"type": "heart", "at": [110, 11]}, + {"type": "enemy", "at": [44, 12], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6} + ] +} diff --git a/scripts/ledge/levels/1-3.json b/scripts/ledge/levels/1-3.json new file mode 100644 index 00000000000..ea27cbfec5b --- /dev/null +++ b/scripts/ledge/levels/1-3.json @@ -0,0 +1,59 @@ +{ + "name": "Drifting Isles", + "theme": "meadow", + "par": 60, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "platforms": [{"path": [[19, 11], [34, 11]], "w": 3, "speed": 0.8, "pause": 30}, {"path": [[48, 12], [48, 6]], "w": 3, "speed": 0.7, "pause": 40}, {"path": [[81, 9], [95, 9]], "w": 3, "speed": 1.0, "pause": 20}, {"path": [[108, 10], [108, 6]], "w": 3, "speed": 0.7, "pause": 30}, {"path": [[127, 10], [131, 5]], "w": 3, "speed": 0.8, "pause": 30}], + "goal": [145, 4, 1, 2], + "spawn": [7, 11], + "tiles": [ + "......................................................................................................................................................", + "......................................................................................................................................................", + "......................................................................................................................................................", + "......................................................................................................................................................", + "......................................................................................................................................................", + "........................................................#######.......................................................................................", + "........................................................#######.........................................................................##############", + "........................................................#######.........................................................................##############", + "........................................................#######.....................................######..............................##############", + "........................................................#######.....................................######..............................##############", + "........................................................#######.....................................######..............................##############", + "........................................................#######.........#######.....................######............#######...........##############", + "################........................######..........#######.........#######.....................######............#######...........##############", + "################........................######..........#######.........#######.....................######............#######...........##############", + "################^^^^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^#######^^^^^^^^^#######^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^^^#######^^^^^^^^^^^##############", + "################^^^^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^#######^^^^^^^^^#######^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^^^#######^^^^^^^^^^^##############" + ], + "entities": [ + {"type": "coin", "at": [125, 2]}, + {"type": "coin", "at": [126, 2]}, + {"type": "coin", "at": [127, 2]}, + {"type": "coin", "at": [128, 2]}, + {"type": "coin", "at": [129, 2]}, + {"type": "coin", "at": [130, 2]}, + {"type": "coin", "at": [57, 3]}, + {"type": "coin", "at": [58, 3]}, + {"type": "coin", "at": [59, 3]}, + {"type": "coin", "at": [60, 3]}, + {"type": "coin", "at": [61, 3]}, + {"type": "gem", "at": [140, 3]}, + {"type": "coin", "at": [88, 6]}, + {"type": "coin", "at": [89, 6]}, + {"type": "coin", "at": [90, 6]}, + {"type": "coin", "at": [91, 6]}, + {"type": "coin", "at": [92, 6]}, + {"type": "coin", "at": [93, 6]}, + {"type": "checkpoint", "at": [102, 7]}, + {"type": "coin", "at": [20, 9]}, + {"type": "coin", "at": [22, 9]}, + {"type": "coin", "at": [24, 9]}, + {"type": "coin", "at": [26, 9]}, + {"type": "coin", "at": [28, 9]}, + {"type": "coin", "at": [30, 9]}, + {"type": "coin", "at": [32, 9]}, + {"type": "coin", "at": [34, 9]}, + {"type": "enemy", "at": [74, 10], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [121, 10], "kind": "beetle", "brain": "walker", "speed": 0.8} + ] +} diff --git a/scripts/ledge/levels/1-4.json b/scripts/ledge/levels/1-4.json new file mode 100644 index 00000000000..96822e10147 --- /dev/null +++ b/scripts/ledge/levels/1-4.json @@ -0,0 +1,52 @@ +{ + "name": "Thornwood", + "theme": "meadow", + "par": 75, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [146, 4, 1, 2], + "spawn": [7, 9], + "tiles": [ + "............................................................................................................................................................", + "............................................................................................................................................................", + "............................................................................................................................................................", + "............................................................................................................................................................", + "..............................................................................................................................=======.......................", + "............................................................................................................................................................", + ".....................................................................=====................................................................#########.........", + ".....................................................................................................####................................#########..........", + ".....................................#########.....................................................######....................####.......#########...........", + ".....................................#########..................................##########..........######..........######....####......##########..........", + ".....................................#########.................................##########..........######.........#######....####.....###########...........", + "...........................##############....##..........########.............##########..........######.........#######....####....############............", + "##############......##########################..........###########.........##############.........######.........#######....####...#############...........", + "##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.........", + "##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.........", + "##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############........." + ], + "entities": [ + {"type": "enemy", "at": [95, 2], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6}, + {"type": "coin", "at": [129, 3]}, + {"type": "coin", "at": [130, 3]}, + {"type": "coin", "at": [131, 3]}, + {"type": "enemy", "at": [54, 4], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6}, + {"type": "coin", "at": [70, 5]}, + {"type": "coin", "at": [71, 5]}, + {"type": "coin", "at": [72, 5]}, + {"type": "coin", "at": [41, 6]}, + {"type": "coin", "at": [42, 6]}, + {"type": "coin", "at": [43, 6]}, + {"type": "checkpoint", "at": [102, 6]}, + {"type": "spring", "at": [127, 7]}, + {"type": "coin", "at": [22, 8]}, + {"type": "coin", "at": [23, 8]}, + {"type": "coin", "at": [24, 8]}, + {"type": "enemy", "at": [85, 8], "kind": "frog", "brain": "hopper", "interval": 80}, + {"type": "enemy", "at": [118, 8], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [33, 10], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [60, 10], "kind": "beetle", "brain": "walker", "speed": 0.8}, + {"type": "enemy", "at": [51, 12], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "heart", "at": [110, 12]} + ] +} diff --git a/scripts/ledge/levels/2-1.json b/scripts/ledge/levels/2-1.json new file mode 100644 index 00000000000..b96375e1317 --- /dev/null +++ b/scripts/ledge/levels/2-1.json @@ -0,0 +1,115 @@ +{ + "name": "Echo Caves", + "theme": "cavern", + "par": 70, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [140, 7, 1, 2], + "spawn": [5, 11], + "tiles": [ + "######################################################################################################################################################", + "######################################################################################################################################################", + "......................................................................................................................................................", + "......................................................................................................................................................", + ".....................................############...........===========...............................................................................", + ".....................................############.................H.......................................=====.......................................", + ".....................................############.................H...................................................................................", + "........................................H.........................H.............................###############.......................................", + "........................................H.........................H.............................###############.......====............................", + "........................................H.........................H.............................###############............###########################", + "...........................................................############.........................###############.=====......###########################", + "...........................................................############.........................###############............###########################", + "###############........##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############............###########################", + "###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^###########################", + "###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^###########################", + "###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^###########################" + ], + "entities": [ + {"type": "coin", "at": [74, 4]}, + {"type": "coin", "at": [76, 4]}, + {"type": "coin", "at": [78, 4]}, + {"type": "coin", "at": [80, 4]}, + {"type": "coin", "at": [82, 4]}, + {"type": "coin", "at": [84, 4]}, + {"type": "coin", "at": [86, 4]}, + {"type": "coin", "at": [88, 4]}, + {"type": "coin", "at": [90, 4]}, + {"type": "coin", "at": [92, 4]}, + {"type": "coin", "at": [94, 4]}, + {"type": "gem", "at": [108, 4]}, + {"type": "crumble", "at": [72, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [73, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [74, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [75, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [76, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [77, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [78, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [79, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [80, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [81, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [82, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [83, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [84, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [85, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [86, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [87, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [88, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [89, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [90, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [91, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [92, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [93, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [94, 6], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [95, 6], "delay": 24, "respawn": 240}, + {"type": "enemy", "at": [103, 6], "kind": "brute", "brain": "chase", "speed": 1.1, "range": 7, "hp": 2}, + {"type": "coin", "at": [126, 6]}, + {"type": "coin", "at": [127, 6]}, + {"type": "coin", "at": [128, 6]}, + {"type": "coin", "at": [129, 6]}, + {"type": "coin", "at": [130, 6]}, + {"type": "coin", "at": [131, 6]}, + {"type": "coin", "at": [132, 6]}, + {"type": "coin", "at": [133, 6]}, + {"type": "coin", "at": [134, 6]}, + {"type": "coin", "at": [52, 8]}, + {"type": "coin", "at": [53, 8]}, + {"type": "coin", "at": [54, 8]}, + {"type": "coin", "at": [55, 8]}, + {"type": "coin", "at": [56, 8]}, + {"type": "coin", "at": [57, 8]}, + {"type": "checkpoint", "at": [64, 9]}, + {"type": "coin", "at": [17, 10]}, + {"type": "coin", "at": [18, 10]}, + {"type": "coin", "at": [19, 10]}, + {"type": "coin", "at": [20, 10]}, + {"type": "coin", "at": [21, 10]}, + {"type": "coin", "at": [39, 10]}, + {"type": "coin", "at": [40, 10]}, + {"type": "coin", "at": [41, 10]}, + {"type": "coin", "at": [42, 10]}, + {"type": "coin", "at": [43, 10]}, + {"type": "coin", "at": [44, 10]}, + {"type": "coin", "at": [45, 10]}, + {"type": "coin", "at": [46, 10]}, + {"type": "enemy", "at": [30, 11], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [44, 11], "kind": "frog", "brain": "hopper", "interval": 80}, + {"type": "crumble", "at": [50, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [51, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [52, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [53, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [54, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [55, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [56, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [57, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [58, 11], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [15, 12], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [16, 12], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [17, 12], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [18, 12], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [19, 12], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [20, 12], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [21, 12], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [22, 12], "delay": 24, "respawn": 240} + ] +} diff --git a/scripts/ledge/levels/2-2.json b/scripts/ledge/levels/2-2.json new file mode 100644 index 00000000000..005bb7b51af --- /dev/null +++ b/scripts/ledge/levels/2-2.json @@ -0,0 +1,60 @@ +{ + "name": "Locked Deep", + "theme": "cavern", + "par": 80, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [132, 8, 1, 2], + "spawn": [4, 13], + "tiles": [ + "############################################################################################################################################", + "############################################################################################################################################", + "......................................................................................#.....................................................", + ".........................................####################.........................#.....................................................", + ".........................................#............................................#.....................................................", + ".........................................#............................................#.....................................................", + ".........................................#............................................#.....................................................", + ".........................................#............................................#.....................................................", + ".........................................#....###############.........................#.....................................................", + ".........................................#....###############.........................#.....................................................", + ".........................................#....###############.....................................=====..........###########################", + ".........................................#....###############....................................................###########################", + "..............................................###############======###################.##################........###########################", + "..............................................###############......###################.##################........###########################", + "#####################.......#################################......###################.##################........###########################", + "#####################.......#################################......###################.##################........###########################", + "#####################^^^^^^^#################################^^^^^^###################.##################^^^^^^^^###########################", + "#####################^^^^^^^#################################^^^^^^###################.##################^^^^^^^^###########################" + ], + "entities": [ + {"type": "coin", "at": [43, 7]}, + {"type": "coin", "at": [44, 7]}, + {"type": "enemy", "at": [51, 7], "kind": "beetle", "brain": "walker", "speed": 0.8}, + {"type": "key", "at": [55, 7], "name": "gold"}, + {"type": "gem", "at": [100, 9]}, + {"type": "crumble", "at": [109, 9], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [110, 9], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [111, 9], "delay": 24, "respawn": 240}, + {"type": "heart", "at": [120, 9]}, + {"type": "coin", "at": [72, 10]}, + {"type": "coin", "at": [74, 10]}, + {"type": "coin", "at": [76, 10]}, + {"type": "coin", "at": [78, 10]}, + {"type": "coin", "at": [80, 10]}, + {"type": "crumble", "at": [105, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [106, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [107, 10], "delay": 24, "respawn": 240}, + {"type": "coin", "at": [43, 11]}, + {"type": "coin", "at": [44, 11]}, + {"type": "checkpoint", "at": [70, 11]}, + {"type": "door", "at": [86, 10], "key": "gold", "h": 2}, + {"type": "enemy", "at": [95, 11], "kind": "brute", "brain": "chase", "speed": 1.1, "range": 7, "hp": 2}, + {"type": "coin", "at": [8, 12]}, + {"type": "coin", "at": [10, 12]}, + {"type": "coin", "at": [12, 12]}, + {"type": "coin", "at": [14, 12]}, + {"type": "coin", "at": [16, 12]}, + {"type": "enemy", "at": [34, 13], "kind": "slime", "brain": "patrol", "speed": 0.6} + ] +} diff --git a/scripts/ledge/levels/2-3.json b/scripts/ledge/levels/2-3.json new file mode 100644 index 00000000000..e7453025891 --- /dev/null +++ b/scripts/ledge/levels/2-3.json @@ -0,0 +1,62 @@ +{ + "name": "Lever Works", + "theme": "cavern", + "par": 75, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [142, 8, 1, 2], + "spawn": [4, 11], + "tiles": [ + "######################################################################################################################################################", + "######################################################################################################################################################", + "...............................#......................................................................................................................", + "...............................#......................................................................................................................", + "...............................#......................................................................................................................", + "...............................#......................................................................................................................", + "...............................#......................................................................................................................", + "...............................#........................................#########.....................................................................", + "...............................#........................................H.................===.........................................................", + "........................................................................H.............................................................................", + "........................................................................H...........===.........................................######################", + "........................................................................H........................########################.......######################", + "###############################.########################.........################................########################.......######################", + "###############################.########################.........################^^^^^^^^^^^^^^^^########################.......######################", + "###############################.########################^^^^^^^^^################^^^^^^^^^^^^^^^^########################^^^^^^^######################", + "###############################.########################^^^^^^^^^################^^^^^^^^^^^^^^^^########################^^^^^^^######################" + ], + "entities": [ + {"type": "gem", "at": [76, 6]}, + {"type": "enemy", "at": [91, 7], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6}, + {"type": "coin", "at": [100, 8]}, + {"type": "coin", "at": [103, 8]}, + {"type": "coin", "at": [106, 8]}, + {"type": "coin", "at": [109, 8]}, + {"type": "coin", "at": [112, 8]}, + {"type": "coin", "at": [115, 8]}, + {"type": "coin", "at": [118, 8]}, + {"type": "coin", "at": [8, 9]}, + {"type": "coin", "at": [11, 9]}, + {"type": "coin", "at": [14, 9]}, + {"type": "coin", "at": [17, 9]}, + {"type": "coin", "at": [20, 9]}, + {"type": "coin", "at": [36, 9]}, + {"type": "coin", "at": [40, 9]}, + {"type": "coin", "at": [44, 9]}, + {"type": "coin", "at": [48, 9]}, + {"type": "coin", "at": [52, 9]}, + {"type": "heart", "at": [133, 9]}, + {"type": "crumble", "at": [58, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [59, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [60, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [61, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [62, 10], "delay": 24, "respawn": 240}, + {"type": "enemy", "at": [105, 10], "kind": "frog", "brain": "hopper", "interval": 80}, + {"type": "enemy", "at": [112, 10], "kind": "beetle", "brain": "walker", "speed": 0.8}, + {"type": "lever", "at": [24, 11], "channel": 1}, + {"type": "gate", "at": [31, 9], "channel": 1, "h": 3}, + {"type": "enemy", "at": [40, 11], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [48, 11], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "checkpoint", "at": [70, 11]} + ] +} diff --git a/scripts/ledge/levels/3-1.json b/scripts/ledge/levels/3-1.json new file mode 100644 index 00000000000..a2a9150bc70 --- /dev/null +++ b/scripts/ledge/levels/3-1.json @@ -0,0 +1,59 @@ +{ + "name": "Foundry Gate", + "theme": "foundry", + "par": 75, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [152, 6, 1, 2], + "spawn": [5, 11], + "tiles": [ + "................................................................................................................................................................", + "................................................................................................................................................................", + "................................................................................................................................................................", + "............................................................................#####...............................................................................", + "............................................................................#####...............................................................................", + "............................................................................#####...............................................................................", + "............................................................................#####..................=====..............=====.....................................", + "............................................................................#####...............................................................................", + "............................................................................#####.......................................................########################", + "...............................####################......................................................#####################..........########################", + "...............................####################......................................................#####################..........########################", + "...............................####################..........###############.##############..............#####################..........########################", + "#####################..........####################..........###############.##############....##........#####################..........########################", + "#####################....#.....####################..........###############.##############....##........#####################..........########################", + "#####################^^^^^^^^^^####################^^^^^^^^^^###############.##############^^^^^^^^^^^^^^#####################^^^^^^^^^^########################", + "#####################^^^^^^^^^^####################^^^^^^^^^^###############.##############^^^^^^^^^^^^^^#####################^^^^^^^^^^########################" + ], + "entities": [ + {"type": "coin", "at": [99, 4]}, + {"type": "coin", "at": [100, 4]}, + {"type": "coin", "at": [101, 4]}, + {"type": "coin", "at": [102, 4]}, + {"type": "coin", "at": [103, 4]}, + {"type": "coin", "at": [33, 7]}, + {"type": "coin", "at": [36, 7]}, + {"type": "coin", "at": [39, 7]}, + {"type": "coin", "at": [42, 7]}, + {"type": "heart", "at": [140, 7]}, + {"type": "enemy", "at": [46, 8], "kind": "turret", "brain": "turret", "interval": 90, "range": 12}, + {"type": "enemy", "at": [110, 8], "kind": "brute", "brain": "chase", "speed": 1.1, "range": 7, "hp": 2}, + {"type": "gem", "at": [120, 8]}, + {"type": "crumble", "at": [132, 9], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [133, 9], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [134, 9], "delay": 24, "respawn": 240}, + {"type": "coin", "at": [9, 10]}, + {"type": "coin", "at": [12, 10]}, + {"type": "coin", "at": [15, 10]}, + {"type": "coin", "at": [18, 10]}, + {"type": "checkpoint", "at": [64, 10]}, + {"type": "enemy", "at": [70, 10], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [88, 10], "kind": "turret", "brain": "turret", "interval": 90, "range": 12}, + {"type": "crumble", "at": [127, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [128, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [129, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [130, 10], "delay": 24, "respawn": 240}, + {"type": "spring", "at": [96, 11]}, + {"type": "spring", "at": [25, 12]} + ] +} diff --git a/scripts/ledge/levels/3-2.json b/scripts/ledge/levels/3-2.json new file mode 100644 index 00000000000..defc399b268 --- /dev/null +++ b/scripts/ledge/levels/3-2.json @@ -0,0 +1,63 @@ +{ + "name": "Smokestack", + "theme": "foundry", + "par": 70, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash", "jetpack"], + "goal": [112, 4, 1, 2], + "spawn": [4, 17], + "tiles": [ + "........................................................................................................................", + "........................................................................................................................", + "........................................................................................................................", + "........................................................................................................................", + "..........................................................###...........................................................", + "..........................................................###...........................................................", + "..........................................................###................................###########################", + "..........................................................###................................###########################", + ".........................................############.....###................................###########################", + ".........................................############.....###................................###########################", + ".........................................############.....###................................###########################", + "....................................====.############.....###...............=====............###########################", + ".........................................############.....###................................###########################", + ".......................########..........############........................................###########################", + ".......................########..........############..............##############............###########################", + ".......................########..====....############..............##############............###########################", + ".......................########..........############..............##############............###########################", + ".......................########..........############..............##############............###########################", + "#################......########..........############..............##############............###########################", + "#################......########..........############..............##############............###########################", + "#################^^^^^^########^^^^^^^^^^############^^^^^^^^^^^^^^##############^^^^^^^^^^^^###########################", + "#################^^^^^^########^^^^^^^^^^############^^^^^^^^^^^^^^##############^^^^^^^^^^^^###########################" + ], + "entities": [ + {"type": "enemy", "at": [59, 3], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6}, + {"type": "coin", "at": [96, 4]}, + {"type": "coin", "at": [99, 4]}, + {"type": "coin", "at": [102, 4]}, + {"type": "coin", "at": [105, 4]}, + {"type": "coin", "at": [108, 4]}, + {"type": "coin", "at": [42, 5]}, + {"type": "coin", "at": [45, 5]}, + {"type": "coin", "at": [48, 5]}, + {"type": "coin", "at": [51, 5]}, + {"type": "heart", "at": [100, 5]}, + {"type": "checkpoint", "at": [46, 7]}, + {"type": "crumble", "at": [89, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [90, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [91, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [84, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [85, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [86, 10], "delay": 24, "respawn": 240}, + {"type": "enemy", "at": [27, 12], "kind": "turret", "brain": "turret", "interval": 90, "range": 12}, + {"type": "enemy", "at": [73, 13], "kind": "beetle", "brain": "walker", "speed": 0.8}, + {"type": "gem", "at": [78, 13]}, + {"type": "coin", "at": [6, 15]}, + {"type": "coin", "at": [7, 15]}, + {"type": "coin", "at": [8, 15]}, + {"type": "coin", "at": [9, 15]}, + {"type": "coin", "at": [10, 15]}, + {"type": "powerup", "at": [12, 17], "name": "jetpack"} + ] +} diff --git a/scripts/ledge/levels/3-3.json b/scripts/ledge/levels/3-3.json new file mode 100644 index 00000000000..9c1e361f574 --- /dev/null +++ b/scripts/ledge/levels/3-3.json @@ -0,0 +1,57 @@ +{ + "name": "Molten Run", + "theme": "foundry", + "par": 85, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "goal": [163, 8, 1, 2], + "spawn": [5, 11], + "tiles": [ + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + ".................................................................................................................=====....................................................", + "...................................................................................................==.....................................................................", + "..........................................................................................................................................................................", + "..............................................................................................==......#################...................................................", + "......................................................................................................#################..................................#################", + "..................................................#################...................................#################..................................#################", + "###################........##############.........#################..........##############...........#################..........#################.......#################", + "###################........##############.........#################..........##############...........#################..........#################.......#################", + "###################^^^^^^^^##############^^^^^^^^^#################^^^^^^^^^^##############^^^^^^^^^^^#################^^^^^^^^^^#################^^^^^^^#################", + "###################^^^^^^^^##############^^^^^^^^^#################^^^^^^^^^^##############^^^^^^^^^^^#################^^^^^^^^^^#################^^^^^^^#################" + ], + "entities": [ + {"type": "gem", "at": [115, 5]}, + {"type": "enemy", "at": [62, 7], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6}, + {"type": "enemy", "at": [107, 8], "kind": "turret", "brain": "turret", "interval": 90, "range": 12}, + {"type": "enemy", "at": [137, 8], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6}, + {"type": "coin", "at": [78, 9]}, + {"type": "coin", "at": [80, 9]}, + {"type": "coin", "at": [82, 9]}, + {"type": "coin", "at": [84, 9]}, + {"type": "coin", "at": [86, 9]}, + {"type": "coin", "at": [88, 9]}, + {"type": "heart", "at": [157, 9]}, + {"type": "coin", "at": [8, 10]}, + {"type": "coin", "at": [10, 10]}, + {"type": "coin", "at": [12, 10]}, + {"type": "coin", "at": [14, 10]}, + {"type": "coin", "at": [16, 10]}, + {"type": "crumble", "at": [43, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [44, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [45, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [46, 10], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [47, 10], "delay": 24, "respawn": 240}, + {"type": "checkpoint", "at": [58, 10]}, + {"type": "enemy", "at": [33, 11], "kind": "frog", "brain": "hopper", "interval": 80}, + {"type": "enemy", "at": [80, 11], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [86, 11], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "checkpoint", "at": [132, 11]}, + {"type": "enemy", "at": [140, 11], "kind": "frog", "brain": "hopper", "interval": 80} + ] +} diff --git a/scripts/ledge/levels/4-1.json b/scripts/ledge/levels/4-1.json new file mode 100644 index 00000000000..92e2edd4490 --- /dev/null +++ b/scripts/ledge/levels/4-1.json @@ -0,0 +1,73 @@ +{ + "name": "Skyway", + "theme": "sky", + "depth": true, + "par": 60, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "platforms": [{"path": [[142, 9], [146, 6]], "w": 3, "speed": 0.8, "pause": 30}], + "goal": [162, 6, 1, 2], + "spawn": [5, 11], + "tiles": [ + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................=====..............===......................................####################", + "...................................................................===...............................................===........#############.........####################", + ".............................===...........................===..............===.....###########.................................#############.........####################", + ".....................===.............===....###########.............................###########.................................#############.........####################", + "#################...........................###########.............................###########.................................#############.........####################", + "#################...........................###########.............................###########.................................#############.........####################", + "#################...........................###########.............................###########.................................#############.........####################", + "#################...........................###########.............................###########.................................#############.........####################" + ], + "entities": [ + {"type": "coin", "at": [108, 6]}, + {"type": "coin", "at": [110, 6]}, + {"type": "coin", "at": [112, 6]}, + {"type": "coin", "at": [114, 6]}, + {"type": "coin", "at": [116, 6]}, + {"type": "coin", "at": [118, 6]}, + {"type": "coin", "at": [120, 6]}, + {"type": "coin", "at": [122, 6]}, + {"type": "coin", "at": [124, 6]}, + {"type": "coin", "at": [20, 7]}, + {"type": "coin", "at": [22, 7]}, + {"type": "coin", "at": [24, 7]}, + {"type": "coin", "at": [26, 7]}, + {"type": "coin", "at": [28, 7]}, + {"type": "coin", "at": [30, 7]}, + {"type": "coin", "at": [32, 7]}, + {"type": "coin", "at": [34, 7]}, + {"type": "coin", "at": [36, 7]}, + {"type": "coin", "at": [38, 7]}, + {"type": "coin", "at": [40, 7]}, + {"type": "gem", "at": [92, 7]}, + {"type": "crumble", "at": [98, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [99, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [100, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [101, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [102, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [103, 7], "delay": 24, "respawn": 240}, + {"type": "crumble", "at": [104, 7], "delay": 24, "respawn": 240}, + {"type": "heart", "at": [155, 7]}, + {"type": "coin", "at": [58, 8]}, + {"type": "coin", "at": [61, 8]}, + {"type": "coin", "at": [64, 8]}, + {"type": "coin", "at": [67, 8]}, + {"type": "coin", "at": [70, 8]}, + {"type": "coin", "at": [73, 8]}, + {"type": "coin", "at": [76, 8]}, + {"type": "coin", "at": [79, 8]}, + {"type": "enemy", "at": [134, 8], "kind": "bat", "brain": "flyer", "speed": 0.9, "range": 6}, + {"type": "checkpoint", "at": [88, 9]}, + {"type": "enemy", "at": [50, 10], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "powerup", "at": [12, 11], "name": "glide"} + ] +} diff --git a/scripts/ledge/levels/4-2.json b/scripts/ledge/levels/4-2.json new file mode 100644 index 00000000000..b15ac8d3d6c --- /dev/null +++ b/scripts/ledge/levels/4-2.json @@ -0,0 +1,43 @@ +{ + "name": "Cloudsteps", + "theme": "sky", + "depth": true, + "par": 70, + "health": 3, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "platforms": [{"path": [[17, 11], [29, 11]], "w": 3, "speed": 0.9, "pause": 25}, {"path": [[47, 10], [60, 7]], "w": 3, "speed": 0.9, "pause": 25}, {"path": [[79, 9], [93, 9]], "w": 3, "speed": 1.0, "pause": 20}, {"path": [[111, 9], [124, 6]], "w": 3, "speed": 0.9, "pause": 25}, {"path": [[141, 9], [150, 7]], "w": 3, "speed": 0.9, "pause": 25}], + "goal": [164, 5, 1, 2], + "spawn": [5, 11], + "tiles": [ + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "..........................................................................................................................................................................", + "............................................................................................................................................................##############", + "....................................................................#########...............................................................................##############", + "....................................................................#########.....................................................#########.................##############", + "..................................###########.......................#########.......................#########.....................#########.................##############", + "..................................###########.......................#########.......................#########.....................#########.................##############", + "###############...................###########.......................#########.......................#########.....................#########.................##############", + "###############...................###########.......................#########.......................#########.....................#########.................##############", + "###############...................###########.......................#########.......................#########.....................#########.................##############", + "###############...................###########.......................#########.......................#########.....................#########.................##############" + ], + "entities": [ + {"type": "gem", "at": [104, 4]}, + {"type": "checkpoint", "at": [72, 7]}, + {"type": "heart", "at": [134, 8]}, + {"type": "enemy", "at": [39, 9], "kind": "slime", "brain": "patrol", "speed": 0.6}, + {"type": "enemy", "at": [104, 9], "kind": "frog", "brain": "hopper", "interval": 80}, + {"type": "coin", "at": [8, 10]}, + {"type": "coin", "at": [9, 10]}, + {"type": "coin", "at": [10, 10]}, + {"type": "coin", "at": [11, 10]}, + {"type": "coin", "at": [12, 10]}, + {"type": "coin", "at": [13, 10]} + ] +} diff --git a/scripts/ledge/levels/5-1.json b/scripts/ledge/levels/5-1.json new file mode 100644 index 00000000000..3ede5f66bff --- /dev/null +++ b/scripts/ledge/levels/5-1.json @@ -0,0 +1,41 @@ +{ + "name": "The Forge Heart", + "theme": "forge", + "par": 90, + "health": 5, + "boss": true, + "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash", "weapon"], + "spawn": [5, 12], + "goal": [64, 11, 1, 2], + "tiles": [ + "######################################################################", + "######################################################################", + "##............................................................#.....##", + "##............................................................#.....##", + "##............................................................#.....##", + "##............................................................#.....##", + "##............................................................#.....##", + "##............................................................#.....##", + "##..........................========..........................#.....##", + "##........======....................................======....#.....##", + "##..................................................................##", + "##..................................................................##", + "##..................................................................##", + "######################################################################", + "######################################################################", + "######################################################################" + ], + "entities": [ + {"type": "coin", "at": [30, 5]}, + {"type": "coin", "at": [31, 5]}, + {"type": "coin", "at": [32, 5]}, + {"type": "coin", "at": [33, 5]}, + {"type": "coin", "at": [34, 5]}, + {"type": "coin", "at": [35, 5]}, + {"type": "heart", "at": [12, 8]}, + {"type": "heart", "at": [56, 8]}, + {"type": "enemy", "at": [40, 12], "kind": "golem", "brain": "boss", "hp": 8, "opens": 1, "w": 2, "h": 2, "speed": 1.0, "range": 14}, + {"type": "gate", "at": [62, 10], "channel": 1, "h": 3} + ] +} diff --git a/scripts/ledge/levels/demo/1-1.log b/scripts/ledge/levels/demo/1-1.log new file mode 100644 index 00000000000..930b91e8efc --- /dev/null +++ b/scripts/ledge/levels/demo/1-1.log @@ -0,0 +1 @@ +8*19,4*d,10*19,0*1,18*7,8*1,0*13,2*1b,6*17,2*10,11*c,41*15,62*9,100*19,4*a,62*10,81*c,6*c,32*10,6*c,62*1c,0*10,32*10,22*1,12*14,2*1,22*f,32*3,22*1,11*8,32*14,0*14,32*9,22*1,81*8,41*4,100*d,12*15,2*1,90*4,82*c,62*22,18*c,22*a,100*8,32*a,22*1,0*4,21*6,12*14,2*9,100*8,21*d,22*d,62*14,18*9,8*1,100*4,2*5,31*6,21*1,6*4,82*8,8*4,62*8,100*1b,62*c,81*9,32*f,22*1,100*a,8*d,62*4,32*4,62*18,31*7,21*1,11*8,8*12,2*14,90*c,4*9,31*8,0*1c,12*b,2*1,10*a,0*1,18*14,8*1,10*5,0*1,32*c,11*4,0*17,12*14,10*6,0*1,12*16,2*1,62*14,22*1c,100*12,62*1b,18*7,8*1,18*4,32*17,22*1,10*d,0*1,21*5,90*17,80*1,32*e,22*1,90*c,62*1b,0*4,90*c,4*13,10*4,0*1,18*10,8*1,22*13,11*3,1*1,82*10,11*15,1*1,62*4,22*1a,4*4,31*4,22*10,100*4,22*4,12*c,2*1,11*f,1*1,62*1b,8*4,82*10,11*10,4*10,10*2,0*1,2*10,6*9,2*4,62*10,32*19,22*1,4*10,82*11,4*16,8*d,11*8,62*19,0*4,12*8,90*2,80*1,0*9,22*4,32*6,22*1,62*12 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/1-2.log b/scripts/ledge/levels/demo/1-2.log new file mode 100644 index 00000000000..d2be86293cc --- /dev/null +++ b/scripts/ledge/levels/demo/1-2.log @@ -0,0 +1 @@ +8*19,4*d,10*19,0*1,18*7,8*1,0*13,2*1b,6*17,2*10,11*c,41*15,62*9,100*19,4*a,62*10,81*c,6*c,32*8,10*1b,0*1,6*16,18*c,8*1,11*4,81*14,2*5,6*20,2*4,31*a,21*1,100*4,62*9,18*c,2*9,11*12,1*1,62*9,11*f,1*1,12*3,2*1,11*15,1*1,4*1c,0*c,32*7,22*1,6*f,32*d,22*1,31*2,21*15,100*13,2*10,62*4,82*10,81*16,62*f,4*8,11*8,100*12,22*10,18*8,21*d,0*a,90*13,80*1,32*18,22*1,12*14,0*13,32*11,22*5,32*11,22*1,4*c,62*8,21*4,10*10,62*18,6*5,32*1a,22*1,90*17,80*1,2*8,32*e,22*1,21*13,12*1b,2*1,4*7,81*11,90*e,80*1,6*8,18*4,62*4,18*8,62*8,90*5,80*1,2*5,18*18,8*1,81*14,2*11,31*c,22*b,62*6,41*8,31*c,0*e,6*b,10*7,0*1,31*2,21*1,62*c,100*18,31*10,21*1,2*35,10*1a,0*1,82*3,22*10,4*4,11*5,1*1,4*4,6*1b,31*c,21*1,4*9,31*8,6*1a,0*1b,100*a,22*12,21*4,8*19,11*3,1*1,12*8,11*c,1*1,32*a,22*1,62*26,31*c,32*8,82*14,18*c,21*8,10*18,0*1,90*14,80*1,32*a,22*1,62*c,90*8,18*2,8*1,82*14,62*2 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/1-3.log b/scripts/ledge/levels/demo/1-3.log new file mode 100644 index 00000000000..225e650c603 --- /dev/null +++ b/scripts/ledge/levels/demo/1-3.log @@ -0,0 +1 @@ +18*5,8*1,18*4,100*10,62*1c,2*c,32*a,22*1,32*1c,62*8,8*5,22*c,0*1a,12*10,6*b,90*8,62*4,10*16,0*1,4*19,10*14,0*1,62*4,0*b,81*7,12*1b,2*1,6*12,32*b,22*1,32*14,12*e,2*1,8*6,82*14,8*1a,2*14,62*c,31*8,12*e,2*1,90*4,31*f,21*1,82*c,100*12,12*13,2*1,62*5,21*c,6*8,82*18,2*9,0*12,82*c,90*1a,80*1,8*6,62*18,31*8,62*a,2*4,32*8,22*1,32*6,22*1,18*c,62*f,100*8,2*5,100*15,62*4,82*8,90*8,80*1,62*c,10*4,12*13,2*1,62*4,32*c,22*f,32*19,22*1,81*3,2*4,62*14,32*19,22*1,81*4,82*c,12*c,90*4,32*10,62*8,6*5,8*1a,62*c,11*4,6*10,8*c,62*8,4*f,2*11,12*18,2*1,62*14,32*b,22*1,2*f,21*11,6*17,62*c,31*8,21*c,62*c,12*8,31*d,21*1,10*4,0*1,32*18,22*1,11*4,82*c,2*8,62*4,6*14,90*18,32*b,22*1,21*4,32*15,22*1,81*c,12*13,2*1,8*10,2*1c,12*6 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/1-4.log b/scripts/ledge/levels/demo/1-4.log new file mode 100644 index 00000000000..42e2a53dd03 --- /dev/null +++ b/scripts/ledge/levels/demo/1-4.log @@ -0,0 +1 @@ +8*19,4*d,10*19,0*1,18*7,8*1,0*13,2*1b,6*17,2*10,11*c,6*c,32*18,4*4,32*8,2*17,90*1a,80*1,32*19,22*1,6*f,32*c,0*14,32*9,22*1,81*4,100*13,2*10,62*4,82*10,81*16,62*f,4*4,11*11,1*1,12*c,100*12,22*10,18*12,8*1,10*c,21*d,0*a,90*13,80*1,32*18,22*1,12*10,0*10,12*9,2*1,12*3,2*1,90*a,80*1,32*11,22*13,11*4,12*12,2*1,18*4,22*1b,18*c,22*18,11*7,1*1,31*4,82*1b,81*b,4*17,22*16,2*17,100*c,62*3,12*4,22*13,12*c,90*a,80*1,82*d,12*16,2*1,32*c,12*b,2*1,4*9,12*10,2*8,4*4,22*4,21*7,82*33,62*c,0*4,21*8,32*8,22*1,100*8,12*10,2*1,18*8,62*18,31*c,82*a,0*8,62*12,18*10,8*1,22*12,100*8,32*a,22*1,0*4,4*17,18*7,8*1,31*8,18*7,8*1,62*b,8*4,2*16,6*f,12*c,62*8,21*c,100*4,12*11,2*1,12*4,62*18,8*12,2*14,90*4,82*e,81*4,100*d,32*a,22*1,12*1b,2*1,11*8,12*4,10*6,0*1,12*16,2*1,62*14,22*17 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/2-1.log b/scripts/ledge/levels/demo/2-1.log new file mode 100644 index 00000000000..45fece2726d --- /dev/null +++ b/scripts/ledge/levels/demo/2-1.log @@ -0,0 +1 @@ +8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*17,2*8,11*c,6*c,32*22,22*1,12*8,2*1,0*4,11*8,82*13,6*e,62*9,18*8,11*4,32*19,22*1,6*f,32*d,22*1,31*2,21*5,82*10,81*16,62*f,4*4,11*11,1*1,12*1a,2*1,12*8,2*1,32*8,22*1,11*4,100*12,22*10,18*12,8*1,10*4,21*d,0*a,90*13,80*1,32*18,22*1,12*10,0*13,32*11,22*b,6*c,18*c,31*1a,21*1,6*11,32*2,22*1,31*7,21*1,62*17,12*14,2*14,10*18,0*1,82*4,81*6,10*3,0*1,32*14,31*a,21*1,82*10,12*15,2*1,10*15,0*1,6*19,10*4,0*4,82*c,6*17,11*5,1*1,11*d,1*1,22*1b,18*4,81*14,62*c,41*c,62*1c,31*8,32*a,22*1,10*8,32*15,22*1,10*4,22*1a,32*14,22*1,8*3,100*4,12*1b,2*1,4*27,6*1b,82*2f,0*4,81*8,62*1c,21*c,12*12,2*1,11*4,1*1,32*16,22*1,32*8,22*1,10*14,0*1,90*4,6*12,31*4,8*6,32*5,22*1,2*c,90*10,4*a,0*18,62*4,81*8,6*c,62*a,22*1b,62*c \ No newline at end of file diff --git a/scripts/ledge/levels/demo/2-2.log b/scripts/ledge/levels/demo/2-2.log new file mode 100644 index 00000000000..25fe8e96582 --- /dev/null +++ b/scripts/ledge/levels/demo/2-2.log @@ -0,0 +1 @@ +8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*17,2*8,11*c,6*c,32*18,22*1,81*4,2*4,31*8,82*10,81*16,62*c,12*10,2*c,12*4,90*8,6*8,2*1a,12*9,2*1,21*4,82*12,2*4,4*b,11*8,8*11,2*18,32*3,22*1,81*8,12*12,2*1,18*4,6*18,2*14,0*3,2*c,6*12,100*e,0*4,22*a,12*c,90*4,80*1,10*4,8*b,11*15,1*1,11*f,1*1,12*1b,2*1,31*13,21*1,62*14,10*4,100*14,32*d,22*1,0*10,32*f,22*1,18*3,8*1,22*11,82*8,8*3,6*c,0*c,18*19,8*1,100*19,62*7,10*4,22*24,32*8,4*8,31*4,2*17,90*5,80*1,82*10,21*5,22*15,12*13,2*1,12*13,2*1,11*c,32*15,22*1,32*18,22*1,18*4,62*8,81*6,22*14,18*13,8*1,12*15,2*1,90*a,80*1,4*4,32*e,22*1,10*f,0*1,22*12,6*4,62*8,100*12,0*9,82*18,12*c,6*15,82*14,10*4,22*18,18*8,2*d,62*2e,18*4,100*11,2*a,22*e,21*4,18*15,8*1,22*13,90*8,80*1,22*c,62*18,22*8 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/2-3.log b/scripts/ledge/levels/demo/2-3.log new file mode 100644 index 00000000000..1c39946b222 --- /dev/null +++ b/scripts/ledge/levels/demo/2-3.log @@ -0,0 +1 @@ +8*19,4*d,10*c,0*13,2*1b,6*17,2*c,11*c,6*c,32*10,62*c,22*12,8*2b,32*18,22*1,62*c,100*1a,90*a,80*1,18*4,21*16,100*c,22*19,18*15,8*1,62*22,10*4,41*1c,82*5,100*1c,62*8,6*17,10*c,21*c,62*f,11*4,62*c,31*5,21*1,10*10,82*1b,8*1b,6*3,62*1f,32*8,18*a,8*1,90*c,21*c,11*2,1*1,31*18,21*1,62*d,6*14,2*c,6*3,22*14,6*4,32*e,22*1,31*1b,21*1,82*17,11*8,1*1,82*10,62*6,31*c,22*4,12*3,2*1,62*e,4*4,22*14,4*4,90*a,80*1,81*10,6*18,11*d,1*1,82*3,62*5,82*8,41*b,32*d,22*1,0*c,22*14,32*3,22*1,4*4,18*21,8*1,31*14,21*1,90*4,21*15,22*1f,62*19,90*20,80*1,32*a,22*1,62*f,81*8,32*19,22*1,82*8,90*13,80*1,18*2,8*1,82*14,32*1b,22*1,11*4,12*12,2*1,100*c,62*e,32*7,22*1,0*e,6*10,100*18,82*10,2*c,22*c,12*8,6*5,8*1a,2*13,22*3,100*4,11*8,4*9,8*1c,4*c,12*10,11*e,1*1,12*5,2*15,12*5,2*1,6*8,12*9,2*1,82*13,22*1b,82*7,31*4,12*a,2*1,10*6,0*1,62*1c,11*15,1*1,2*c,12*11,2*1,62*d,4*c,10*13,0*1,90*18,80*1,82*c,12*13,2*1,8*8,32*17,22*1,18*5,8*2 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/3-1.log b/scripts/ledge/levels/demo/3-1.log new file mode 100644 index 00000000000..b5d723f7dc6 --- /dev/null +++ b/scripts/ledge/levels/demo/3-1.log @@ -0,0 +1 @@ +8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*17,2*8,11*c,6*c,32*18,4*8,6*1c,11*8,31*8,21*d,0*a,90*13,80*1,32*18,22*c,10*8,0*1,81*21,32*e,22*1,32*10,18*18,22*17,90*8,12*b,2*1,22*8,21*4,82*17,31*8,82*11,32*4,82*9,31*c,21*1,62*9,21*c,32*8,22*1,100*4,12*10,2*1,18*10,90*c,6*1b,32*18,22*1,10*1a,0*1,10*4,62*18,41*8,10*5,0*1,4*4,62*12,18*8,22*a,100*8,32*a,22*1,0*4,21*6,12*10,2*9,100*8,21*d,22*d,62*2c,18*9,8*1,100*4,2*5,31*6,21*1,6*4,82*8,18*7,8*1,62*b,8*9,82*c,8*f,62*13,8*b,11*c,62*d,90*4,80*1,81*4,2*1a,81*c,62*c,18*c,8*1,32*c,22*1,18*7,8*1,10*4,8*2b,62*c,22*6,41*4,12*3,2*1,8*b,100*c,62*c,22*14,4*4,90*8,10*f,0*1,22*14,21*3,2*8,32*3,22*1,90*6,80*1,18*c,22*c,31*8,32*9,22*1,32*8,8*5,90*c,12*9,2*1,32*f,22*1,100*9,81*8,4*6,21*e,18*10,62*18,21*4,82*c,10*8,2*d,82*4,21*a,2*a,100*4,22*d,2*19,21*3,12*14,2*1,4*13,62*c,82*9,41*4,6*8,0*b,12*12,2*1,82*7 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/3-2.log b/scripts/ledge/levels/demo/3-2.log new file mode 100644 index 00000000000..7d26fde37ea --- /dev/null +++ b/scripts/ledge/levels/demo/3-2.log @@ -0,0 +1 @@ +8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*4,10*4,82*1a,21*16,62*15,12*11,2*1,31*c,41*8,90*13,80*1,18*2,8*1,82*14,32*14,62*4,82*7,10*4,12*1b,2*1,90*4,62*14,6*5,21*4,10*a,0*1,10*8,18*d,8*1,62*8,2*11,22*c,12*10,2*1,0*a,11*8,18*3,8*1,62*14,11*8,12*c,2*1,12*8,2*1,82*10,62*a,31*14,21*7,6*19,100*8,22*c,32*f,22*1,18*4,10*9,0*1,2*4,62*c,6*8,22*10,18*4,2*c,62*29,12*18,2*1,12*3,2*1,12*13,2*18,62*8,2*4,90*8,22*1a,10*c,32*8,22*8,18*5,8*1,4*4,62*6,2*18,18*17,8*1,2*15,100*4,12*c,2*1,100*10,62*12,32*17,22*1,18*14,8*1,62*8,6*8,10*13,0*1,12*d,2*1,81*18,32*18,22*1,6*10,22*4 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/3-3.log b/scripts/ledge/levels/demo/3-3.log new file mode 100644 index 00000000000..9f73dc6c640 --- /dev/null +++ b/scripts/ledge/levels/demo/3-3.log @@ -0,0 +1 @@ +8*19,4*d,10*c,0*13,2*1b,6*17,2*c,11*c,6*c,32*18,22*1,81*4,4*9,11*8,62*1c,0*10,32*10,22*1,12*14,2*1,22*f,32*3,22*1,11*8,32*19,22*1,6*f,32*d,22*1,31*2,21*d,11*11,1*1,12*1a,2*1,12*8,2*1,32*8,22*1,11*c,0*13,32*11,22*9,100*c,32*2,22*1,31*7,21*1,62*17,12*14,31*a,21*1,82*10,21*4,12*8,90*14,22*14,10*8,0*1,81*15,11*8,32*e,22*1,32*10,22*1,12*b,2*1,82*4,21*1a,81*14,62*14,22*8,62*10,10*8,32*19,22*1,4*8,6*8,12*c,100*4,12*11,2*1,12*c,2*4,31*b,21*1,18*c,8*1,22*8,62*c,100*1b,62*14,18*c,41*4,81*c,10*10,4*19,32*a,22*1,6*4,22*8,90*4,12*10,81*11,62*4,18*6,8*1,90*8,62*4,2*8,62*1b,32*17,22*1,62*e,8*8,21*8,82*c,2*4,31*4,21*1,22*4,62*18,81*4,18*c,82*8,62*14,18*b,8*1,62*8,82*4,62*8,82*10,90*c,100*12,12*13,2*1,62*5,21*8,22*8,6*8,82*1b,10*c,2*4,12*c,2*1,22*11,2*c,31*8,6*1c,0*5,11*c,21*7,41*10,8*1b,82*b,32*10,12*7,2*1,32*11,22*d,62*17,8*1a,32*d,22*1,90*19,80*1,2*1b,11*4,22*c,10*6,0*1,4*c \ No newline at end of file diff --git a/scripts/ledge/levels/demo/4-1.log b/scripts/ledge/levels/demo/4-1.log new file mode 100644 index 00000000000..0922b07c8b6 --- /dev/null +++ b/scripts/ledge/levels/demo/4-1.log @@ -0,0 +1 @@ +8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*4,82*9,62*8,22*3,32*1b,22*1,81*4,12*c,2*1,11*f,1*1,62*c,11*7,1*1,2*14,12*5,2*1,31*c,22*8,62*12,12*9,2*1,31*6,21*1,11*4,4*6,21*c,32*15,22*1,8*21,22*c,11*10,1*1,4*13,62*f,10*4,22*5,18*16,8*1,82*1b,4*4,62*a,32*9,22*1,81*4,90*17,80*1,82*17,22*c,31*c,32*9,22*1,12*c,2*1,4*b,22*16,81*4,32*1b,22*1,2*8,11*4,4*8,11*c,6*19,12*c,2*1,32*c,62*1c,2*d,32*12,22*1,2*6,22*4,62*6,6*4,100*b,6*16,100*4,12*3,2*1,18*8,0*11,8*22,12*6,2*5,82*c,10*8,32*18,22*1,8*3,4*4,31*c,32*6,22*1,62*c,8*11,12*14,81*f,32*1b,22*1,31*14,21*1,2*10,11*4,22*10,12*3,2*1,32*7,22*1,32*3,22*1,62*9,11*4,90*12,80*1,22*a,2*18,81*4,18*8,8*1,4*11,2*4,90*b,80*1,32*11,22*1,62*4,11*8,2*f,62*11,32*18,8*10,12*8,62*b,2*4,82*3,32*1a,22*1,32*17,22*1,18*4,10*4,12*14,6*9,31*8,8*f,81*4,31*14,21*1,81*8,90*16,80*1,62*f,31*d,21*1,22*8,32*14,10*14,62*10,31*9,21*1,2*4,62*6,81*3,100*d,10*3,0*1,18*2,8*1,62*c,8*5,90*4,8*1a,62*7,12*f,2*1,21*4,0*13,62*5 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/4-2.log b/scripts/ledge/levels/demo/4-2.log new file mode 100644 index 00000000000..b80c6887b93 --- /dev/null +++ b/scripts/ledge/levels/demo/4-2.log @@ -0,0 +1 @@ +10*c,6*4,2*8,62*e,0*4,6*9,62*10,11*8,6*14,62*11,12*1a,2*1,90*16,80*1,21*8,62*c,22*a,4*14,8*e,12*3,2*1,90*8,62*13,22*3,100*4,18*4,2*1c,82*18,62*a,90*15,80*1,22*8,18*d,8*1,62*1a,12*3,2*1,81*4,82*7,32*12,22*1,12*c,62*6,8*4,62*e,32*4,6*d,82*c,62*5,22*f,82*c,62*c,12*1a,2*1,32*6,22*1,62*8,22*8,32*4,22*c,62*17,10*4,2*20,32*9,22*1,81*4,32*f,22*11,100*12,32*1b,22*1,62*6,82*8,32*13,22*1,41*13,22*16,4*14,12*12,2*1,8*10,18*4,32*f,22*1,10*8,62*e,21*8,41*17,12*17,2*1,100*2e,18*c,82*1c,62*c,12*c,82*10,32*b,22*1,62*16,4*7,82*9,12*1a,2*1,32*1a,22*1,4*8,6*4,82*12,10*4,4*a,62*6,22*d,82*3,10*4,6*5 \ No newline at end of file diff --git a/scripts/ledge/levels/demo/5-1.log b/scripts/ledge/levels/demo/5-1.log new file mode 100644 index 00000000000..852b253009e --- /dev/null +++ b/scripts/ledge/levels/demo/5-1.log @@ -0,0 +1 @@ +8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,10*1b,0*1,6*16,18*c,8*1,11*10,62*18,18*4,2*14,90*f,80*1,11*c,2*17,62*6,90*b,80*1,82*12,32*14,22*1,21*8,4*17,2*17,81*19,11*21,1*1,31*18,18*d,8*1,22*8,41*4,32*f,22*1,32*c,8*c,32*16,22*16,2*c,32*12,22*1,8*8,22*12,8*4,82*9,62*17,18*3,8*1,41*10,8*10,32*6,22*1,11*13,1*1,32*11,22*1,2*c,6*1b,90*4,0*3,22*2d,81*4,62*1b,90*11,80*1,90*4,2*6,0*5,18*c,8*1,62*4,4*8,21*e,100*1b,6*14,2*c,82*10,18*4,10*1a,0*1,62*e \ No newline at end of file diff --git a/scripts/ledge/levels/src/1-1.sketch b/scripts/ledge/levels/src/1-1.sketch new file mode 100644 index 00000000000..437fff8cc91 --- /dev/null +++ b/scripts/ledge/levels/src/1-1.sketch @@ -0,0 +1,19 @@ +{"name": "First Light", "theme": "meadow", "par": 40, "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +............................................................................................................................................ +............................................................................................................................................ +............................................................................................................................................ +............................................................................................................................................ +............................................................................................................................................ +...........................................................*................................................................................ +.........................................................======............................................................................. +............................................................................ooo............................................................. +...........................................ooo.............................=====..........................o.o.o............................... +.................ooo..................................................................................................................X..... +..............................................................................................#####.........................ooo..........##### +.......................ab####...............................................................######.......................######.......###### +.....S........ooo..ab########b.............o.o.....e...................#######...........#########......e.............#######.......####### +...............ab#############b.........#############..........##############c..........##########.....###########....########^^^^^^^######## +###############################.......################.....#####################d.....##############...############....######################## +###############################.......################.....########################...##############...############....######################## diff --git a/scripts/ledge/levels/src/1-2.sketch b/scripts/ledge/levels/src/1-2.sketch new file mode 100644 index 00000000000..2c352a7cce7 --- /dev/null +++ b/scripts/ledge/levels/src/1-2.sketch @@ -0,0 +1,19 @@ +{"name": "Ladder Hill", "theme": "meadow", "par": 55, "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +................................................................................................................................... +.............................................ooo.........................................*........................................ +..........................................=========.....................................####....................................... +.......................................................................................##..##...................................... +...........................ooo.......H.................H.................................................ooo...........X.......... +.........................=======.....H.......e.........H...........ooo..................................=====........#####......... +.....................................H#################H.........=======..........C.................................######......... +.....................................H.................H..........................####.............................#######......... +.................ooo.................H.................H....................e....######.......e.....=====.........########......... +................=====................H.................H.............############################################.#########......... +.......S.............................H.....o.o.o.......H...........................................................##########......... +...............................=========.........=========....................................................h...###########........ +######################.......##########.....V.......########.....................................................############........ +######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############........ +######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############........ +######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############........ diff --git a/scripts/ledge/levels/src/1-3.sketch b/scripts/ledge/levels/src/1-3.sketch new file mode 100644 index 00000000000..33dfaf2f2bc --- /dev/null +++ b/scripts/ledge/levels/src/1-3.sketch @@ -0,0 +1,25 @@ +{"name": "Drifting Isles", "theme": "meadow", "par": 60, "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], + "platforms": [ + {"path": [[19, 11], [34, 11]], "w": 3, "speed": 0.8, "pause": 30}, + {"path": [[48, 12], [48, 6]], "w": 3, "speed": 0.7, "pause": 40}, + {"path": [[81, 9], [95, 9]], "w": 3, "speed": 1.0, "pause": 20}, + {"path": [[108, 10], [108, 6]], "w": 3, "speed": 0.7, "pause": 30}, + {"path": [[127, 10], [131, 5]], "w": 3, "speed": 0.8, "pause": 30}]} +--- +...................................................................................................................................................... +...................................................................................................................................................... +.............................................................................................................................oooooo................... +.........................................................ooooo..............................................................................*......... +...................................................................................................................................................... +........................................................#######..................................................................................X.... +........................................................#######.........................oooooo..........................................############## +........................................................#######.......................................C.................................############## +........................................................#######.....................................######..............................############## +....................o.o.o.o.o.o.o.o.....................#######.....................................######..............................############## +........................................................#######...........e.........................######...............w..............############## +.......S................................................#######.........#######.....................######............#######...........############## +################........................######..........#######.........#######.....................######............#######...........############## +################........................######..........#######.........#######.....................######............#######...........############## +################^^^^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^#######^^^^^^^^^#######^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^^^#######^^^^^^^^^^^############## +################^^^^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^#######^^^^^^^^^#######^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^^^#######^^^^^^^^^^^############## diff --git a/scripts/ledge/levels/src/1-4.sketch b/scripts/ledge/levels/src/1-4.sketch new file mode 100644 index 00000000000..8d5bec53801 --- /dev/null +++ b/scripts/ledge/levels/src/1-4.sketch @@ -0,0 +1,19 @@ +{"name": "Thornwood", "theme": "meadow", "par": 75, "health": 3, "tuning": {"maxJumps": 2}, + "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +............................................................................................................................................................ +............................................................................................................................................................ +...............................................................................................V.................................................... +.................................................................................................................................ooo.................. +......................................................V.......................................................................=======................. +......................................................................ooo.........................................................................X... +.........................................ooo.........................=====............................C...................................#########.. +.....................................................................................................####......................s.........#########.. +......................ooo............#########.......................................F.............######.............e......####.......#########.. +.......S.............................#########..................................##########..........######..........######....####......##########.. +.................................e...#########..............w..................##########..........######.........#######....####.....###########.. +...........................##############....##..........########.............##########..........######.........#######....####....############.. +##############......##########################.....e....###########.........##############.........######.....h...#######....####...#############.. +##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.. +##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.. +##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.. diff --git a/scripts/ledge/levels/src/2-1.sketch b/scripts/ledge/levels/src/2-1.sketch new file mode 100644 index 00000000000..0522335da1d --- /dev/null +++ b/scripts/ledge/levels/src/2-1.sketch @@ -0,0 +1,18 @@ +{"name": "Echo Caves", "theme": "cavern", "par": 70, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +###################################################################################################################################################### +###################################################################################################################################################### +...................................................................................................................................................... +...................................................................................................................................................... +.....................................############...........===========...o.o.o.o.o.o.o.o.o.o.o.............*......................................... +.....................................############.................H.......................................=====....................................... +.....................................############.................H.....%%%%%%%%%%%%%%%%%%%%%%%%.......B......................ooooooooo............... +........................................H.........................H.............................###############....................................... +........................................H...........oooooo........H.............................###############.......====..................X......... +........................................H.......................C.H.............................###############............########################### +.................ooooo.................oooooooo............############.........................###############.=====......########################### +.....S........................e.............F.....%%%%%%%%%############.........................###############............########################### +###############%%%%%%%%##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############............########################### +###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^########################### +###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^########################### +###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^########################### diff --git a/scripts/ledge/levels/src/2-2.sketch b/scripts/ledge/levels/src/2-2.sketch new file mode 100644 index 00000000000..b280d33bd93 --- /dev/null +++ b/scripts/ledge/levels/src/2-2.sketch @@ -0,0 +1,20 @@ +{"name": "Locked Deep", "theme": "cavern", "par": 80, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +############################################################################################################################################ +############################################################################################################################################ +......................................................................................#..................................................... +.........................................####################.........................#..................................................... +.........................................#............................................#..................................................... +.........................................#............................................#..................................................... +.........................................#............................................#..................................................... +.........................................#.oo......w...k..............................#..................................................... +.........................................#....###############.........................#..................................................... +.........................................#....###############.........................#.............*........%%%........h...........X....... +.........................................#....###############...........o.o.o.o.o.................=====..%%%.....########################### +.........................................#.oo.###############.........C...............D........B.................########################### +........o.o.o.o.o.............................###############======###################.##################........########################### +....S.............................e...........###############......###################.##################........########################### +#####################.......#################################......###################.##################........########################### +#####################.......#################################......###################.##################........########################### +#####################^^^^^^^#################################^^^^^^###################.##################^^^^^^^^########################### +#####################^^^^^^^#################################^^^^^^###################.##################^^^^^^^^########################### diff --git a/scripts/ledge/levels/src/2-3.sketch b/scripts/ledge/levels/src/2-3.sketch new file mode 100644 index 00000000000..e071b7a3458 --- /dev/null +++ b/scripts/ledge/levels/src/2-3.sketch @@ -0,0 +1,18 @@ +{"name": "Lever Works", "theme": "cavern", "par": 75, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +###################################################################################################################################################### +###################################################################################################################################################### +...............................#...................................................................................................................... +...............................#...................................................................................................................... +...............................#...................................................................................................................... +...............................#...................................................................................................................... +...............................#............................................*......................................................................... +...............................#........................................#########..........V.......................................................... +...............................#........................................H.................===.......o..o..o..o..o..o..o............................... +........o..o..o..o..o...............o...o...o...o...o...................H............................................................h........X....... +..........................................................%%%%%.........H...........===..................F......w...............###################### +....S...................L......|........e.......e.....................C.H........................########################.......###################### +###############################.########################.........################................########################.......###################### +###############################.########################.........################^^^^^^^^^^^^^^^^########################.......###################### +###############################.########################^^^^^^^^^################^^^^^^^^^^^^^^^^########################^^^^^^^###################### +###############################.########################^^^^^^^^^################^^^^^^^^^^^^^^^^########################^^^^^^^###################### diff --git a/scripts/ledge/levels/src/3-1.sketch b/scripts/ledge/levels/src/3-1.sketch new file mode 100644 index 00000000000..95cd3931487 --- /dev/null +++ b/scripts/ledge/levels/src/3-1.sketch @@ -0,0 +1,18 @@ +{"name": "Foundry Gate", "theme": "foundry", "par": 75, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +................................................................................................................................................................ +................................................................................................................................................................ +................................................................................................................................................................ +............................................................................#####............................................................................... +............................................................................#####..................ooooo........................................................ +............................................................................#####............................................................................... +............................................................................#####..................=====..............=====..................................... +.................................o..o..o..o.................................#####...........................................................h...........X....... +..............................................T.............................#####.............................B.........*...............######################## +...............................####################......................................................#####################......%%%.######################## +.........o..o..o..o............####################.............C.....e.................T................#####################.%%%%.....######################## +.....S.........................####################..........###############.##############.....s........#####################..........######################## +#####################....s.....####################..........###############.##############....##........#####################..........######################## +#####################....#.....####################..........###############.##############....##........#####################..........######################## +#####################^^^^^^^^^^####################^^^^^^^^^^###############.##############^^^^^^^^^^^^^^#####################^^^^^^^^^^######################## +#####################^^^^^^^^^^####################^^^^^^^^^^###############.##############^^^^^^^^^^^^^^#####################^^^^^^^^^^######################## diff --git a/scripts/ledge/levels/src/3-2.sketch b/scripts/ledge/levels/src/3-2.sketch new file mode 100644 index 00000000000..f23304ed8b9 --- /dev/null +++ b/scripts/ledge/levels/src/3-2.sketch @@ -0,0 +1,24 @@ +{"name": "Smokestack", "theme": "foundry", "par": 70, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash", "jetpack"]} +--- +........................................................................................................................ +........................................................................................................................ +........................................................................................................................ +...........................................................V............................................................ +..........................................................###...................................o..o..o..o..o........... +..........................................o..o..o..o......###.......................................h...........X....... +..........................................................###................................########################### +..............................................C...........###............................%%%.########################### +.........................................############.....###................................########################### +.........................................############.....###................................########################### +.........................................############.....###.......................%%%......########################### +....................................====.############.....###...............=====............########################### +...........................T.............############.....###................................########################### +.......................########..........############....................w....*..............########################### +.......................########..........############..............##############............########################### +......ooooo............########..====....############..............##############............########################### +.......................########..........############..............##############............########################### +....S.......J..........########..........############..............##############............########################### +#################......########..........############..............##############............########################### +#################......########..........############..............##############............########################### +#################^^^^^^########^^^^^^^^^^############^^^^^^^^^^^^^^##############^^^^^^^^^^^^########################### +#################^^^^^^########^^^^^^^^^^############^^^^^^^^^^^^^^##############^^^^^^^^^^^^########################### diff --git a/scripts/ledge/levels/src/3-3.sketch b/scripts/ledge/levels/src/3-3.sketch new file mode 100644 index 00000000000..dcab1509145 --- /dev/null +++ b/scripts/ledge/levels/src/3-3.sketch @@ -0,0 +1,18 @@ +{"name": "Molten Run", "theme": "foundry", "par": 85, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"]} +--- +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +...................................................................................................................*...................................................... +.................................................................................................................=====.................................................... +..............................................................V....................................==..................................................................... +...........................................................................................................T.............................V................................ +..............................................................................o.o.o.o.o.o.....==......#################......................................h.....X...... +........o.o.o.o.o..........................%%%%%..........C...........................................#################..................................################# +.....S...........................F................#################.............e.....e...............#################.............C.......F............################# +###################........##############.........#################..........##############...........#################..........#################.......################# +###################........##############.........#################..........##############...........#################..........#################.......################# +###################^^^^^^^^##############^^^^^^^^^#################^^^^^^^^^^##############^^^^^^^^^^^#################^^^^^^^^^^#################^^^^^^^################# +###################^^^^^^^^##############^^^^^^^^^#################^^^^^^^^^^##############^^^^^^^^^^^#################^^^^^^^^^^#################^^^^^^^################# diff --git a/scripts/ledge/levels/src/4-1.sketch b/scripts/ledge/levels/src/4-1.sketch new file mode 100644 index 00000000000..593f43d7428 --- /dev/null +++ b/scripts/ledge/levels/src/4-1.sketch @@ -0,0 +1,18 @@ +{"name": "Skyway", "theme": "sky", "depth": true, "par": 60, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], "platforms": [{"path": [[142, 9], [146, 6]], "w": 3, "speed": 0.8, "pause": 30}]} +--- +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +............................................................................................................o.o.o.o.o.o.o.o.o............................................. +....................o.o.o.o.o.o.o.o.o.o.o...................................................*.....%%%%%%%..................................................h......X....... +..........................................................o..o..o..o..o..o..o..o..........=====..............===......................V...............#################### +...................................................................===..................C............................===........#############.........#################### +.............................===..................e........===..............===.....###########.................................#############.........#################### +.....S......G........===.............===....###########.............................###########.................................#############.........#################### +#################...........................###########.............................###########.................................#############.........#################### +#################...........................###########.............................###########.................................#############.........#################### +#################...........................###########.............................###########.................................#############.........#################### +#################...........................###########.............................###########.................................#############.........#################### diff --git a/scripts/ledge/levels/src/4-2.sketch b/scripts/ledge/levels/src/4-2.sketch new file mode 100644 index 00000000000..3f76ebb5b44 --- /dev/null +++ b/scripts/ledge/levels/src/4-2.sketch @@ -0,0 +1,18 @@ +{"name": "Cloudsteps", "theme": "sky", "depth": true, "par": 70, "health": 3, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash"], "platforms": [{"path": [[17, 11], [29, 11]], "w": 3, "speed": 0.9, "pause": 25}, {"path": [[47, 10], [60, 7]], "w": 3, "speed": 0.9, "pause": 25}, {"path": [[79, 9], [93, 9]], "w": 3, "speed": 1.0, "pause": 20}, {"path": [[111, 9], [124, 6]], "w": 3, "speed": 0.9, "pause": 25}, {"path": [[141, 9], [150, 7]], "w": 3, "speed": 0.9, "pause": 25}]} +--- +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +.......................................................................................................................................................................... +........................................................................................................*................................................................. +.......................................................................................................................................................................... +....................................................................................................................................................................X..... +........................................................................C...................................................................................############## +....................................................................#########.........................................................h.....................############## +.......................................e............................#########...........................F.........................#########.................############## +........oooooo....................###########.......................#########.......................#########.....................#########.................############## +.....S............................###########.......................#########.......................#########.....................#########.................############## +###############...................###########.......................#########.......................#########.....................#########.................############## +###############...................###########.......................#########.......................#########.....................#########.................############## +###############...................###########.......................#########.......................#########.....................#########.................############## +###############...................###########.......................#########.......................#########.....................#########.................############## diff --git a/scripts/ledge/levels/src/5-1.sketch b/scripts/ledge/levels/src/5-1.sketch new file mode 100644 index 00000000000..52ee40c7f58 --- /dev/null +++ b/scripts/ledge/levels/src/5-1.sketch @@ -0,0 +1,18 @@ +{"name": "The Forge Heart", "theme": "forge", "par": 90, "health": 5, "boss": true, "tuning": {"maxJumps": 2}, "abilities": ["move", "ladder", "walljump", "jump", "crouch", "dash", "weapon"]} +--- +###################################################################### +###################################################################### +##............................................................#.....## +##............................................................#.....## +##............................................................#.....## +##............................oooooo..........................#.....## +##............................................................#.....## +##............................................................#.....## +##..........h...............========....................h.....#.....## +##........======....................................======....#.....## +##..................................................................## +##..................................................................## +##...S..................................Z.....................|.X...## +###################################################################### +###################################################################### +###################################################################### diff --git a/scripts/ledge/pom.xml b/scripts/ledge/pom.xml new file mode 100644 index 00000000000..61b1822aec0 --- /dev/null +++ b/scripts/ledge/pom.xml @@ -0,0 +1,314 @@ + + 4.0.0 + com.codenameone.examples.ledge + ledge + 1.0-SNAPSHOT + pom + ledge + ledge + https://www.codenameone.com + + + MIT No Attribution + https://opensource.org/license/mit-0 + repo + The same terms as the LICENSE file beside this pom + + + + + shared + common + + + 8.0-SNAPSHOT + 8.0-SNAPSHOT + UTF-8 + 1.8 + 11 + 1.7.11 + 3.8.0 + 1.8 + 1.8 + 1.8 + ledge + + + + + com.codenameone + java-runtime + ${cn1.version} + + + com.codenameone + codenameone-core + ${cn1.version} + + + com.codenameone + codenameone-javase + ${cn1.version} + + + com.codenameone + codenameone-android-compat + ${cn1.version} + provided + + + + com.codenameone + cn1-binaries-javase + ${cn1.version} + pom + runtime + + + com.codenameone + codenameone-buildclient + ${cn1.version} + system + ${user.home}/.codenameone/CodeNameOneBuildClient.jar + + + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + org.codehaus.mojo + exec-maven-plugin + 3.0.0 + + + maven-antrun-plugin + org.apache.maven.plugins + 3.1.0 + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + + + + codenameone + https://repo.codenameone.com/maven2 + + true + + + false + + + + + + codenameone-plugins + https://repo.codenameone.com/maven2 + + true + + + false + + + + + + + + cn1-client-tests + + + codename1.platform + !backend + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + + + + + javascript + + + codename1.platform + javascript + + + ${basedir}/javascript/pom.xml + + + + javascript + + + + ios + + + codename1.platform + ios + + + ${basedir}/ios/pom.xml + + + + ios + + + + win + + + codename1.platform + win + + + ${basedir}/win/pom.xml + + + + win + + + + linux + + + codename1.platform + linux + + + ${basedir}/linux/pom.xml + + + + linux + + + + + backend + + + codename1.platform + backend + + + ${basedir}/backend/pom.xml + + + + backend + + + + android + + + codename1.platform + android + + + ${basedir}/android/pom.xml + + + + android + + + + javase + + + codename1.platform + javase + + + ${basedir}/javase/pom.xml + + + + javase + + + + cn1libs + + + ${basedir}/cn1libs/pom.xml + + + + cn1libs + + + + diff --git a/scripts/ledge/run-e2e.sh b/scripts/ledge/run-e2e.sh new file mode 100755 index 00000000000..6427fc3f3e3 --- /dev/null +++ b/scripts/ledge/run-e2e.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# +# Runs the client's tests against a real server. +# +# Builds the server, starts it with the test profile (an in-memory database and +# simulated store receipts), then runs the simulator tests in common/src/test +# against it: the arena's own tests, which need no server, and the end-to-end +# tests that drive the real screens. The screenshots they take land in +# target/e2e-shots. +# +# run-e2e.sh [--prebuilt] +# +# On Linux it wraps the simulator in xvfb-run when that is installed. To drive +# a running app by hand instead, use its built-in loopback MCP server. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +MVN="${MVN:-mvn}" +PORT="${LEDGE_PORT:-18092}" +LOG="${LEDGE_SERVER_LOG:-$HERE/target/e2e-server.log}" +SHOTS="$HERE/target/e2e-shots" +BUILD=1 +for arg in "$@"; do + case "$arg" in + --prebuilt) BUILD=0 ;; + *) echo "[ledge-e2e] unknown option: $arg" >&2; exit 2 ;; + esac +done + +mkdir -p "$HERE/target" +rm -rf "$SHOTS" +mkdir -p "$SHOTS" + +if [ "$BUILD" = 1 ]; then + "$HERE/backend/server.sh" build +fi + +echo "[ledge-e2e] starting the server on port $PORT" +CN1_PROFILE=test "$HERE/backend/server.sh" run --prebuilt --port "$PORT" >"$LOG" 2>&1 & +SERVER_PID=$! +cleanup() { + kill "$SERVER_PID" >/dev/null 2>&1 || true + wait "$SERVER_PID" 2>/dev/null || true +} +trap cleanup EXIT + +ready=0 +for _ in $(seq 1 90); do + if curl -fs -o /dev/null "http://localhost:$PORT/oauth2/jwks" 2>/dev/null; then + ready=1 + break + fi + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + break + fi + sleep 1 +done +if [ "$ready" != "1" ]; then + echo "[ledge-e2e] the server did not start; its log:" >&2 + cat "$LOG" >&2 || true + exit 1 +fi + +RUNNER=() +if command -v xvfb-run >/dev/null 2>&1; then + RUNNER=(xvfb-run -a -s "-screen 0 1280x1024x24") +fi + +export JAVA_TOOL_OPTIONS="${JAVA_TOOL_OPTIONS:-} -Xmx1536m -Dledge.server.url=http://localhost:$PORT -Dledge.shots.dir=$SHOTS" + +set +e +${RUNNER[@]+"${RUNNER[@]}"} "$MVN" -B -f "$HERE/pom.xml" -Dcodename1.platform=javase -Ptest verify +STATUS=$? +set -e + +# The second pass: the same tests with the simulator as a desktop window and +# not a phone, which is where the admin console is a side bar and a page +# (DesktopTest). Each test knows which pass it is for +# and passes untouched in the other (E2e.desktop()). +# +# The simulator is a desktop when its "desktopSkin" preference says so; there +# is no switch for it on the command line. Java keeps preferences in files only +# on Linux, where java.util.prefs.userRoot can point them at a directory of +# this run's own -- so that is where this pass runs, which covers CI and a +# container. Elsewhere it would mean rewriting the developer's own simulator +# preferences, and it is skipped with a word. +if [ "$STATUS" -eq 0 ] && [ "$(uname -s)" = "Linux" ]; then + PREFS="$HERE/target/e2e-desktop-prefs" + NODE="$PREFS/.java/.userPrefs/com/codename1/impl/javase" + rm -rf "$PREFS" + mkdir -p "$NODE" + cat >"$NODE/prefs.xml" <<'XML' + + + + + +XML + echo "[ledge-e2e] the desktop pass" + export JAVA_TOOL_OPTIONS="$JAVA_TOOL_OPTIONS -Dledge.e2e.desktop=true -Djava.util.prefs.userRoot=$PREFS" + set +e + ${RUNNER[@]+"${RUNNER[@]}"} "$MVN" -B -f "$HERE/pom.xml" -Dcodename1.platform=javase -Ptest verify + STATUS=$? + set -e +elif [ "$STATUS" -eq 0 ]; then + echo "[ledge-e2e] not on Linux: the desktop pass was skipped" +fi + +echo "[ledge-e2e] screenshots: $(find "$SHOTS" -name '*.png' | wc -l | tr -d ' ') in $SHOTS" +exit "$STATUS" diff --git a/scripts/ledge/shared/pom.xml b/scripts/ledge/shared/pom.xml new file mode 100644 index 00000000000..7723ff0462c --- /dev/null +++ b/scripts/ledge/shared/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + com.codenameone.examples.ledge + ledge + 1.0-SNAPSHOT + + com.codenameone.examples.ledge + ledge-shared + 1.0-SNAPSHOT + jar + ledge-shared + + + + 17 + 17 + + + + + com.codenameone + codenameone-core + provided + + + diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AccountApi.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AccountApi.java new file mode 100644 index 00000000000..96d3186448b --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AccountApi.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; + +/// Accounts: registration, the signed-in player, the profile and push devices. Signing in is +/// OAuth (see the app's Session). +@RestClient +public interface AccountApi { + @POST("/api/account/register") + void register(@Body RegisterDto request, OnComplete> callback); + + @GET("/api/me") + void me(OnComplete> callback); + + @POST("/api/me/profile") + void saveProfile(@Body ProfileDto profile, OnComplete> callback); + + @POST("/api/account/push") + void registerPush(@Body PushDeviceDto device, OnComplete> callback); + + @POST("/api/account/push/remove") + void unregisterPush(@Body PushDeviceDto device, OnComplete> callback); +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AchievementDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AchievementDto.java new file mode 100644 index 00000000000..2b39230c5dd --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AchievementDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A goal, and how far the player is toward it. +@Mapped +public record AchievementDto(String id, String name, String description, boolean unlocked, long progress, long goal) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdRewardDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdRewardDto.java new file mode 100644 index 00000000000..ea682aef520 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdRewardDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Claiming the reward for a watched rewarded ad. +@Mapped +public record AdRewardDto(String nonce) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminActionDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminActionDto.java new file mode 100644 index 00000000000..46aceecbffc --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminActionDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// What an admin does to a player: WARN, SUSPEND (for `days`), BAN, UNBAN or RESET_SCORES. +@Mapped +public record AdminActionDto(String action, String reason, int days) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminApi.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminApi.java new file mode 100644 index 00000000000..8abae92197a --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminApi.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.Path; +import com.codename1.annotations.rest.Query; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// The console: everything it reads and does. Every route requires the ADMIN role, and every +/// action is written to the audit log. +@RestClient +public interface AdminApi { + @GET("/api/admin/stats") + void stats(OnComplete> callback); + + @GET("/api/admin/players") + void players(@Query("q") String query, OnComplete>> callback); + + @POST("/api/admin/players/{username}/action") + void act(@Path("username") String username, @Body AdminActionDto action, OnComplete> callback); + + @GET("/api/admin/flags") + void flags(@Query("open") boolean open, OnComplete>> callback); + + @POST("/api/admin/flags/{id}/resolve") + void resolve(@Path("id") String id, @Body ResolveDto verdict, OnComplete> callback); + + @POST("/api/admin/daily") + void setDaily(@Body DailySeedDto seed, OnComplete> callback); + + @POST("/api/admin/broadcast") + void broadcast(@Body BroadcastDto broadcast, OnComplete> callback); + + @GET("/api/admin/heatmap/{level}") + void heatmap(@Path("level") String level, OnComplete> callback); + + @GET("/api/admin/audit") + void audit(OnComplete>> callback); +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminStatsDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminStatsDto.java new file mode 100644 index 00000000000..97063835f57 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AdminStatsDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// The console's front page. +@Mapped +public record AdminStatsDto(int players, int activeToday, int runsToday, int flagsOpen, long topScore, long dailySeed, int purchases) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AuditDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AuditDto.java new file mode 100644 index 00000000000..3a1ecaf6707 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/AuditDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// One entry of the admin audit log. +@Mapped +public record AuditDto(String id, String admin, String username, String action, String reason, long createdAt) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/BroadcastDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/BroadcastDto.java new file mode 100644 index 00000000000..5bba9fb2cbc --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/BroadcastDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A push notification to every player, or to those not seen for `days`. `targets` is how +/// many it reached. +@Mapped +public record BroadcastDto(String id, String title, String body, int days, int targets, long createdAt) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/BuyDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/BuyDto.java new file mode 100644 index 00000000000..5b62b00b174 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/BuyDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Buying a shop item with ink coins. +@Mapped +public record BuyDto(String itemId) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/DailyDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/DailyDto.java new file mode 100644 index 00000000000..3820c5bb89c --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/DailyDto.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Today's challenge. +/// +/// - `date`: the day, `yyyy-mm-dd` +/// - `level`: the level it is played on +/// - `seed`: the seed every player gets +/// - `myBest`: the caller's best today, 0 if none +/// - `topScore`: the best score today +/// - `topName`: who holds it +/// - `players`: how many have played today +@Mapped +public record DailyDto(String date, String level, long seed, long myBest, long topScore, String topName, int players) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/DailySeedDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/DailySeedDto.java new file mode 100644 index 00000000000..ab07cd3ead1 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/DailySeedDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Overrides today's seed, for a sheet an admin has picked. +@Mapped +public record DailySeedDto(long seed) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/EquipDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/EquipDto.java new file mode 100644 index 00000000000..616444d706d --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/EquipDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Puts on an owned scarf. +/// +/// - `scarf`: the item id +@Mapped +public record EquipDto(String scarf) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FlagDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FlagDto.java new file mode 100644 index 00000000000..3dacaf56e43 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FlagDto.java @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A run filed for a moderator. +/// +/// - `id`: the flag +/// - `username`: the account +/// - `displayName`: the name shown +/// - `level`: the level id +/// - `score`: the replayed score +/// - `ticks`: the replayed time +/// - `reason`: why it was filed +/// - `createdAt`: epoch milliseconds +/// - `open`: not yet resolved +@Mapped +public record FlagDto(String id, String username, String displayName, String level, long score, int ticks, String reason, long createdAt, boolean open) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendAddDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendAddDto.java new file mode 100644 index 00000000000..6210da8ae2f --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendAddDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Adds or removes a friend by username or display name. +@Mapped +public record FriendAddDto(String name) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendDto.java new file mode 100644 index 00000000000..6e3e61cc4b4 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendDto.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A friend. +/// +/// - `username`: the account +/// - `displayName`: the name shown +/// - `stars`: stars earned over every level +/// - `scarf`: the scarf worn +@Mapped +public record FriendDto(String username, String displayName, int stars, String scarf) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendsApi.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendsApi.java new file mode 100644 index 00000000000..862c752b16d --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/FriendsApi.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// Friends: the people whose scores the FRIENDS board shows. +@RestClient +public interface FriendsApi { + @GET("/api/friends") + void friends(OnComplete>> callback); + + @POST("/api/friends") + void add(@Body FriendAddDto friend, OnComplete>> callback); + + @POST("/api/friends/remove") + void remove(@Body FriendAddDto friend, OnComplete>> callback); +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GenerateDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GenerateDto.java new file mode 100644 index 00000000000..3a961ddc729 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GenerateDto.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Asks the server for a level. +/// +/// - `prompt`: what the level should be, in words ("a long cave full of +/// spikes"); may be empty +/// - `seed`: varies the answer for the same words +@Mapped +public record GenerateDto(String prompt, long seed) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GeneratedDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GeneratedDto.java new file mode 100644 index 00000000000..f5d97f46421 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GeneratedDto.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A generated level, already proven finishable by the solver. +/// +/// - `sketch`: the level in sketch form, as the editor edits it +/// - `source`: `ai` when a language model drew it, `pieces` when the +/// built-in generator did +/// - `note`: a line for the player, such as why the model's level was not used +@Mapped +public record GeneratedDto(String sketch, String source, String note) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GhostDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GhostDto.java new file mode 100644 index 00000000000..6c57876ad1b --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/GhostDto.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A recorded run to race: the best run on a level, or a friend's. +/// +/// - `level`: the level id +/// - `username`: whose run it is +/// - `displayName`: the name shown above the ghost +/// - `seed`: the seed the run was played with +/// - `log`: its input, in `InputLog` encoding +/// - `ticks`: its time +/// - `score`: its score +@Mapped +public record GhostDto(String level, String username, String displayName, long seed, String log, int ticks, long score) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/HeatmapDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/HeatmapDto.java new file mode 100644 index 00000000000..366dde8dbfd --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/HeatmapDto.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Where players died on a level, from replaying their stored runs. +/// +/// - `level`: the level id +/// - `cols`, `rows`: the level's size in tiles +/// - `cells`: deaths per tile, row by row, comma separated +/// - `runs`: how many runs were replayed +/// - `deaths`: the total +@Mapped +public record HeatmapDto(String level, int cols, int rows, String cells, int runs, int deaths) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/LeaderDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/LeaderDto.java new file mode 100644 index 00000000000..55504e4e49c --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/LeaderDto.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// One row of a level's board. +/// +/// - `rank`: the place, from 1 +/// - `username`: the account +/// - `displayName`: the name shown +/// - `score`: the best score +/// - `ticks`: that run's time +/// - `scarf`: the scarf the player wears, for the row's avatar +/// - `me`: the row is the caller's +@Mapped +public record LeaderDto(int rank, String username, String displayName, long score, int ticks, String scarf, boolean me) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/LevelsApi.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/LevelsApi.java new file mode 100644 index 00000000000..3eb516b10b5 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/LevelsApi.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; + +/// Levels made on request, for the editor. +@RestClient +public interface LevelsApi { + /// Generates a level from a description and proves it can be finished. + @POST("/api/levels/generate") + void generate(@Body GenerateDto request, OnComplete> callback); +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/PlayerDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/PlayerDto.java new file mode 100644 index 00000000000..3c9af5af36d --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/PlayerDto.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// The signed-in player. +/// +/// - `username`: the account +/// - `displayName`: the name shown +/// - `coins`: the wallet +/// - `progress`: stars per level in `LevelPack` order, one digit each +/// - `bestDaily`: the best daily score +/// - `runs`: verified runs +/// - `admin`: may open the console +/// - `suspended`: may not submit runs +/// - `flagged`: has a run waiting for a moderator +/// - `scarf`: the scarf worn +/// - `owned`: shop items owned +@Mapped +public record PlayerDto(String username, String displayName, int coins, String progress, long bestDaily, int runs, boolean admin, boolean suspended, boolean flagged, String scarf, List owned) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ProfileDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ProfileDto.java new file mode 100644 index 00000000000..70230589eae --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ProfileDto.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// The parts of a profile a player may change. +/// +/// - `displayName`: the name shown +/// - `scarf`: the scarf to wear +@Mapped +public record ProfileDto(String displayName, String scarf) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ProgressApi.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ProgressApi.java new file mode 100644 index 00000000000..8daf1ef13db --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ProgressApi.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// Achievements, worked out by the server from the runs it accepted. +@RestClient +public interface ProgressApi { + @GET("/api/achievements") + void achievements(OnComplete>> callback); +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/PushDeviceDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/PushDeviceDto.java new file mode 100644 index 00000000000..b9a8700ee61 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/PushDeviceDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A device the server may send push notifications to. +@Mapped +public record PushDeviceDto(String provider, String token, String platform) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ReceiptDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ReceiptDto.java new file mode 100644 index 00000000000..6b8ee823922 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ReceiptDto.java @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A store purchase for the server to verify before it grants anything. `receipt` is the +/// store's proof: the App Store receipt or the Play purchase token. +@Mapped +public record ReceiptDto(String store, String sku, String transactionId, String receipt) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RegisterDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RegisterDto.java new file mode 100644 index 00000000000..fd38eb3ad2e --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RegisterDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// What a new player sends to open an account. +@Mapped +public record RegisterDto(String email, String password, String displayName) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ResolveDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ResolveDto.java new file mode 100644 index 00000000000..2911f3cfdf1 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ResolveDto.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Closes a flag: KEEP leaves the run on the boards, REMOVE strikes it. +@Mapped +public record ResolveDto(String verdict) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunApi.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunApi.java new file mode 100644 index 00000000000..451905726e7 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunApi.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.Query; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// Runs and the boards: a ticket before a run, the result after it, the leaderboards and the +/// daily challenge. `period` is ALL, WEEK, TODAY or FRIENDS. +@RestClient +public interface RunApi { + @POST("/api/runs/start") + void start(@Body StartRunDto request, OnComplete> callback); + + @POST("/api/runs") + void submit(@Body RunDto run, OnComplete> callback); + + @GET("/api/leaderboard") + void leaderboard(@Query("level") String level, @Query("period") String period, OnComplete>> callback); + + /// The best run on a level, or a friend's best when `username` is given, to + /// race as a ghost. + /// + /// #### Parameters + /// + /// - `level`: the level id + /// - `username`: a friend, or null for the level's best + /// - `callback`: the ghost, or 404 when nobody has finished the level + @GET("/api/ghost") + void ghost(@Query("level") String level, @Query("username") String username, OnComplete> callback); + + @GET("/api/daily") + void daily(OnComplete> callback); +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunDto.java new file mode 100644 index 00000000000..312321c850c --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunDto.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A finished run. The server ignores any score the client might think it +/// earned: it replays `log` against the level with the ticket's seed and scores +/// that. +/// +/// - `token`: the ticket the run was played under +/// - `log`: every tick's input, in `InputLog` encoding +/// - `ticks`: how many ticks the client simulated, checked against the replay +/// - `hash`: the client's final world hash, checked against the replay +@Mapped +public record RunDto(String token, String log, int ticks, long hash) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunResultDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunResultDto.java new file mode 100644 index 00000000000..7cf9fd77b33 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunResultDto.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// What the server made of a run. +/// +/// - `accepted`: false if the replay disagreed with the client or did not finish +/// - `flagged`: the run was filed for a moderator to look at +/// - `newBest`: the score beat the player's best on this level +/// - `score`: the replayed score +/// - `ticks`: the replayed time +/// - `stars`: 0 to 3 +/// - `best`: the player's best on the level after this run +/// - `rank`: the player's place on the level's all-time board, 0 if unranked +/// - `coinsEarned`: coins added to the wallet +/// - `message`: a line for the result screen +@Mapped +public record RunResultDto(boolean accepted, boolean flagged, boolean newBest, long score, int ticks, int stars, long best, int rank, int coinsEarned, String message) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunTicketDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunTicketDto.java new file mode 100644 index 00000000000..38b6344a331 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/RunTicketDto.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// A single-use ticket for one run: the seed it must be played with and the +/// level it is for (for the daily, the server picks the level). +/// +/// - `token`: the ticket +/// - `level`: the level id the run must be played on +/// - `daily`: whether this is the daily challenge +/// - `seed`: the simulation seed +/// - `expiresAt`: when the ticket stops being accepted, epoch milliseconds +@Mapped +public record RunTicketDto(String token, String level, boolean daily, long seed, long expiresAt) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ShopApi.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ShopApi.java new file mode 100644 index 00000000000..b71d3268255 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ShopApi.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.rest.Body; +import com.codename1.annotations.rest.GET; +import com.codename1.annotations.rest.POST; +import com.codename1.annotations.rest.RestClient; +import com.codename1.io.rest.Response; +import com.codename1.util.OnComplete; +import java.util.List; + +/// The wallet, the shop, store purchases (verified on the server) and rewarded ads. +@RestClient +public interface ShopApi { + @GET("/api/shop") + void items(OnComplete>> callback); + + @GET("/api/wallet") + void wallet(OnComplete> callback); + + @POST("/api/shop/buy") + void buy(@Body BuyDto item, OnComplete> callback); + + @POST("/api/shop/equip") + void equip(@Body EquipDto scarf, OnComplete> callback); + + @POST("/api/shop/receipt") + void receipt(@Body ReceiptDto receipt, OnComplete> callback); + + @POST("/api/shop/ad-reward") + void adReward(@Body AdRewardDto reward, OnComplete> callback); +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ShopItemDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ShopItemDto.java new file mode 100644 index 00000000000..d3115dde12c --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/ShopItemDto.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Something the shop sells. +/// +/// - `id`: the item +/// - `name`: the name shown +/// - `kind`: `scarf`, `coins` or `adfree` +/// - `priceCoins`: the price in coins, 0 for a store purchase +/// - `sku`: the store product, for a real-money item +/// - `colour`: a scarf's colour as `#rrggbb` +@Mapped +public record ShopItemDto(String id, String name, String kind, int priceCoins, String sku, String colour) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/StartRunDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/StartRunDto.java new file mode 100644 index 00000000000..d9fc9c2f980 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/StartRunDto.java @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; + +/// Asks for a ticket to play a level. +/// +/// - `level`: a level id such as `1-1`, or `daily` for today's challenge +@Mapped +public record StartRunDto(String level) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/WalletDto.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/WalletDto.java new file mode 100644 index 00000000000..1e18909323f --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/WalletDto.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.api; + +import com.codename1.annotations.Mapped; +import java.util.List; + +/// The wallet. +/// +/// - `coins`: coins to spend +/// - `owned`: item ids owned +/// - `scarf`: the scarf worn +@Mapped +public record WalletDto(int coins, List owned, String scarf) { +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/package-info.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/package-info.java new file mode 100644 index 00000000000..39881d6c6de --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/api/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +/// The REST contract between the app and its server: every route as a `@RestClient` +/// interface and every object it carries as a `@Mapped` record. How a run is scored is +/// not here but in `com.codenameone.examples.ledge.levels.Scoring`, which both sides run. +package com.codenameone.examples.ledge.api; diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Heatmap.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Heatmap.java new file mode 100644 index 00000000000..a988efd3676 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Heatmap.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.levels; + +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.PlatformWorld; +import com.codename1.gaming.platformer.WorldEvent; +import java.util.List; + +/// Where players die. A recorded run is replayed and every tile the hero died +/// on is counted -- the same replay that verifies a score, so the map is of +/// what really happened rather than of what a client reported. +public final class Heatmap { + private Heatmap() { + } + + /// Adds one run's deaths to a count per tile. + /// + /// #### Parameters + /// + /// - `index`: the level index + /// - `seed`: the seed the run was played with + /// - `encodedLog`: its input, in `InputLog` encoding + /// - `counts`: one entry per tile, row by row, `cols * rows` long + /// + /// #### Returns + /// + /// the deaths added, or -1 when the log could not be replayed + public static int add(int index, long seed, String encodedLog, int[] counts) { + if (index < 0 || index >= LevelPack.IDS.length || encodedLog == null + || encodedLog.length() > Scoring.MAX_LOG_CHARS) { + return -1; + } + InputLog log; + try { + log = InputLog.decode(encodedLog, Scoring.MAX_TICKS); + } catch (IllegalArgumentException e) { + return -1; + } + PlatformWorld w = LevelPack.load(index).createWorld(seed); + int cols = w.getGrid().getCols(); + int rows = w.getGrid().getRows(); + int tile = w.getGrid().getTileSize(); + if (counts.length != cols * rows) { + throw new IllegalArgumentException("counts must hold cols * rows entries"); + } + int added = 0; + int[] in = log.toArray(); + for (int i = 0; i < in.length && !w.isComplete() && !w.isGameOver(); i++) { + w.step(in[i]); + List events = w.getEvents(); + for (int k = 0; k < events.size(); k++) { + WorldEvent e = events.get(k); + if (e.getType() == WorldEvent.DEATH && "hero".equals(e.getDetail())) { + int c = Math.max(0, Math.min(cols - 1, e.getX() / tile)); + int r = Math.max(0, Math.min(rows - 1, e.getY() / tile)); + counts[r * cols + c]++; + added++; + } + } + } + return added; + } +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelGenerator.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelGenerator.java new file mode 100644 index 00000000000..7c05eccd73c --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelGenerator.java @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.levels; + +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.LevelData; +import java.util.Random; + +/// Builds a level sketch from hand-made pieces -- a gap, a pit of spikes under +/// a ledge, a ladder up to a gem, a patrolling slime -- chosen by a seed and +/// weighted by the words of a request ("a long cave full of spikes"), then +/// has the [Solver] prove it can be finished. +/// +/// This is what the editor's "Surprise me" makes on the device, and what the +/// server answers with when no language model is configured or the model's +/// level cannot be finished. +public final class LevelGenerator { + /// The rows of every generated level; the floor's top is row 14. + public static final int ROWS = 16; + + private static final String HEADER_ABILITIES = + "\"abilities\": [\"move\", \"ladder\", \"walljump\", \"jump\", \"crouch\", \"dash\"]"; + + /// Pieces, each its columns' bottom rows (the last two are the floor); + /// the rest of the column above is open air. A piece starts and ends on + /// the floor so any two can follow each other. + private static final String[][] PIECES = { + // 0 a run with a coin arc + {"..ooo...", "........", "........", "########", "########"}, + // 1 a short gap + {"...o.o..", "........", "........", "###...##", "###...##"}, + // 2 a hill + {"....o.....", "...###....", "..######..", "##########", "##########"}, + // 3 spikes under a ledge + {"...=====....", "............", "............", "............", + "##^^^^^^^^##", "############"}, + // 4 a slime on patrol + {"..ooo.....", "..........", "....e.....", "##########", "##########"}, + // 5 floating ledges over a wide gap + {".....ooo.......", "....=====......", "...............", "...............", + "##...........##", "##...........##"}, + // 6 a ladder to a coin shelf + {".==ooo===.", ".H........", ".H........", ".H........", "##########", "##########"}, + // 7 slopes + {"....o.....", "...##.....", "../##\\....", "./####\\...", "##########", "##########"}, + // 8 a beetle and a step + {".........", "......###", "..w...###", "#########", "#########"}, + // 9 a bat over a gap + {"....V.....", "..........", "..........", "##......##", "##......##"}, + // 10 a spring up to a high shelf + {".....=====o", "...........", "...........", "...........", "...........", + "..s........", "###########", "###########"}, + // 11 a turret on a tower + {"......T..", ".....###.", ".....###.", "#########", "#########"}, + }; + + private static final int SPIKES = 3; + private static final int[] ENEMIES = {4, 8, 9, 11}; + private static final int LADDER = 6; + private static final int GAP = 1; + private static final int WIDE_GAP = 5; + + private LevelGenerator() { + } + + /// The world a request reads as, by its words: a cave, a foundry, the sky + /// or a forge, and the meadow otherwise. + public static String theme(String request) { + String r = asciiLower(request); + if (r.indexOf("cave") >= 0 || r.indexOf("crystal") >= 0 || r.indexOf("dark") >= 0) { + return "cavern"; + } + if (r.indexOf("factory") >= 0 || r.indexOf("foundry") >= 0 || r.indexOf("machine") >= 0) { + return "foundry"; + } + if (r.indexOf("sky") >= 0 || r.indexOf("cloud") >= 0) { + return "sky"; + } + if (r.indexOf("lava") >= 0 || r.indexOf("fire") >= 0 || r.indexOf("forge") >= 0) { + return "forge"; + } + return "meadow"; + } + + /// Makes a sketch from a request and a seed, without checking it. + /// + /// #### Parameters + /// + /// - `request`: what the player asked for, in words; may be empty + /// - `seed`: picks the pieces + /// + /// #### Returns + /// + /// the sketch + public static String sketch(String request, long seed) { + String r = asciiLower(request); + Random rnd = new Random(seed); + int[] weights = new int[PIECES.length]; + for (int i = 0; i < weights.length; i++) { + weights[i] = 3; + } + if (r.indexOf("spike") >= 0 || r.indexOf("thorn") >= 0) { + weights[SPIKES] = 12; + } + if (r.indexOf("enem") >= 0 || r.indexOf("monster") >= 0 || r.indexOf("slime") >= 0) { + for (int e : ENEMIES) { + weights[e] = 9; + } + } + if (r.indexOf("ladder") >= 0 || r.indexOf("climb") >= 0) { + weights[LADDER] = 12; + } + if (r.indexOf("jump") >= 0 || r.indexOf("gap") >= 0) { + weights[GAP] = 10; + weights[WIDE_GAP] = 8; + } + boolean easy = r.indexOf("easy") >= 0 || r.indexOf("gentle") >= 0 || r.indexOf("first") >= 0; + if (easy) { + weights[SPIKES] = 1; + weights[WIDE_GAP] = 1; + weights[11] = 0; + } + int count = r.indexOf("long") >= 0 ? 14 : r.indexOf("short") >= 0 ? 5 : 9; + StringBuilder[] rows = new StringBuilder[ROWS]; + for (int i = 0; i < ROWS; i++) { + rows[i] = new StringBuilder(); + } + append(rows, new String[] {"......", "..S...", "######", "######"}); + int total = 0; + for (int w : weights) { + total += w; + } + int last = -1; + for (int n = 0; n < count; n++) { + int pick; + do { + int roll = rnd.nextInt(total); + pick = 0; + while (roll >= weights[pick]) { + roll -= weights[pick]; + pick++; + } + } while (pick == last); + last = pick; + if (n == count / 2) { + append(rows, new String[] {"...", ".C.", "###", "###"}); + } + append(rows, PIECES[pick]); + } + append(rows, new String[] {"........", "....X...", "########", "########"}); + String theme = theme(r); + StringBuilder sb = new StringBuilder(); + sb.append("{\"name\": \"").append(name(rnd, theme)).append("\", \"theme\": \"").append(theme) + .append("\", \"par\": ").append(20 + count * 6) + .append(", \"health\": 3, \"tuning\": {\"maxJumps\": 2},\n ").append(HEADER_ABILITIES).append("}\n---\n"); + for (int i = 0; i < ROWS; i++) { + sb.append(rows[i]).append('\n'); + } + return sb.toString(); + } + + /// Makes a level from a request and proves it can be finished, trying + /// further seeds until the solver finds a route. + /// + /// #### Parameters + /// + /// - `request`: what the player asked for, in words + /// - `seed`: the first seed to try + /// - `budgetTicks`: the solver's budget for each try + /// + /// #### Returns + /// + /// the sketch, or null when no try could be finished + public static String solvable(String request, long seed, long budgetTicks) { + for (int attempt = 0; attempt < 6; attempt++) { + String s = sketch(request, seed + attempt * 7919L); + if (check(s, budgetTicks) != null) { + return s; + } + } + return null; + } + + /// Proves a sketch can be finished. + /// + /// #### Parameters + /// + /// - `sketch`: the level + /// - `budgetTicks`: how much simulation the solver may spend + /// + /// #### Returns + /// + /// a finishing run's input, or null when the sketch is not a level or no + /// route was found in the budget + public static InputLog check(String sketch, long budgetTicks) { + LevelData level; + try { + level = LevelData.parse(LevelSketch.compile(sketch)); + } catch (RuntimeException e) { + return null; + } + return new Solver(level, 7, 1).solve(budgetTicks); + } + + /// Folds ASCII letters by hand: `toLowerCase` is locale sensitive, and on + /// a Turkish device "SPIKES" would not contain "spike". + private static String asciiLower(String s) { + if (s == null) { + return ""; + } + StringBuilder sb = new StringBuilder(s.length()); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + sb.append(c >= 'A' && c <= 'Z' ? (char) (c + 32) : c); + } + return sb.toString(); + } + + private static void append(StringBuilder[] rows, String[] piece) { + int width = piece[0].length(); + int top = ROWS - piece.length; + for (int i = 0; i < ROWS; i++) { + if (i < top) { + for (int c = 0; c < width; c++) { + rows[i].append('.'); + } + } else { + rows[i].append(piece[i - top]); + } + } + } + + private static String name(Random rnd, String theme) { + String[] first = {"Windy", "Hidden", "Crooked", "Golden", "Restless", "Quiet", "Tumbling"}; + String[] meadow = {"Hollow", "Meadow", "Ridge", "Path"}; + String[] cavern = {"Grotto", "Depths", "Tunnels", "Hollow"}; + String[] foundry = {"Works", "Gears", "Furnace", "Line"}; + String[] sky = {"Heights", "Drift", "Isles", "Stair"}; + String[] forge = {"Embers", "Crucible", "Cinders", "Anvil"}; + String[] second = "cavern".equals(theme) ? cavern : "foundry".equals(theme) ? foundry + : "sky".equals(theme) ? sky : "forge".equals(theme) ? forge : meadow; + return first[rnd.nextInt(first.length)] + " " + second[rnd.nextInt(second.length)]; + } +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelPack.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelPack.java new file mode 100644 index 00000000000..32d16dcc9be --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelPack.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + */ +package com.codenameone.examples.ledge.levels; + +import com.codename1.gaming.platformer.LevelData; + +/// Every level the game ships, generated by `tools/pack-levels.py` from +/// `levels/*.json`. Do not edit by hand: change a level and run the tool. +/// +/// The app and the server both read levels from here, so a run replayed on the +/// server meets exactly the level the player saw. +public final class LevelPack { + /// Level ids in play order. + public static final String[] IDS = {"1-1", "1-2", "1-3", "1-4", "2-1", "2-2", "2-3", "3-1", "3-2", "3-3", "4-1", "4-2", "5-1"}; + /// Display names, by index. + public static final String[] NAMES = {"First Light", "Ladder Hill", "Drifting Isles", "Thornwood", "Echo Caves", "Locked Deep", "Lever Works", "Foundry Gate", "Smokestack", "Molten Run", "Skyway", "Cloudsteps", "The Forge Heart"}; + /// World themes, by index. + public static final String[] THEMES = {"meadow", "meadow", "meadow", "meadow", "cavern", "cavern", "cavern", "foundry", "foundry", "foundry", "sky", "sky", "forge"}; + /// Par times in seconds, by index. + public static final int[] PAR = {40, 55, 60, 75, 70, 80, 75, 75, 70, 85, 60, 70, 90}; + /// Whether a level is drawn in 2.5D, by index. + public static final boolean[] DEPTH = {false, false, false, false, false, false, false, false, false, false, true, true, false}; + /// Hidden gems in each level, by index. + public static final int[] GEMS = {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0}; + + private LevelPack() { + } + + /// The index of a level id. + /// + /// #### Parameters + /// + /// - `id`: a level id such as `1-1` + /// + /// #### Returns + /// + /// the index, or -1 for an unknown id + public static int indexOf(String id) { + for (int i = 0; i < IDS.length; i++) { + if (IDS[i].equals(id)) { + return i; + } + } + return -1; + } + + /// The level JSON. + /// + /// #### Parameters + /// + /// - `index`: the level index + /// + /// #### Returns + /// + /// the JSON text + public static String json(int index) { + switch (index) { + case 0: + return "{\"name\":\"First Light\",\"theme\":\"meadow\",\"par\":40,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[134,8,1,2],\"spawn\":[5,12],\"tiles\":[\"...............................................................................................................................................\",\"...............................................................................................................................................\",\"...............................................................................................................................................\",\"...............................................................................................................................................\",\"...............................................................................................................................................\",\"...............................................................................................................................................\",\".........................................................======................................................................................\",\"...............................................................................................................................................\",\"...........................................................................=====...............................................................\",\"...............................................................................................................................................\",\"..............................................................................................#####......................................#####.\",\".......................ab####...............................................................######.......................######.......######...\",\"...................ab########b.........................................#######...........#########....................#######.......#######....\",\"...............ab#############b.........#############..........##############c..........##########.....###########....########^^^^^^^########..\",\"###############################.......################.....#####################d.....##############...############....########################\",\"###############################.......################.....########################...##############...############....########################\"],\"entities\":[{\"type\":\"gem\",\"at\":[59,5]},{\"type\":\"coin\",\"at\":[76,7]},{\"type\":\"coin\",\"at\":[77,7]},{\"type\":\"coin\",\"at\":[78,7]},{\"type\":\"coin\",\"at\":[43,8]},{\"type\":\"coin\",\"at\":[44,8]},{\"type\":\"coin\",\"at\":[45,8]},{\"type\":\"coin\",\"at\":[106,8]},{\"type\":\"coin\",\"at\":[108,8]},{\"type\":\"coin\",\"at\":[110,8]},{\"type\":\"coin\",\"at\":[17,9]},{\"type\":\"coin\",\"at\":[18,9]},{\"type\":\"coin\",\"at\":[19,9]},{\"type\":\"coin\",\"at\":[124,10]},{\"type\":\"coin\",\"at\":[125,10]},{\"type\":\"coin\",\"at\":[126,10]},{\"type\":\"coin\",\"at\":[14,12]},{\"type\":\"coin\",\"at\":[15,12]},{\"type\":\"coin\",\"at\":[16,12]},{\"type\":\"coin\",\"at\":[43,12]},{\"type\":\"coin\",\"at\":[45,12]},{\"type\":\"enemy\",\"at\":[51,12],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[104,12],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6}]}"; + case 1: + return "{\"name\":\"Ladder Hill\",\"theme\":\"meadow\",\"par\":55,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[119,3,1,2],\"spawn\":[7,10],\"tiles\":[\"......................................................................................................................................\",\"......................................................................................................................................\",\"..........................................=========.....................................####..........................................\",\".......................................................................................##..##.........................................\",\".....................................H.................H..............................................................................\",\".........................=======.....H.................H................................................=====........#####............\",\".....................................H#################H.........=======............................................######............\",\".....................................H.................H..........................####.............................#######............\",\".....................................H.................H.........................######.............=====.........########............\",\"................=====................H.................H.............############################################.#########...........\",\".....................................H.................H...........................................................##########.........\",\"...............................=========.........=========........................................................###########.........\",\"######################.......##########.............########.....................................................############.........\",\"######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############...........\",\"######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############...........\",\"######################^^^^^^^##########.............########^^^^^^^^#####.......###...........................#############...........\"],\"entities\":[{\"type\":\"coin\",\"at\":[45,1]},{\"type\":\"coin\",\"at\":[46,1]},{\"type\":\"coin\",\"at\":[47,1]},{\"type\":\"gem\",\"at\":[89,1]},{\"type\":\"coin\",\"at\":[27,4]},{\"type\":\"coin\",\"at\":[28,4]},{\"type\":\"coin\",\"at\":[29,4]},{\"type\":\"coin\",\"at\":[105,4]},{\"type\":\"coin\",\"at\":[106,4]},{\"type\":\"coin\",\"at\":[107,4]},{\"type\":\"enemy\",\"at\":[45,5],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"coin\",\"at\":[67,5]},{\"type\":\"coin\",\"at\":[68,5]},{\"type\":\"coin\",\"at\":[69,5]},{\"type\":\"checkpoint\",\"at\":[82,6]},{\"type\":\"coin\",\"at\":[17,8]},{\"type\":\"coin\",\"at\":[18,8]},{\"type\":\"coin\",\"at\":[19,8]},{\"type\":\"enemy\",\"at\":[76,8],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[94,8],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"coin\",\"at\":[43,10]},{\"type\":\"coin\",\"at\":[45,10]},{\"type\":\"coin\",\"at\":[47,10]},{\"type\":\"heart\",\"at\":[110,11]},{\"type\":\"enemy\",\"at\":[44,12],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6}]}"; + case 2: + return "{\"name\":\"Drifting Isles\",\"theme\":\"meadow\",\"par\":60,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"platforms\":[{\"path\":[[19,11],[34,11]],\"w\":3,\"speed\":0.8,\"pause\":30},{\"path\":[[48,12],[48,6]],\"w\":3,\"speed\":0.7,\"pause\":40},{\"path\":[[81,9],[95,9]],\"w\":3,\"speed\":1.0,\"pause\":20},{\"path\":[[108,10],[108,6]],\"w\":3,\"speed\":0.7,\"pause\":30},{\"path\":[[127,10],[131,5]],\"w\":3,\"speed\":0.8,\"pause\":30}],\"goal\":[145,4,1,2],\"spawn\":[7,11],\"tiles\":[\"......................................................................................................................................................\",\"......................................................................................................................................................\",\"......................................................................................................................................................\",\"......................................................................................................................................................\",\"......................................................................................................................................................\",\"........................................................#######.......................................................................................\",\"........................................................#######.........................................................................##############\",\"........................................................#######.........................................................................##############\",\"........................................................#######.....................................######..............................##############\",\"........................................................#######.....................................######..............................##############\",\"........................................................#######.....................................######..............................##############\",\"........................................................#######.........#######.....................######............#######...........##############\",\"################........................######..........#######.........#######.....................######............#######...........##############\",\"################........................######..........#######.........#######.....................######............#######...........##############\",\"################^^^^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^#######^^^^^^^^^#######^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^^^#######^^^^^^^^^^^##############\",\"################^^^^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^#######^^^^^^^^^#######^^^^^^^^^^^^^^^^^^^^^######^^^^^^^^^^^^#######^^^^^^^^^^^##############\"],\"entities\":[{\"type\":\"coin\",\"at\":[125,2]},{\"type\":\"coin\",\"at\":[126,2]},{\"type\":\"coin\",\"at\":[127,2]},{\"type\":\"coin\",\"at\":[128,2]},{\"type\":\"coin\",\"at\":[129,2]},{\"type\":\"coin\",\"at\":[130,2]},{\"type\":\"coin\",\"at\":[57,3]},{\"type\":\"coin\",\"at\":[58,3]},{\"type\":\"coin\",\"at\":[59,3]},{\"type\":\"coin\",\"at\":[60,3]},{\"type\":\"coin\",\"at\":[61,3]},{\"type\":\"gem\",\"at\":[140,3]},{\"type\":\"coin\",\"at\":[88,6]},{\"type\":\"coin\",\"at\":[89,6]},{\"type\":\"coin\",\"at\":[90,6]},{\"type\":\"coin\",\"at\":[91,6]},{\"type\":\"coin\",\"at\":[92,6]},{\"type\":\"coin\",\"at\":[93,6]},{\"type\":\"checkpoint\",\"at\":[102,7]},{\"type\":\"coin\",\"at\":[20,9]},{\"type\":\"coin\",\"at\":[22,9]},{\"type\":\"coin\",\"at\":[24,9]},{\"type\":\"coin\",\"at\":[26,9]},{\"type\":\"coin\",\"at\":[28,9]},{\"type\":\"coin\",\"at\":[30,9]},{\"type\":\"coin\",\"at\":[32,9]},{\"type\":\"coin\",\"at\":[34,9]},{\"type\":\"enemy\",\"at\":[74,10],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[121,10],\"kind\":\"beetle\",\"brain\":\"walker\",\"speed\":0.8}]}"; + case 3: + return "{\"name\":\"Thornwood\",\"theme\":\"meadow\",\"par\":75,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[146,4,1,2],\"spawn\":[7,9],\"tiles\":[\"............................................................................................................................................................\",\"............................................................................................................................................................\",\"............................................................................................................................................................\",\"............................................................................................................................................................\",\"..............................................................................................................................=======.......................\",\"............................................................................................................................................................\",\".....................................................................=====................................................................#########.........\",\".....................................................................................................####................................#########..........\",\".....................................#########.....................................................######....................####.......#########...........\",\".....................................#########..................................##########..........######..........######....####......##########..........\",\".....................................#########.................................##########..........######.........#######....####.....###########...........\",\"...........................##############....##..........########.............##########..........######.........#######....####....############............\",\"##############......##########################..........###########.........##############.........######.........#######....####...#############...........\",\"##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.........\",\"##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.........\",\"##############^^^^^^###########################....######################...################^^^^^^^^######^^^^^^^^^#######^^^^####^^^##############.........\"],\"entities\":[{\"type\":\"enemy\",\"at\":[95,2],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6},{\"type\":\"coin\",\"at\":[129,3]},{\"type\":\"coin\",\"at\":[130,3]},{\"type\":\"coin\",\"at\":[131,3]},{\"type\":\"enemy\",\"at\":[54,4],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6},{\"type\":\"coin\",\"at\":[70,5]},{\"type\":\"coin\",\"at\":[71,5]},{\"type\":\"coin\",\"at\":[72,5]},{\"type\":\"coin\",\"at\":[41,6]},{\"type\":\"coin\",\"at\":[42,6]},{\"type\":\"coin\",\"at\":[43,6]},{\"type\":\"checkpoint\",\"at\":[102,6]},{\"type\":\"spring\",\"at\":[127,7]},{\"type\":\"coin\",\"at\":[22,8]},{\"type\":\"coin\",\"at\":[23,8]},{\"type\":\"coin\",\"at\":[24,8]},{\"type\":\"enemy\",\"at\":[85,8],\"kind\":\"frog\",\"brain\":\"hopper\",\"interval\":80},{\"type\":\"enemy\",\"at\":[118,8],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[33,10],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[60,10],\"kind\":\"beetle\",\"brain\":\"walker\",\"speed\":0.8},{\"type\":\"enemy\",\"at\":[51,12],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"heart\",\"at\":[110,12]}]}"; + case 4: + return "{\"name\":\"Echo Caves\",\"theme\":\"cavern\",\"par\":70,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[140,7,1,2],\"spawn\":[5,11],\"tiles\":[\"######################################################################################################################################################\",\"######################################################################################################################################################\",\"......................................................................................................................................................\",\"......................................................................................................................................................\",\".....................................############...........===========...............................................................................\",\".....................................############.................H.......................................=====.......................................\",\".....................................############.................H...................................................................................\",\"........................................H.........................H.............................###############.......................................\",\"........................................H.........................H.............................###############.......====............................\",\"........................................H.........................H.............................###############............###########################\",\"...........................................................############.........................###############.=====......###########################\",\"...........................................................############.........................###############............###########################\",\"###############........##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############............###########################\",\"###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^###########################\",\"###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^###########################\",\"###############^^^^^^^^##########################.^^^^^^^^^############.^^^^^^^^^^^^^^^^^^^^^^^^###############^^^^^^^^^^^^###########################\"],\"entities\":[{\"type\":\"coin\",\"at\":[74,4]},{\"type\":\"coin\",\"at\":[76,4]},{\"type\":\"coin\",\"at\":[78,4]},{\"type\":\"coin\",\"at\":[80,4]},{\"type\":\"coin\",\"at\":[82,4]},{\"type\":\"coin\",\"at\":[84,4]},{\"type\":\"coin\",\"at\":[86,4]},{\"type\":\"coin\",\"at\":[88,4]},{\"type\":\"coin\",\"at\":[90,4]},{\"type\":\"coin\",\"at\":[92,4]},{\"type\":\"coin\",\"at\":[94,4]},{\"type\":\"gem\",\"at\":[108,4]},{\"type\":\"crumble\",\"at\":[72,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[73,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[74,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[75,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[76,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[77,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[78,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[79,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[80,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[81,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[82,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[83,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[84,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[85,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[86,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[87,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[88,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[89,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[90,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[91,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[92,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[93,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[94,6],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[95,6],\"delay\":24,\"respawn\":240},{\"type\":\"enemy\",\"at\":[103,6],\"kind\":\"brute\",\"brain\":\"chase\",\"speed\":1.1,\"range\":7,\"hp\":2},{\"type\":\"coin\",\"at\":[126,6]},{\"type\":\"coin\",\"at\":[127,6]},{\"type\":\"coin\",\"at\":[128,6]},{\"type\":\"coin\",\"at\":[129,6]},{\"type\":\"coin\",\"at\":[130,6]},{\"type\":\"coin\",\"at\":[131,6]},{\"type\":\"coin\",\"at\":[132,6]},{\"type\":\"coin\",\"at\":[133,6]},{\"type\":\"coin\",\"at\":[134,6]},{\"type\":\"coin\",\"at\":[52,8]},{\"type\":\"coin\",\"at\":[53,8]},{\"type\":\"coin\",\"at\":[54,8]},{\"type\":\"coin\",\"at\":[55,8]},{\"type\":\"coin\",\"at\":[56,8]},{\"type\":\"coin\",\"at\":[57,8]},{\"type\":\"checkpoint\",\"at\":[64,9]},{\"type\":\"coin\",\"at\":[17,10]},{\"type\":\"coin\",\"at\":[18,10]},{\"type\":\"coin\",\"at\":[19,10]},{\"type\":\"coin\",\"at\":[20,10]},{\"type\":\"coin\",\"at\":[21,10]},{\"type\":\"coin\",\"at\":[39,10]},{\"type\":\"coin\",\"at\":[40,10]},{\"type\":\"coin\",\"at\":[41,10]},{\"type\":\"coin\",\"at\":[42,10]},{\"type\":\"coin\",\"at\":[43,10]},{\"type\":\"coin\",\"at\":[44,10]},{\"type\":\"coin\",\"at\":[45,10]},{\"type\":\"coin\",\"at\":[46,10]},{\"type\":\"enemy\",\"at\":[30,11],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[44,11],\"kind\":\"frog\",\"brain\":\"hopper\",\"interval\":80},{\"type\":\"crumble\",\"at\":[50,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[51,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[52,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[53,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[54,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[55,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[56,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[57,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[58,11],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[15,12],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[16,12],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[17,12],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[18,12],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[19,12],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[20,12],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[21,12],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[22,12],\"delay\":24,\"respawn\":240}]}"; + case 5: + return "{\"name\":\"Locked Deep\",\"theme\":\"cavern\",\"par\":80,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[132,8,1,2],\"spawn\":[4,13],\"tiles\":[\"############################################################################################################################################\",\"############################################################################################################################################\",\"......................................................................................#.....................................................\",\".........................................####################.........................#.....................................................\",\".........................................#............................................#.....................................................\",\".........................................#............................................#.....................................................\",\".........................................#............................................#.....................................................\",\".........................................#............................................#.....................................................\",\".........................................#....###############.........................#.....................................................\",\".........................................#....###############.........................#.....................................................\",\".........................................#....###############.....................................=====..........###########################\",\".........................................#....###############....................................................###########################\",\"..............................................###############======###################.##################........###########################\",\"..............................................###############......###################.##################........###########################\",\"#####################.......#################################......###################.##################........###########################\",\"#####################.......#################################......###################.##################........###########################\",\"#####################^^^^^^^#################################^^^^^^###################.##################^^^^^^^^###########################\",\"#####################^^^^^^^#################################^^^^^^###################.##################^^^^^^^^###########################\"],\"entities\":[{\"type\":\"coin\",\"at\":[43,7]},{\"type\":\"coin\",\"at\":[44,7]},{\"type\":\"enemy\",\"at\":[51,7],\"kind\":\"beetle\",\"brain\":\"walker\",\"speed\":0.8},{\"type\":\"key\",\"at\":[55,7],\"name\":\"gold\"},{\"type\":\"gem\",\"at\":[100,9]},{\"type\":\"crumble\",\"at\":[109,9],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[110,9],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[111,9],\"delay\":24,\"respawn\":240},{\"type\":\"heart\",\"at\":[120,9]},{\"type\":\"coin\",\"at\":[72,10]},{\"type\":\"coin\",\"at\":[74,10]},{\"type\":\"coin\",\"at\":[76,10]},{\"type\":\"coin\",\"at\":[78,10]},{\"type\":\"coin\",\"at\":[80,10]},{\"type\":\"crumble\",\"at\":[105,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[106,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[107,10],\"delay\":24,\"respawn\":240},{\"type\":\"coin\",\"at\":[43,11]},{\"type\":\"coin\",\"at\":[44,11]},{\"type\":\"checkpoint\",\"at\":[70,11]},{\"type\":\"door\",\"at\":[86,10],\"key\":\"gold\",\"h\":2},{\"type\":\"enemy\",\"at\":[95,11],\"kind\":\"brute\",\"brain\":\"chase\",\"speed\":1.1,\"range\":7,\"hp\":2},{\"type\":\"coin\",\"at\":[8,12]},{\"type\":\"coin\",\"at\":[10,12]},{\"type\":\"coin\",\"at\":[12,12]},{\"type\":\"coin\",\"at\":[14,12]},{\"type\":\"coin\",\"at\":[16,12]},{\"type\":\"enemy\",\"at\":[34,13],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6}]}"; + case 6: + return "{\"name\":\"Lever Works\",\"theme\":\"cavern\",\"par\":75,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[142,8,1,2],\"spawn\":[4,11],\"tiles\":[\"######################################################################################################################################################\",\"######################################################################################################################################################\",\"...............................#......................................................................................................................\",\"...............................#......................................................................................................................\",\"...............................#......................................................................................................................\",\"...............................#......................................................................................................................\",\"...............................#......................................................................................................................\",\"...............................#........................................#########.....................................................................\",\"...............................#........................................H.................===.........................................................\",\"........................................................................H.............................................................................\",\"........................................................................H...........===.........................................######################\",\"........................................................................H........................########################.......######################\",\"###############################.########################.........################................########################.......######################\",\"###############################.########################.........################^^^^^^^^^^^^^^^^########################.......######################\",\"###############################.########################^^^^^^^^^################^^^^^^^^^^^^^^^^########################^^^^^^^######################\",\"###############################.########################^^^^^^^^^################^^^^^^^^^^^^^^^^########################^^^^^^^######################\"],\"entities\":[{\"type\":\"gem\",\"at\":[76,6]},{\"type\":\"enemy\",\"at\":[91,7],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6},{\"type\":\"coin\",\"at\":[100,8]},{\"type\":\"coin\",\"at\":[103,8]},{\"type\":\"coin\",\"at\":[106,8]},{\"type\":\"coin\",\"at\":[109,8]},{\"type\":\"coin\",\"at\":[112,8]},{\"type\":\"coin\",\"at\":[115,8]},{\"type\":\"coin\",\"at\":[118,8]},{\"type\":\"coin\",\"at\":[8,9]},{\"type\":\"coin\",\"at\":[11,9]},{\"type\":\"coin\",\"at\":[14,9]},{\"type\":\"coin\",\"at\":[17,9]},{\"type\":\"coin\",\"at\":[20,9]},{\"type\":\"coin\",\"at\":[36,9]},{\"type\":\"coin\",\"at\":[40,9]},{\"type\":\"coin\",\"at\":[44,9]},{\"type\":\"coin\",\"at\":[48,9]},{\"type\":\"coin\",\"at\":[52,9]},{\"type\":\"heart\",\"at\":[133,9]},{\"type\":\"crumble\",\"at\":[58,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[59,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[60,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[61,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[62,10],\"delay\":24,\"respawn\":240},{\"type\":\"enemy\",\"at\":[105,10],\"kind\":\"frog\",\"brain\":\"hopper\",\"interval\":80},{\"type\":\"enemy\",\"at\":[112,10],\"kind\":\"beetle\",\"brain\":\"walker\",\"speed\":0.8},{\"type\":\"lever\",\"at\":[24,11],\"channel\":1},{\"type\":\"gate\",\"at\":[31,9],\"channel\":1,\"h\":3},{\"type\":\"enemy\",\"at\":[40,11],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[48,11],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"checkpoint\",\"at\":[70,11]}]}"; + case 7: + return "{\"name\":\"Foundry Gate\",\"theme\":\"foundry\",\"par\":75,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[152,6,1,2],\"spawn\":[5,11],\"tiles\":[\"................................................................................................................................................................\",\"................................................................................................................................................................\",\"................................................................................................................................................................\",\"............................................................................#####...............................................................................\",\"............................................................................#####...............................................................................\",\"............................................................................#####...............................................................................\",\"............................................................................#####..................=====..............=====.....................................\",\"............................................................................#####...............................................................................\",\"............................................................................#####.......................................................########################\",\"...............................####################......................................................#####################..........########################\",\"...............................####################......................................................#####################..........########################\",\"...............................####################..........###############.##############..............#####################..........########################\",\"#####################..........####################..........###############.##############....##........#####################..........########################\",\"#####################....#.....####################..........###############.##############....##........#####################..........########################\",\"#####################^^^^^^^^^^####################^^^^^^^^^^###############.##############^^^^^^^^^^^^^^#####################^^^^^^^^^^########################\",\"#####################^^^^^^^^^^####################^^^^^^^^^^###############.##############^^^^^^^^^^^^^^#####################^^^^^^^^^^########################\"],\"entities\":[{\"type\":\"coin\",\"at\":[99,4]},{\"type\":\"coin\",\"at\":[100,4]},{\"type\":\"coin\",\"at\":[101,4]},{\"type\":\"coin\",\"at\":[102,4]},{\"type\":\"coin\",\"at\":[103,4]},{\"type\":\"coin\",\"at\":[33,7]},{\"type\":\"coin\",\"at\":[36,7]},{\"type\":\"coin\",\"at\":[39,7]},{\"type\":\"coin\",\"at\":[42,7]},{\"type\":\"heart\",\"at\":[140,7]},{\"type\":\"enemy\",\"at\":[46,8],\"kind\":\"turret\",\"brain\":\"turret\",\"interval\":90,\"range\":12},{\"type\":\"enemy\",\"at\":[110,8],\"kind\":\"brute\",\"brain\":\"chase\",\"speed\":1.1,\"range\":7,\"hp\":2},{\"type\":\"gem\",\"at\":[120,8]},{\"type\":\"crumble\",\"at\":[132,9],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[133,9],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[134,9],\"delay\":24,\"respawn\":240},{\"type\":\"coin\",\"at\":[9,10]},{\"type\":\"coin\",\"at\":[12,10]},{\"type\":\"coin\",\"at\":[15,10]},{\"type\":\"coin\",\"at\":[18,10]},{\"type\":\"checkpoint\",\"at\":[64,10]},{\"type\":\"enemy\",\"at\":[70,10],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[88,10],\"kind\":\"turret\",\"brain\":\"turret\",\"interval\":90,\"range\":12},{\"type\":\"crumble\",\"at\":[127,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[128,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[129,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[130,10],\"delay\":24,\"respawn\":240},{\"type\":\"spring\",\"at\":[96,11]},{\"type\":\"spring\",\"at\":[25,12]}]}"; + case 8: + return "{\"name\":\"Smokestack\",\"theme\":\"foundry\",\"par\":70,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\",\"jetpack\"],\"goal\":[112,4,1,2],\"spawn\":[4,17],\"tiles\":[\"........................................................................................................................\",\"........................................................................................................................\",\"........................................................................................................................\",\"........................................................................................................................\",\"..........................................................###...........................................................\",\"..........................................................###...........................................................\",\"..........................................................###................................###########################\",\"..........................................................###................................###########################\",\".........................................############.....###................................###########################\",\".........................................############.....###................................###########################\",\".........................................############.....###................................###########################\",\"....................................====.############.....###...............=====............###########################\",\".........................................############.....###................................###########################\",\".......................########..........############........................................###########################\",\".......................########..........############..............##############............###########################\",\".......................########..====....############..............##############............###########################\",\".......................########..........############..............##############............###########################\",\".......................########..........############..............##############............###########################\",\"#################......########..........############..............##############............###########################\",\"#################......########..........############..............##############............###########################\",\"#################^^^^^^########^^^^^^^^^^############^^^^^^^^^^^^^^##############^^^^^^^^^^^^###########################\",\"#################^^^^^^########^^^^^^^^^^############^^^^^^^^^^^^^^##############^^^^^^^^^^^^###########################\"],\"entities\":[{\"type\":\"enemy\",\"at\":[59,3],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6},{\"type\":\"coin\",\"at\":[96,4]},{\"type\":\"coin\",\"at\":[99,4]},{\"type\":\"coin\",\"at\":[102,4]},{\"type\":\"coin\",\"at\":[105,4]},{\"type\":\"coin\",\"at\":[108,4]},{\"type\":\"coin\",\"at\":[42,5]},{\"type\":\"coin\",\"at\":[45,5]},{\"type\":\"coin\",\"at\":[48,5]},{\"type\":\"coin\",\"at\":[51,5]},{\"type\":\"heart\",\"at\":[100,5]},{\"type\":\"checkpoint\",\"at\":[46,7]},{\"type\":\"crumble\",\"at\":[89,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[90,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[91,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[84,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[85,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[86,10],\"delay\":24,\"respawn\":240},{\"type\":\"enemy\",\"at\":[27,12],\"kind\":\"turret\",\"brain\":\"turret\",\"interval\":90,\"range\":12},{\"type\":\"enemy\",\"at\":[73,13],\"kind\":\"beetle\",\"brain\":\"walker\",\"speed\":0.8},{\"type\":\"gem\",\"at\":[78,13]},{\"type\":\"coin\",\"at\":[6,15]},{\"type\":\"coin\",\"at\":[7,15]},{\"type\":\"coin\",\"at\":[8,15]},{\"type\":\"coin\",\"at\":[9,15]},{\"type\":\"coin\",\"at\":[10,15]},{\"type\":\"powerup\",\"at\":[12,17],\"name\":\"jetpack\"}]}"; + case 9: + return "{\"name\":\"Molten Run\",\"theme\":\"foundry\",\"par\":85,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"goal\":[163,8,1,2],\"spawn\":[5,11],\"tiles\":[\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\".................................................................................................................=====....................................................\",\"...................................................................................................==.....................................................................\",\"..........................................................................................................................................................................\",\"..............................................................................................==......#################...................................................\",\"......................................................................................................#################..................................#################\",\"..................................................#################...................................#################..................................#################\",\"###################........##############.........#################..........##############...........#################..........#################.......#################\",\"###################........##############.........#################..........##############...........#################..........#################.......#################\",\"###################^^^^^^^^##############^^^^^^^^^#################^^^^^^^^^^##############^^^^^^^^^^^#################^^^^^^^^^^#################^^^^^^^#################\",\"###################^^^^^^^^##############^^^^^^^^^#################^^^^^^^^^^##############^^^^^^^^^^^#################^^^^^^^^^^#################^^^^^^^#################\"],\"entities\":[{\"type\":\"gem\",\"at\":[115,5]},{\"type\":\"enemy\",\"at\":[62,7],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6},{\"type\":\"enemy\",\"at\":[107,8],\"kind\":\"turret\",\"brain\":\"turret\",\"interval\":90,\"range\":12},{\"type\":\"enemy\",\"at\":[137,8],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6},{\"type\":\"coin\",\"at\":[78,9]},{\"type\":\"coin\",\"at\":[80,9]},{\"type\":\"coin\",\"at\":[82,9]},{\"type\":\"coin\",\"at\":[84,9]},{\"type\":\"coin\",\"at\":[86,9]},{\"type\":\"coin\",\"at\":[88,9]},{\"type\":\"heart\",\"at\":[157,9]},{\"type\":\"coin\",\"at\":[8,10]},{\"type\":\"coin\",\"at\":[10,10]},{\"type\":\"coin\",\"at\":[12,10]},{\"type\":\"coin\",\"at\":[14,10]},{\"type\":\"coin\",\"at\":[16,10]},{\"type\":\"crumble\",\"at\":[43,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[44,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[45,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[46,10],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[47,10],\"delay\":24,\"respawn\":240},{\"type\":\"checkpoint\",\"at\":[58,10]},{\"type\":\"enemy\",\"at\":[33,11],\"kind\":\"frog\",\"brain\":\"hopper\",\"interval\":80},{\"type\":\"enemy\",\"at\":[80,11],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[86,11],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"checkpoint\",\"at\":[132,11]},{\"type\":\"enemy\",\"at\":[140,11],\"kind\":\"frog\",\"brain\":\"hopper\",\"interval\":80}]}"; + case 10: + return "{\"name\":\"Skyway\",\"theme\":\"sky\",\"depth\":true,\"par\":60,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"platforms\":[{\"path\":[[142,9],[146,6]],\"w\":3,\"speed\":0.8,\"pause\":30}],\"goal\":[162,6,1,2],\"spawn\":[5,11],\"tiles\":[\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................=====..............===......................................####################\",\"...................................................................===...............................................===........#############.........####################\",\".............................===...........................===..............===.....###########.................................#############.........####################\",\".....................===.............===....###########.............................###########.................................#############.........####################\",\"#################...........................###########.............................###########.................................#############.........####################\",\"#################...........................###########.............................###########.................................#############.........####################\",\"#################...........................###########.............................###########.................................#############.........####################\",\"#################...........................###########.............................###########.................................#############.........####################\"],\"entities\":[{\"type\":\"coin\",\"at\":[108,6]},{\"type\":\"coin\",\"at\":[110,6]},{\"type\":\"coin\",\"at\":[112,6]},{\"type\":\"coin\",\"at\":[114,6]},{\"type\":\"coin\",\"at\":[116,6]},{\"type\":\"coin\",\"at\":[118,6]},{\"type\":\"coin\",\"at\":[120,6]},{\"type\":\"coin\",\"at\":[122,6]},{\"type\":\"coin\",\"at\":[124,6]},{\"type\":\"coin\",\"at\":[20,7]},{\"type\":\"coin\",\"at\":[22,7]},{\"type\":\"coin\",\"at\":[24,7]},{\"type\":\"coin\",\"at\":[26,7]},{\"type\":\"coin\",\"at\":[28,7]},{\"type\":\"coin\",\"at\":[30,7]},{\"type\":\"coin\",\"at\":[32,7]},{\"type\":\"coin\",\"at\":[34,7]},{\"type\":\"coin\",\"at\":[36,7]},{\"type\":\"coin\",\"at\":[38,7]},{\"type\":\"coin\",\"at\":[40,7]},{\"type\":\"gem\",\"at\":[92,7]},{\"type\":\"crumble\",\"at\":[98,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[99,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[100,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[101,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[102,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[103,7],\"delay\":24,\"respawn\":240},{\"type\":\"crumble\",\"at\":[104,7],\"delay\":24,\"respawn\":240},{\"type\":\"heart\",\"at\":[155,7]},{\"type\":\"coin\",\"at\":[58,8]},{\"type\":\"coin\",\"at\":[61,8]},{\"type\":\"coin\",\"at\":[64,8]},{\"type\":\"coin\",\"at\":[67,8]},{\"type\":\"coin\",\"at\":[70,8]},{\"type\":\"coin\",\"at\":[73,8]},{\"type\":\"coin\",\"at\":[76,8]},{\"type\":\"coin\",\"at\":[79,8]},{\"type\":\"enemy\",\"at\":[134,8],\"kind\":\"bat\",\"brain\":\"flyer\",\"speed\":0.9,\"range\":6},{\"type\":\"checkpoint\",\"at\":[88,9]},{\"type\":\"enemy\",\"at\":[50,10],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"powerup\",\"at\":[12,11],\"name\":\"glide\"}]}"; + case 11: + return "{\"name\":\"Cloudsteps\",\"theme\":\"sky\",\"depth\":true,\"par\":70,\"health\":3,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\"],\"platforms\":[{\"path\":[[17,11],[29,11]],\"w\":3,\"speed\":0.9,\"pause\":25},{\"path\":[[47,10],[60,7]],\"w\":3,\"speed\":0.9,\"pause\":25},{\"path\":[[79,9],[93,9]],\"w\":3,\"speed\":1.0,\"pause\":20},{\"path\":[[111,9],[124,6]],\"w\":3,\"speed\":0.9,\"pause\":25},{\"path\":[[141,9],[150,7]],\"w\":3,\"speed\":0.9,\"pause\":25}],\"goal\":[164,5,1,2],\"spawn\":[5,11],\"tiles\":[\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"..........................................................................................................................................................................\",\"............................................................................................................................................................##############\",\"....................................................................#########...............................................................................##############\",\"....................................................................#########.....................................................#########.................##############\",\"..................................###########.......................#########.......................#########.....................#########.................##############\",\"..................................###########.......................#########.......................#########.....................#########.................##############\",\"###############...................###########.......................#########.......................#########.....................#########.................##############\",\"###############...................###########.......................#########.......................#########.....................#########.................##############\",\"###############...................###########.......................#########.......................#########.....................#########.................##############\",\"###############...................###########.......................#########.......................#########.....................#########.................##############\"],\"entities\":[{\"type\":\"gem\",\"at\":[104,4]},{\"type\":\"checkpoint\",\"at\":[72,7]},{\"type\":\"heart\",\"at\":[134,8]},{\"type\":\"enemy\",\"at\":[39,9],\"kind\":\"slime\",\"brain\":\"patrol\",\"speed\":0.6},{\"type\":\"enemy\",\"at\":[104,9],\"kind\":\"frog\",\"brain\":\"hopper\",\"interval\":80},{\"type\":\"coin\",\"at\":[8,10]},{\"type\":\"coin\",\"at\":[9,10]},{\"type\":\"coin\",\"at\":[10,10]},{\"type\":\"coin\",\"at\":[11,10]},{\"type\":\"coin\",\"at\":[12,10]},{\"type\":\"coin\",\"at\":[13,10]}]}"; + case 12: + return "{\"name\":\"The Forge Heart\",\"theme\":\"forge\",\"par\":90,\"health\":5,\"boss\":true,\"tuning\":{\"maxJumps\":2},\"abilities\":[\"move\",\"ladder\",\"walljump\",\"jump\",\"crouch\",\"dash\",\"weapon\"],\"spawn\":[5,12],\"goal\":[64,11,1,2],\"tiles\":[\"######################################################################\",\"######################################################################\",\"##............................................................#.....##\",\"##............................................................#.....##\",\"##............................................................#.....##\",\"##............................................................#.....##\",\"##............................................................#.....##\",\"##............................................................#.....##\",\"##..........................========..........................#.....##\",\"##........======....................................======....#.....##\",\"##..................................................................##\",\"##..................................................................##\",\"##..................................................................##\",\"######################################################################\",\"######################################################################\",\"######################################################################\"],\"entities\":[{\"type\":\"coin\",\"at\":[30,5]},{\"type\":\"coin\",\"at\":[31,5]},{\"type\":\"coin\",\"at\":[32,5]},{\"type\":\"coin\",\"at\":[33,5]},{\"type\":\"coin\",\"at\":[34,5]},{\"type\":\"coin\",\"at\":[35,5]},{\"type\":\"heart\",\"at\":[12,8]},{\"type\":\"heart\",\"at\":[56,8]},{\"type\":\"enemy\",\"at\":[40,12],\"kind\":\"golem\",\"brain\":\"boss\",\"hp\":8,\"opens\":1,\"w\":2,\"h\":2,\"speed\":1.0,\"range\":14},{\"type\":\"gate\",\"at\":[62,10],\"channel\":1,\"h\":3}]}"; + default: + throw new IllegalArgumentException("No level " + index); + } + } + + /// A recorded input that finishes the level, in `InputLog` encoding. + /// + /// #### Parameters + /// + /// - `index`: the level index + /// + /// #### Returns + /// + /// the encoded log, or an empty string if the level has none + public static String demo(int index) { + switch (index) { + case 0: + return "8*19,4*d,10*19,0*1,18*7,8*1,0*13,2*1b,6*17,2*10,11*c,41*15,62*9,100*19,4*a,62*10,81*c,6*c,32*10,6*c,62*1c,0*10,32*10,22*1,12*14,2*1,22*f,32*3,22*1,11*8,32*14,0*14,32*9,22*1,81*8,41*4,100*d,12*15,2*1,90*4,82*c,62*22,18*c,22*a,100*8,32*a,22*1,0*4,21*6,12*14,2*9,100*8,21*d,22*d,62*14,18*9,8*1,100*4,2*5,31*6,21*1,6*4,82*8,8*4,62*8,100*1b,62*c,81*9,32*f,22*1,100*a,8*d,62*4,32*4,62*18,31*7,21*1,11*8,8*12,2*14,90*c,4*9,31*8,0*1c,12*b,2*1,10*a,0*1,18*14,8*1,10*5,0*1,32*c,11*4,0*17,12*14,10*6,0*1,12*16,2*1,62*14,22*1c,100*12,62*1b,18*7,8*1,18*4,32*17,22*1,10*d,0*1,21*5,90*17,80*1,32*e,22*1,90*c,62*1b,0*4,90*c,4*13,10*4,0*1,18*10,8*1,22*13,11*3,1*1,82*10,11*15,1*1,62*4,22*1a,4*4,31*4,22*10,100*4,22*4,12*c,2*1,11*f,1*1,62*1b,8*4,82*10,11*10,4*10,10*2,0*1,2*10,6*9,2*4,62*10,32*19,22*1,4*10,82*11,4*16,8*d,11*8,62*19,0*4,12*8,90*2,80*1,0*9,22*4,32*6,22*1,62*12"; + case 1: + return "8*19,4*d,10*19,0*1,18*7,8*1,0*13,2*1b,6*17,2*10,11*c,41*15,62*9,100*19,4*a,62*10,81*c,6*c,32*8,10*1b,0*1,6*16,18*c,8*1,11*4,81*14,2*5,6*20,2*4,31*a,21*1,100*4,62*9,18*c,2*9,11*12,1*1,62*9,11*f,1*1,12*3,2*1,11*15,1*1,4*1c,0*c,32*7,22*1,6*f,32*d,22*1,31*2,21*15,100*13,2*10,62*4,82*10,81*16,62*f,4*8,11*8,100*12,22*10,18*8,21*d,0*a,90*13,80*1,32*18,22*1,12*14,0*13,32*11,22*5,32*11,22*1,4*c,62*8,21*4,10*10,62*18,6*5,32*1a,22*1,90*17,80*1,2*8,32*e,22*1,21*13,12*1b,2*1,4*7,81*11,90*e,80*1,6*8,18*4,62*4,18*8,62*8,90*5,80*1,2*5,18*18,8*1,81*14,2*11,31*c,22*b,62*6,41*8,31*c,0*e,6*b,10*7,0*1,31*2,21*1,62*c,100*18,31*10,21*1,2*35,10*1a,0*1,82*3,22*10,4*4,11*5,1*1,4*4,6*1b,31*c,21*1,4*9,31*8,6*1a,0*1b,100*a,22*12,21*4,8*19,11*3,1*1,12*8,11*c,1*1,32*a,22*1,62*26,31*c,32*8,82*14,18*c,21*8,10*18,0*1,90*14,80*1,32*a,22*1,62*c,90*8,18*2,8*1,82*14,62*2"; + case 2: + return "18*5,8*1,18*4,100*10,62*1c,2*c,32*a,22*1,32*1c,62*8,8*5,22*c,0*1a,12*10,6*b,90*8,62*4,10*16,0*1,4*19,10*14,0*1,62*4,0*b,81*7,12*1b,2*1,6*12,32*b,22*1,32*14,12*e,2*1,8*6,82*14,8*1a,2*14,62*c,31*8,12*e,2*1,90*4,31*f,21*1,82*c,100*12,12*13,2*1,62*5,21*c,6*8,82*18,2*9,0*12,82*c,90*1a,80*1,8*6,62*18,31*8,62*a,2*4,32*8,22*1,32*6,22*1,18*c,62*f,100*8,2*5,100*15,62*4,82*8,90*8,80*1,62*c,10*4,12*13,2*1,62*4,32*c,22*f,32*19,22*1,81*3,2*4,62*14,32*19,22*1,81*4,82*c,12*c,90*4,32*10,62*8,6*5,8*1a,62*c,11*4,6*10,8*c,62*8,4*f,2*11,12*18,2*1,62*14,32*b,22*1,2*f,21*11,6*17,62*c,31*8,21*c,62*c,12*8,31*d,21*1,10*4,0*1,32*18,22*1,11*4,82*c,2*8,62*4,6*14,90*18,32*b,22*1,21*4,32*15,22*1,81*c,12*13,2*1,8*10,2*1c,12*6"; + case 3: + return "8*19,4*d,10*19,0*1,18*7,8*1,0*13,2*1b,6*17,2*10,11*c,6*c,32*18,4*4,32*8,2*17,90*1a,80*1,32*19,22*1,6*f,32*c,0*14,32*9,22*1,81*4,100*13,2*10,62*4,82*10,81*16,62*f,4*4,11*11,1*1,12*c,100*12,22*10,18*12,8*1,10*c,21*d,0*a,90*13,80*1,32*18,22*1,12*10,0*10,12*9,2*1,12*3,2*1,90*a,80*1,32*11,22*13,11*4,12*12,2*1,18*4,22*1b,18*c,22*18,11*7,1*1,31*4,82*1b,81*b,4*17,22*16,2*17,100*c,62*3,12*4,22*13,12*c,90*a,80*1,82*d,12*16,2*1,32*c,12*b,2*1,4*9,12*10,2*8,4*4,22*4,21*7,82*33,62*c,0*4,21*8,32*8,22*1,100*8,12*10,2*1,18*8,62*18,31*c,82*a,0*8,62*12,18*10,8*1,22*12,100*8,32*a,22*1,0*4,4*17,18*7,8*1,31*8,18*7,8*1,62*b,8*4,2*16,6*f,12*c,62*8,21*c,100*4,12*11,2*1,12*4,62*18,8*12,2*14,90*4,82*e,81*4,100*d,32*a,22*1,12*1b,2*1,11*8,12*4,10*6,0*1,12*16,2*1,62*14,22*17"; + case 4: + return "8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*17,2*8,11*c,6*c,32*22,22*1,12*8,2*1,0*4,11*8,82*13,6*e,62*9,18*8,11*4,32*19,22*1,6*f,32*d,22*1,31*2,21*5,82*10,81*16,62*f,4*4,11*11,1*1,12*1a,2*1,12*8,2*1,32*8,22*1,11*4,100*12,22*10,18*12,8*1,10*4,21*d,0*a,90*13,80*1,32*18,22*1,12*10,0*13,32*11,22*b,6*c,18*c,31*1a,21*1,6*11,32*2,22*1,31*7,21*1,62*17,12*14,2*14,10*18,0*1,82*4,81*6,10*3,0*1,32*14,31*a,21*1,82*10,12*15,2*1,10*15,0*1,6*19,10*4,0*4,82*c,6*17,11*5,1*1,11*d,1*1,22*1b,18*4,81*14,62*c,41*c,62*1c,31*8,32*a,22*1,10*8,32*15,22*1,10*4,22*1a,32*14,22*1,8*3,100*4,12*1b,2*1,4*27,6*1b,82*2f,0*4,81*8,62*1c,21*c,12*12,2*1,11*4,1*1,32*16,22*1,32*8,22*1,10*14,0*1,90*4,6*12,31*4,8*6,32*5,22*1,2*c,90*10,4*a,0*18,62*4,81*8,6*c,62*a,22*1b,62*c"; + case 5: + return "8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*17,2*8,11*c,6*c,32*18,22*1,81*4,2*4,31*8,82*10,81*16,62*c,12*10,2*c,12*4,90*8,6*8,2*1a,12*9,2*1,21*4,82*12,2*4,4*b,11*8,8*11,2*18,32*3,22*1,81*8,12*12,2*1,18*4,6*18,2*14,0*3,2*c,6*12,100*e,0*4,22*a,12*c,90*4,80*1,10*4,8*b,11*15,1*1,11*f,1*1,12*1b,2*1,31*13,21*1,62*14,10*4,100*14,32*d,22*1,0*10,32*f,22*1,18*3,8*1,22*11,82*8,8*3,6*c,0*c,18*19,8*1,100*19,62*7,10*4,22*24,32*8,4*8,31*4,2*17,90*5,80*1,82*10,21*5,22*15,12*13,2*1,12*13,2*1,11*c,32*15,22*1,32*18,22*1,18*4,62*8,81*6,22*14,18*13,8*1,12*15,2*1,90*a,80*1,4*4,32*e,22*1,10*f,0*1,22*12,6*4,62*8,100*12,0*9,82*18,12*c,6*15,82*14,10*4,22*18,18*8,2*d,62*2e,18*4,100*11,2*a,22*e,21*4,18*15,8*1,22*13,90*8,80*1,22*c,62*18,22*8"; + case 6: + return "8*19,4*d,10*c,0*13,2*1b,6*17,2*c,11*c,6*c,32*10,62*c,22*12,8*2b,32*18,22*1,62*c,100*1a,90*a,80*1,18*4,21*16,100*c,22*19,18*15,8*1,62*22,10*4,41*1c,82*5,100*1c,62*8,6*17,10*c,21*c,62*f,11*4,62*c,31*5,21*1,10*10,82*1b,8*1b,6*3,62*1f,32*8,18*a,8*1,90*c,21*c,11*2,1*1,31*18,21*1,62*d,6*14,2*c,6*3,22*14,6*4,32*e,22*1,31*1b,21*1,82*17,11*8,1*1,82*10,62*6,31*c,22*4,12*3,2*1,62*e,4*4,22*14,4*4,90*a,80*1,81*10,6*18,11*d,1*1,82*3,62*5,82*8,41*b,32*d,22*1,0*c,22*14,32*3,22*1,4*4,18*21,8*1,31*14,21*1,90*4,21*15,22*1f,62*19,90*20,80*1,32*a,22*1,62*f,81*8,32*19,22*1,82*8,90*13,80*1,18*2,8*1,82*14,32*1b,22*1,11*4,12*12,2*1,100*c,62*e,32*7,22*1,0*e,6*10,100*18,82*10,2*c,22*c,12*8,6*5,8*1a,2*13,22*3,100*4,11*8,4*9,8*1c,4*c,12*10,11*e,1*1,12*5,2*15,12*5,2*1,6*8,12*9,2*1,82*13,22*1b,82*7,31*4,12*a,2*1,10*6,0*1,62*1c,11*15,1*1,2*c,12*11,2*1,62*d,4*c,10*13,0*1,90*18,80*1,82*c,12*13,2*1,8*8,32*17,22*1,18*5,8*2"; + case 7: + return "8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*17,2*8,11*c,6*c,32*18,4*8,6*1c,11*8,31*8,21*d,0*a,90*13,80*1,32*18,22*c,10*8,0*1,81*21,32*e,22*1,32*10,18*18,22*17,90*8,12*b,2*1,22*8,21*4,82*17,31*8,82*11,32*4,82*9,31*c,21*1,62*9,21*c,32*8,22*1,100*4,12*10,2*1,18*10,90*c,6*1b,32*18,22*1,10*1a,0*1,10*4,62*18,41*8,10*5,0*1,4*4,62*12,18*8,22*a,100*8,32*a,22*1,0*4,21*6,12*10,2*9,100*8,21*d,22*d,62*2c,18*9,8*1,100*4,2*5,31*6,21*1,6*4,82*8,18*7,8*1,62*b,8*9,82*c,8*f,62*13,8*b,11*c,62*d,90*4,80*1,81*4,2*1a,81*c,62*c,18*c,8*1,32*c,22*1,18*7,8*1,10*4,8*2b,62*c,22*6,41*4,12*3,2*1,8*b,100*c,62*c,22*14,4*4,90*8,10*f,0*1,22*14,21*3,2*8,32*3,22*1,90*6,80*1,18*c,22*c,31*8,32*9,22*1,32*8,8*5,90*c,12*9,2*1,32*f,22*1,100*9,81*8,4*6,21*e,18*10,62*18,21*4,82*c,10*8,2*d,82*4,21*a,2*a,100*4,22*d,2*19,21*3,12*14,2*1,4*13,62*c,82*9,41*4,6*8,0*b,12*12,2*1,82*7"; + case 8: + return "8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,0*13,2*1b,6*4,10*4,82*1a,21*16,62*15,12*11,2*1,31*c,41*8,90*13,80*1,18*2,8*1,82*14,32*14,62*4,82*7,10*4,12*1b,2*1,90*4,62*14,6*5,21*4,10*a,0*1,10*8,18*d,8*1,62*8,2*11,22*c,12*10,2*1,0*a,11*8,18*3,8*1,62*14,11*8,12*c,2*1,12*8,2*1,82*10,62*a,31*14,21*7,6*19,100*8,22*c,32*f,22*1,18*4,10*9,0*1,2*4,62*c,6*8,22*10,18*4,2*c,62*29,12*18,2*1,12*3,2*1,12*13,2*18,62*8,2*4,90*8,22*1a,10*c,32*8,22*8,18*5,8*1,4*4,62*6,2*18,18*17,8*1,2*15,100*4,12*c,2*1,100*10,62*12,32*17,22*1,18*14,8*1,62*8,6*8,10*13,0*1,12*d,2*1,81*18,32*18,22*1,6*10,22*4"; + case 9: + return "8*19,4*d,10*c,0*13,2*1b,6*17,2*c,11*c,6*c,32*18,22*1,81*4,4*9,11*8,62*1c,0*10,32*10,22*1,12*14,2*1,22*f,32*3,22*1,11*8,32*19,22*1,6*f,32*d,22*1,31*2,21*d,11*11,1*1,12*1a,2*1,12*8,2*1,32*8,22*1,11*c,0*13,32*11,22*9,100*c,32*2,22*1,31*7,21*1,62*17,12*14,31*a,21*1,82*10,21*4,12*8,90*14,22*14,10*8,0*1,81*15,11*8,32*e,22*1,32*10,22*1,12*b,2*1,82*4,21*1a,81*14,62*14,22*8,62*10,10*8,32*19,22*1,4*8,6*8,12*c,100*4,12*11,2*1,12*c,2*4,31*b,21*1,18*c,8*1,22*8,62*c,100*1b,62*14,18*c,41*4,81*c,10*10,4*19,32*a,22*1,6*4,22*8,90*4,12*10,81*11,62*4,18*6,8*1,90*8,62*4,2*8,62*1b,32*17,22*1,62*e,8*8,21*8,82*c,2*4,31*4,21*1,22*4,62*18,81*4,18*c,82*8,62*14,18*b,8*1,62*8,82*4,62*8,82*10,90*c,100*12,12*13,2*1,62*5,21*8,22*8,6*8,82*1b,10*c,2*4,12*c,2*1,22*11,2*c,31*8,6*1c,0*5,11*c,21*7,41*10,8*1b,82*b,32*10,12*7,2*1,32*11,22*d,62*17,8*1a,32*d,22*1,90*19,80*1,2*1b,11*4,22*c,10*6,0*1,4*c"; + case 10: + return "8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*4,82*9,62*8,22*3,32*1b,22*1,81*4,12*c,2*1,11*f,1*1,62*c,11*7,1*1,2*14,12*5,2*1,31*c,22*8,62*12,12*9,2*1,31*6,21*1,11*4,4*6,21*c,32*15,22*1,8*21,22*c,11*10,1*1,4*13,62*f,10*4,22*5,18*16,8*1,82*1b,4*4,62*a,32*9,22*1,81*4,90*17,80*1,82*17,22*c,31*c,32*9,22*1,12*c,2*1,4*b,22*16,81*4,32*1b,22*1,2*8,11*4,4*8,11*c,6*19,12*c,2*1,32*c,62*1c,2*d,32*12,22*1,2*6,22*4,62*6,6*4,100*b,6*16,100*4,12*3,2*1,18*8,0*11,8*22,12*6,2*5,82*c,10*8,32*18,22*1,8*3,4*4,31*c,32*6,22*1,62*c,8*11,12*14,81*f,32*1b,22*1,31*14,21*1,2*10,11*4,22*10,12*3,2*1,32*7,22*1,32*3,22*1,62*9,11*4,90*12,80*1,22*a,2*18,81*4,18*8,8*1,4*11,2*4,90*b,80*1,32*11,22*1,62*4,11*8,2*f,62*11,32*18,8*10,12*8,62*b,2*4,82*3,32*1a,22*1,32*17,22*1,18*4,10*4,12*14,6*9,31*8,8*f,81*4,31*14,21*1,81*8,90*16,80*1,62*f,31*d,21*1,22*8,32*14,10*14,62*10,31*9,21*1,2*4,62*6,81*3,100*d,10*3,0*1,18*2,8*1,62*c,8*5,90*4,8*1a,62*7,12*f,2*1,21*4,0*13,62*5"; + case 11: + return "10*c,6*4,2*8,62*e,0*4,6*9,62*10,11*8,6*14,62*11,12*1a,2*1,90*16,80*1,21*8,62*c,22*a,4*14,8*e,12*3,2*1,90*8,62*13,22*3,100*4,18*4,2*1c,82*18,62*a,90*15,80*1,22*8,18*d,8*1,62*1a,12*3,2*1,81*4,82*7,32*12,22*1,12*c,62*6,8*4,62*e,32*4,6*d,82*c,62*5,22*f,82*c,62*c,12*1a,2*1,32*6,22*1,62*8,22*8,32*4,22*c,62*17,10*4,2*20,32*9,22*1,81*4,32*f,22*11,100*12,32*1b,22*1,62*6,82*8,32*13,22*1,41*13,22*16,4*14,12*12,2*1,8*10,18*4,32*f,22*1,10*8,62*e,21*8,41*17,12*17,2*1,100*2e,18*c,82*1c,62*c,12*c,82*10,32*b,22*1,62*16,4*7,82*9,12*1a,2*1,32*1a,22*1,4*8,6*4,82*12,10*4,4*a,62*6,22*d,82*3,10*4,6*5"; + case 12: + return "8*19,4*d,10*8,6*c,8*14,82*18,18*6,8*1,90*c,10*1b,0*1,6*16,18*c,8*1,11*10,62*18,18*4,2*14,90*f,80*1,11*c,2*17,62*6,90*b,80*1,82*12,32*14,22*1,21*8,4*17,2*17,81*19,11*21,1*1,31*18,18*d,8*1,22*8,41*4,32*f,22*1,32*c,8*c,32*16,22*16,2*c,32*12,22*1,8*8,22*12,8*4,82*9,62*17,18*3,8*1,41*10,8*10,32*6,22*1,11*13,1*1,32*11,22*1,2*c,6*1b,90*4,0*3,22*2d,81*4,62*1b,90*11,80*1,90*4,2*6,0*5,18*c,8*1,62*4,4*8,21*e,100*1b,6*14,2*c,82*10,18*4,10*1a,0*1,62*e"; + default: + throw new IllegalArgumentException("No level " + index); + } + } + + /// Parses a level. + /// + /// #### Parameters + /// + /// - `index`: the level index + /// + /// #### Returns + /// + /// the level, freshly parsed so the caller may change it + public static LevelData load(int index) { + return LevelData.parse(json(index)); + } +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelSketch.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelSketch.java new file mode 100644 index 00000000000..b6cef715fad --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/LevelSketch.java @@ -0,0 +1,288 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.levels; + +import com.codename1.gaming.platformer.LevelJson; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/// Turns a level sketch into level JSON: the same conversion as +/// `tools/sketch.py`, in Java, so the on-device editor and the server's level +/// generator speak the format the shipped levels are written in. +/// +/// A sketch is a JSON header (name, theme, abilities, tuning, platforms...), +/// a line holding only `---`, then the level's tile rows with its things +/// drawn in. Tile characters are the engine's own (`Tile`); these letters +/// place things and leave an empty cell behind: +/// +/// ``` +/// S spawn X goal C checkpoint o coin * gem h heart +/// 1 life k key D door (2 tall, needs a key) s spring +/// % crumble L lever P plate | gate (channel 1, 3 tall) +/// e slime w beetle B brute T turret F frog V bat +/// Z boss J jetpack G glide +/// ``` +public final class LevelSketch { + /// Every letter that places a thing, for an editor's palette. + public static final String THINGS = "SXCo*h1kDs%LP|ewBTFVZJG"; + + private LevelSketch() { + } + + /// Converts a sketch. + /// + /// #### Parameters + /// + /// - `sketch`: the sketch text + /// + /// #### Returns + /// + /// the level JSON + /// + /// #### Throws + /// + /// - `IllegalArgumentException`: when the sketch has no `---` line, its + /// header is not a JSON object, or it has no rows + @SuppressWarnings("unchecked") + public static String compile(String sketch) { + String text = sketch.replace("\r\n", "\n"); + int cut = text.indexOf("\n---\n"); + if (cut < 0) { + throw new IllegalArgumentException("a sketch needs a line holding only ---"); + } + Object parsed = LevelJson.parse(text.substring(0, cut)); + if (!(parsed instanceof Map)) { + throw new IllegalArgumentException("the sketch header must be a JSON object"); + } + Map level = new LinkedHashMap((Map) parsed); + List rows = new ArrayList(); + String body = text.substring(cut + 5); + int start = 0; + while (start <= body.length()) { + int nl = body.indexOf('\n', start); + String line = nl < 0 ? body.substring(start) : body.substring(start, nl); + rows.add(line); + if (nl < 0) { + break; + } + start = nl + 1; + } + while (!rows.isEmpty() && rows.get(rows.size() - 1).trim().length() == 0) { + rows.remove(rows.size() - 1); + } + if (rows.isEmpty()) { + throw new IllegalArgumentException("the sketch has no rows"); + } + int width = 0; + for (int i = 0; i < rows.size(); i++) { + width = Math.max(width, rows.get(i).length()); + } + List entities = new ArrayList(); + Object given = level.remove("entities"); + if (given instanceof List) { + entities.addAll((List) given); + } + List tiles = new ArrayList(); + for (int r = 0; r < rows.size(); r++) { + String line = rows.get(r); + StringBuilder out = new StringBuilder(width); + for (int c = 0; c < width; c++) { + char ch = c < line.length() ? line.charAt(c) : '.'; + if (place(ch, c, r, level, entities)) { + out.append('.'); + } else { + out.append(ch); + } + } + tiles.add(out.toString()); + } + level.put("tiles", tiles); + level.put("entities", entities); + StringBuilder sb = new StringBuilder(); + write(sb, level); + return sb.toString(); + } + + private static boolean place(char ch, int c, int r, Map level, List ents) { + switch (ch) { + case 'S': + level.put("spawn", ints(c, r)); + return true; + case 'X': + level.put("goal", ints(c, r - 1, 1, 2)); + return true; + case 'o': + return add(ents, thing("coin", c, r)); + case '*': + return add(ents, thing("gem", c, r)); + case 'h': + return add(ents, thing("heart", c, r)); + case '1': + return add(ents, thing("life", c, r)); + case 's': + return add(ents, thing("spring", c, r)); + case 'C': + return add(ents, thing("checkpoint", c, r)); + case 'k': + return add(ents, with(thing("key", c, r), "name", "gold")); + case 'D': + return add(ents, with(with(thing("door", c, r - 1), "key", "gold"), "h", 2)); + case '%': + return add(ents, with(with(thing("crumble", c, r), "delay", 24), "respawn", 240)); + case 'L': + return add(ents, with(thing("lever", c, r), "channel", 1)); + case 'P': + return add(ents, with(thing("plate", c, r), "channel", 1)); + case '|': + return add(ents, with(with(thing("gate", c, r - 2), "channel", 1), "h", 3)); + case 'J': + return add(ents, with(thing("powerup", c, r), "name", "jetpack")); + case 'G': + return add(ents, with(thing("powerup", c, r), "name", "glide")); + case 'e': + return add(ents, enemy(c, r, "slime", "patrol", "speed", 0.6)); + case 'w': + return add(ents, enemy(c, r, "beetle", "walker", "speed", 0.8)); + case 'B': + return add(ents, with(with(enemy(c, r, "brute", "chase", "speed", 1.1), "range", 7), "hp", 2)); + case 'T': + return add(ents, with(with(enemy(c, r, "turret", "turret", null, 0), "interval", 90), "range", 12)); + case 'F': + return add(ents, with(enemy(c, r, "frog", "hopper", null, 0), "interval", 80)); + case 'V': + return add(ents, with(enemy(c, r, "bat", "flyer", "speed", 0.9), "range", 6)); + case 'Z': { + Map z = enemy(c, r, "golem", "boss", null, 0); + with(with(with(with(with(with(z, "hp", 8), "opens", 1), "w", 2), "h", 2), "speed", 1.0), "range", 14); + return add(ents, z); + } + default: + return false; + } + } + + private static boolean add(List ents, Map e) { + ents.add(e); + return true; + } + + private static Map thing(String type, int c, int r) { + Map m = new LinkedHashMap(); + m.put("type", type); + m.put("at", ints(c, r)); + return m; + } + + private static Map enemy(int c, int r, String kind, String brain, String numKey, double num) { + Map m = thing("enemy", c, r); + m.put("kind", kind); + m.put("brain", brain); + if (numKey != null) { + m.put(numKey, new Double(num)); + } + return m; + } + + private static Map with(Map m, String k, Object v) { + m.put(k, v instanceof Integer ? new Long(((Integer) v).intValue()) : v); + return m; + } + + private static List ints(int... v) { + List l = new ArrayList(v.length); + for (int i = 0; i < v.length; i++) { + l.add(new Long(v[i])); + } + return l; + } + + private static void fixed(StringBuilder sb, int fx) { + if (fx < 0) { + sb.append('-'); + } + long a = Math.abs((long) fx); + sb.append(a >> 16); + if ((a & 0xffff) == 0) { + return; + } + // A quarter step above the value: a reader that truncates and one + // that rounds to nearest both land back on exactly `fx`. + long frac = ((a & 0xffff) << 2) + 1; + sb.append('.'); + while (frac != 0) { + frac *= 10; + sb.append((char) ('0' + (frac >> 18))); + frac &= 0x3ffff; + } + } + + @SuppressWarnings("unchecked") + private static void write(StringBuilder sb, Object v) { + if (v == null) { + sb.append("null"); + } else if (v instanceof String) { + LevelJson.quote(sb, (String) v); + } else if (v instanceof Boolean) { + sb.append(((Boolean) v).booleanValue() ? "true" : "false"); + } else if (v instanceof Double || v instanceof Float) { + double d = ((Number) v).doubleValue(); + if (d == Math.floor(d) && Math.abs(d) < 1e15) { + sb.append((long) d); + } else { + sb.append(d); + } + } else if (v instanceof Integer) { + // LevelJson reads every number into 16.16 fixed point; write it back + // as its exact decimal so it parses to the very same value. + fixed(sb, ((Integer) v).intValue()); + } else if (v instanceof Number) { + sb.append(((Number) v).longValue()); + } else if (v instanceof Map) { + sb.append('{'); + Iterator> it = ((Map) v).entrySet().iterator(); + boolean first = true; + while (it.hasNext()) { + Map.Entry e = it.next(); + if (!first) { + sb.append(','); + } + first = false; + LevelJson.quote(sb, e.getKey()); + sb.append(':'); + write(sb, e.getValue()); + } + sb.append('}'); + } else if (v instanceof List) { + sb.append('['); + List l = (List) v; + for (int i = 0; i < l.size(); i++) { + if (i > 0) { + sb.append(','); + } + write(sb, l.get(i)); + } + sb.append(']'); + } else { + LevelJson.quote(sb, String.valueOf(v)); + } + } +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Scoring.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Scoring.java new file mode 100644 index 00000000000..465e5144be6 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Scoring.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.levels; + +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.Replay; + +/// How a run is judged, shared so the app shows exactly what the server will +/// record. +/// +/// The server never takes a score from the client. It replays the run's input +/// against the level with `Replay` and scores what happened; the client runs +/// the same code to show the result screen before the server answers. +public final class Scoring { + /// Simulation ticks per second. + public static final int TICKS_PER_SECOND = 60; + /// The longest run that is replayed: ten minutes. + public static final int MAX_TICKS = 10 * 60 * TICKS_PER_SECOND; + /// The longest encoded input accepted, in characters. A real ten-minute run + /// encodes to a few kilobytes; this bounds what a hostile client can make the + /// server parse. + public static final int MAX_LOG_CHARS = 64 * 1024; + /// Points for reaching the goal. + public static final int FINISH_POINTS = 1000; + /// Points per second under par. + public static final int PAR_POINTS_PER_SECOND = 50; + /// Points lost per death. + public static final int DEATH_PENALTY = 100; + + private Scoring() { + } + + /// Replays a run. + /// + /// #### Parameters + /// + /// - `index`: the level index in `LevelPack` + /// - `seed`: the run's seed + /// - `encodedLog`: the input in `InputLog` encoding + /// + /// #### Returns + /// + /// the outcome, or null if the log is malformed or too long + public static Replay.Result replay(int index, long seed, String encodedLog) { + if (index < 0 || index >= LevelPack.IDS.length || encodedLog == null + || encodedLog.length() > MAX_LOG_CHARS) { + return null; + } + InputLog log; + try { + log = InputLog.decode(encodedLog, MAX_TICKS); + } catch (IllegalArgumentException e) { + return null; + } + return Replay.run(LevelPack.load(index), seed, log); + } + + /// The score of a finished run: what was collected, a finishing bonus and a + /// bonus for every second under par, less a penalty per death. + /// + /// #### Parameters + /// + /// - `index`: the level index + /// - `r`: the replayed outcome + /// + /// #### Returns + /// + /// the points, 0 for a run that did not finish + public static long points(int index, Replay.Result r) { + if (r == null || !r.isComplete()) { + return 0; + } + long par = (long) LevelPack.PAR[index] * TICKS_PER_SECOND; + long under = Math.max(0, par - r.getTicks()); + long p = r.getScore() + FINISH_POINTS + under * PAR_POINTS_PER_SECOND / TICKS_PER_SECOND + - (long) r.getDeaths() * DEATH_PENALTY; + return Math.max(1, p); + } + + /// Stars for a finished run: one for finishing, one for beating par, one for + /// every hidden gem (or, in a level without one, for finishing without dying). + /// + /// #### Parameters + /// + /// - `index`: the level index + /// - `r`: the replayed outcome + /// + /// #### Returns + /// + /// 0 to 3 + public static int stars(int index, Replay.Result r) { + if (r == null || !r.isComplete()) { + return 0; + } + int s = 1; + if (r.getTicks() <= LevelPack.PAR[index] * TICKS_PER_SECOND) { + s++; + } + int gems = LevelPack.GEMS[index]; + if (gems > 0 ? r.getSecrets() >= gems : r.getDeaths() == 0) { + s++; + } + return s; + } + + /// The level a day's challenge is played on. + /// + /// #### Parameters + /// + /// - `day`: days since the epoch + /// + /// #### Returns + /// + /// a level index + public static int dailyLevel(long day) { + long n = LevelPack.IDS.length; + return (int) (((day % n) + n) % n); + } + + /// Formats ticks as `m:ss.cc`. + /// + /// #### Parameters + /// + /// - `ticks`: simulation ticks + /// + /// #### Returns + /// + /// the time + public static String time(int ticks) { + int cs = ticks * 100 / TICKS_PER_SECOND; + int m = cs / 6000; + int s = (cs / 100) % 60; + int c = cs % 100; + return m + ":" + (s < 10 ? "0" : "") + s + "." + (c < 10 ? "0" : "") + c; + } +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Solver.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Solver.java new file mode 100644 index 00000000000..3be8abe08b4 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/Solver.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.codenameone.examples.ledge.levels; + +import com.codename1.gaming.platformer.Actor; +import com.codename1.gaming.platformer.Body; +import com.codename1.gaming.platformer.GlideAbility; +import com.codename1.gaming.platformer.Input; +import com.codename1.gaming.platformer.InputLog; +import com.codename1.gaming.platformer.JetpackAbility; +import com.codename1.gaming.platformer.LevelData; +import com.codename1.gaming.platformer.PlatformWorld; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +/// Proves a level can be finished by finding a run that finishes it. +/// +/// The simulation is deterministic, so a run is just its input, and any state a +/// run reached can be reached again by replaying that input from the start. +/// The solver keeps an archive of the places it has reached (a tile, whether +/// the hero stood, the keys held and the switches thrown), each with the +/// shortest input that got there. Every round it goes back to one of them -- +/// favouring the ones nearest the goal and the ones it has tried least -- and +/// presses buttons at random from there for a moment, archiving whatever is +/// new. This is the "Go-Explore" idea, and platformers suit it well: being +/// somewhere new is almost always progress. +/// +/// The level editor runs it before a level is published, the server runs it on +/// levels a language model wrote, and the template's tests run it over every +/// shipped level. The run it finds also drives the menu's attract mode. +public final class Solver { + /// Button chords the solver holds, most of them heading right. + private static final int[] CHORDS = { + Input.RIGHT | Input.RUN, + Input.RIGHT | Input.RUN | Input.JUMP, + Input.RIGHT | Input.JUMP, + Input.RIGHT, + Input.LEFT | Input.RUN, + Input.LEFT | Input.RUN | Input.JUMP, + Input.LEFT | Input.JUMP, + Input.JUMP, + 0, + Input.UP, + Input.DOWN, + Input.DOWN | Input.JUMP, + Input.RIGHT | Input.RUN | Input.DASH, + Input.LEFT | Input.DASH, + Input.UP | Input.RIGHT, + Input.ACTIVATE, + Input.RIGHT | Input.FIRE, + Input.LEFT | Input.FIRE, + Input.FIRE | Input.JUMP, + }; + + private final LevelData level; + private final long seed; + private final Random random; + private final Map archive = new HashMap(); + private final List cells = new ArrayList(); + private int maxTicks = 60 * 60 * 5; + private long simulatedTicks; + + private static final class Cell { + final int[] input; + final int distance; + final int col; + final int row; + int chosen; + + Cell(int[] input, int distance, int col, int row) { + this.input = input; + this.distance = distance; + this.col = col; + this.row = row; + } + } + + /// A solver for one level and seed. + /// + /// #### Parameters + /// + /// - `level`: the level + /// - `seed`: the world seed runs use + /// - `searchSeed`: seeds the solver's own choices, so a search repeats + public Solver(LevelData level, long seed, long searchSeed) { + this.level = level; + this.seed = seed; + this.random = new Random(searchSeed); + } + + /// The longest run the solver will consider, in ticks. Five minutes by default. + /// + /// #### Parameters + /// + /// - `ticks`: the cap + public void setMaxTicks(int ticks) { + maxTicks = ticks; + } + + /// Ticks simulated so far, the solver's measure of effort. + /// + /// #### Returns + /// + /// the tick count + public long getSimulatedTicks() { + return simulatedTicks; + } + + /// Searches for a finishing run. + /// + /// #### Parameters + /// + /// - `budgetTicks`: how many ticks of simulation to spend before giving up + /// + /// #### Returns + /// + /// the input of a run that reaches the goal, or null when none was found in + /// the budget + public InputLog solve(long budgetTicks) { + PlatformWorld start = level.createWorld(seed); + add(new int[0], start); + while (simulatedTicks < budgetTicks) { + Cell from = pick(); + from.chosen++; + PlatformWorld w = level.createWorld(seed); + int deaths = w.getDeaths(); + for (int i = 0; i < from.input.length; i++) { + w.step(from.input[i]); + } + simulatedTicks += from.input.length; + int[] buf = new int[from.input.length + 240]; + System.arraycopy(from.input, 0, buf, 0, from.input.length); + int n = from.input.length; + int segments = 1 + random.nextInt(6); + boolean dead = false; + for (int s = 0; s < segments && !dead; s++) { + int chord = CHORDS[random.nextInt(CHORDS.length)]; + int hold = 3 + random.nextInt(26); + for (int t = 0; t < hold; t++) { + if (n >= maxTicks || n >= buf.length) { + dead = true; + break; + } + // Releasing jump for a tick now and then lets a held jump + // chord jump again instead of only once. + int in = (t == hold - 1 && (chord & Input.JUMP) != 0) ? chord & ~Input.JUMP : chord; + w.step(in); + buf[n++] = in; + simulatedTicks++; + if (w.isComplete()) { + int[] done = new int[n]; + System.arraycopy(buf, 0, done, 0, n); + return toLog(done); + } + if (w.getDeaths() != deaths || w.isGameOver() || w.getPlayer() == null + || !w.getPlayer().isAlive()) { + dead = true; + break; + } + if ((t & 3) == 3) { + int[] in2 = new int[n]; + System.arraycopy(buf, 0, in2, 0, n); + add(in2, w); + } + } + } + } + return null; + } + + private void add(int[] input, PlatformWorld w) { + Actor p = w.getPlayer(); + if (p == null) { + return; + } + Body b = p.getBody(); + int ts = w.getGrid().getTileSize(); + int col = (b.x + b.w / 2) / ts; + int row = (b.y + b.h - 1) / ts; + long key = col; + key = key * 1024 + row; + key = key * 2 + (b.isGrounded() ? 1 : 0); + key = key * 16 + Math.min(15, w.getKeys().size()); + key = key * 4 + (w.isChannelOn(1) ? 1 : 0) + (w.isChannelOn(2) ? 2 : 0); + key = key * 4 + (p.getAbility(JetpackAbility.class) != null ? 1 : 0) + + (p.getAbility(GlideAbility.class) != null ? 2 : 0); + // Damage done to the enemies is progress too: a boss is beaten a hit + // at a time, and every hit has to be a place worth coming back to. + int foes = 0; + List actors = w.getActors(); + for (int i = 1; i < actors.size(); i++) { + Actor a = actors.get(i); + if (a.isAlive()) { + foes += a.getHealth() == null ? 1 : a.getHealth().getCurrent(); + } + } + key = key * 64 + Math.min(63, foes); + Cell old = archive.get(Long.valueOf(key)); + if (old != null && old.input.length <= input.length) { + return; + } + int[] goal = w.getGoal(); + int gc = (goal[0] + goal[2] / 2) / ts; + int gr = (goal[1] + goal[3] / 2) / ts; + int dist = Math.abs(col - gc) + Math.abs(row - gr); + Cell c = new Cell(input, dist, col, row); + if (old != null) { + c.chosen = old.chosen; + cells.remove(old); + } + archive.put(Long.valueOf(key), c); + cells.add(c); + } + + /// Where the search came closest to the goal, for telling a level's author + /// where it got stuck. + /// + /// #### Returns + /// + /// `{column, row, distance in tiles}`, or null before a search + public int[] getClosest() { + Cell best = null; + for (int i = 0; i < cells.size(); i++) { + Cell c = cells.get(i); + if (best == null || c.distance < best.distance) { + best = c; + } + } + return best == null ? null : new int[] {best.col, best.row, best.distance}; + } + + /// How many distinct places the search has reached. + /// + /// #### Returns + /// + /// the archive size + public int getExplored() { + return cells.size(); + } + + private Cell pick() { + if (random.nextInt(2) == 0) { + // Among the cells nearest the goal, the least tried. + Cell best = null; + for (int i = 0; i < cells.size(); i++) { + Cell c = cells.get(i); + if (best == null || c.distance * 4 + c.chosen < best.distance * 4 + best.chosen) { + best = c; + } + } + return best; + } + // Otherwise anywhere, the least tried first. + Cell pick = cells.get(random.nextInt(cells.size())); + for (int k = 0; k < 3; k++) { + Cell c = cells.get(random.nextInt(cells.size())); + if (c.chosen < pick.chosen) { + pick = c; + } + } + return pick; + } + + private static InputLog toLog(int[] input) { + InputLog log = new InputLog(); + for (int i = 0; i < input.length; i++) { + log.add(input[i]); + } + return log; + } +} diff --git a/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/package-info.java b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/package-info.java new file mode 100644 index 00000000000..b5bccd463b2 --- /dev/null +++ b/scripts/ledge/shared/src/main/java/com/codenameone/examples/ledge/levels/package-info.java @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +/// The game's content and its rules, shared by the app and the server: every shipped +/// level (`LevelPack`, generated by `tools/pack-levels.py`), how a run is replayed and +/// scored (`Scoring`), and the `Solver` that proves a level can be finished. +package com.codenameone.examples.ledge.levels; diff --git a/scripts/ledge/tools/make-art.py b/scripts/ledge/tools/make-art.py new file mode 100755 index 00000000000..37ebf9ec062 --- /dev/null +++ b/scripts/ledge/tools/make-art.py @@ -0,0 +1,1168 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Codename One and/or its affiliates. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +"""Draws every image and sound Ledge ships into common/src/main/resources. + + tools/make-art.py # everything + tools/make-art.py tiles # one group: tiles, actors, items, backdrops, ui, sfx + +Nothing is downloaded: every picture is drawn here from shapes and every sound +is synthesised, so the whole look can be re-tuned by editing a palette or a +pose and running the script again. That is the point of it -- it is the +template's stand-in for an asset store, and a developer (or a language model, +see the platformer-art skill) changes the game's look by changing this file. + +Conventions the game relies on (see play/LedgeArt.java): + +* Art is drawn at 4 art pixels per world pixel, so a 16 px tile is 64 px. +* tiles_.png is an 8 x 4 atlas of 64 px cells: 0-15 solid ground by + which sides are open (bit 1 top, 2 right, 4 bottom, 8 left), 16-21 the six + slopes in Tile order, 22-25 one-way ledges (middle, left end, right end, + both ends), 26 ladder, 27 spikes, 28 water surface, 29 water. +* Actor sheets are one row of equal frames; the feet sit on the bottom edge, + centred. hero.png frames are listed in HERO_FRAMES. +* Item images are centred on the item's rectangle. +* bg__.png are backdrops, 0 the farthest; each tiles horizontally. + +Needs Pillow; ffmpeg is not needed. +""" +import math +import os +import random +import struct +import sys +import wave + +from PIL import Image, ImageChops, ImageDraw, ImageFilter + +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.join(HERE, '..', 'common', 'src', 'main', 'resources') +SS = 4 # supersampling for smooth edges +T = 64 # art pixels per tile + +THEMES = { + # body, body dark, cap, cap light, outline, accent + 'meadow': dict(body=(146, 96, 64), dark=(98, 60, 42), cap=(98, 186, 84), capl=(170, 230, 120), + line=(46, 32, 40), accent=(255, 214, 102), stone=(176, 168, 160)), + 'cavern': dict(body=(70, 84, 120), dark=(42, 48, 78), cap=(96, 210, 200), capl=(170, 255, 240), + line=(22, 22, 44), accent=(232, 120, 255), stone=(120, 130, 170)), + 'foundry': dict(body=(96, 84, 88), dark=(58, 50, 56), cap=(232, 160, 60), capl=(255, 214, 120), + line=(30, 22, 26), accent=(255, 110, 60), stone=(150, 140, 140)), + 'sky': dict(body=(232, 226, 240), dark=(176, 168, 200), cap=(255, 206, 110), capl=(255, 240, 190), + line=(70, 64, 110), accent=(130, 200, 255), stone=(220, 220, 236)), + 'forge': dict(body=(64, 48, 56), dark=(36, 26, 32), cap=(255, 120, 50), capl=(255, 220, 120), + line=(18, 10, 14), accent=(255, 80, 40), stone=(110, 90, 96)), +} + +HERO_FRAMES = ['idle0', 'idle1', 'run0', 'run1', 'run2', 'run3', 'jump', 'fall', 'crouch', + 'climb0', 'climb1', 'hurt', 'dash', 'cling', 'glide', 'jet', 'swim', 'cheer'] + + +# ------------------------------------------------------------------ helpers +def big(w, h): + return Image.new('RGBA', (w * SS, h * SS), (0, 0, 0, 0)) + + +def small(img): + return img.resize((img.width // SS, img.height // SS), Image.LANCZOS) + + +def S(v): + return int(round(v * SS)) + + +def pts(seq, ox=0, oy=0): + return [((x + ox) * SS, (y + oy) * SS) for x, y in seq] + + +def mix(a, b, t): + return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(3)) + + +def lighten(c, t): + return mix(c, (255, 255, 255), t) + + +def darken(c, t): + return mix(c, (0, 0, 0), t) + + +def rgba(c, a=255): + return (c[0], c[1], c[2], a) + + +def vgrad(w, h, top, bottom): + g = Image.new('RGBA', (w, h)) + d = ImageDraw.Draw(g) + for y in range(h): + d.line([(0, y), (w, y)], fill=rgba(mix(top, bottom, y / max(1, h - 1)))) + return g + + +def fill_mask(img, mask, paint): + """Paints `paint` (an image the size of img, or a colour) through `mask`.""" + if not isinstance(paint, Image.Image): + paint = Image.new('RGBA', img.size, rgba(paint) if len(paint) == 3 else paint) + img.paste(paint, (0, 0), mask) + + +def outline(img, color, width): + """Puts a coloured outline under the art: the 'sticker' edge of the style.""" + a = img.split()[3] + grown = a.filter(ImageFilter.MaxFilter(width * 2 + 1)) + base = Image.new('RGBA', img.size, rgba(color)) + base.putalpha(grown) + base.alpha_composite(img) + return base + + +def soft_glow(img, color, radius, strength=1.0): + a = img.split()[3].filter(ImageFilter.GaussianBlur(radius)) + if strength != 1.0: + a = a.point(lambda v: min(255, int(v * strength))) + g = Image.new('RGBA', img.size, rgba(color)) + g.putalpha(a) + g.alpha_composite(img) + return g + + +def save(img, name): + path = os.path.join(OUT, name) + img.save(path, optimize=True) + return path + + +def shape(w, h, draw_fn): + """A mask drawn at supersampled size.""" + m = Image.new('L', (w * SS, h * SS), 0) + draw_fn(ImageDraw.Draw(m)) + return m + + +# --------------------------------------------------------------------- tiles +def speckle(img, rnd, base, n, rmin, rmax, spread=0.12, alpha=90): + d = ImageDraw.Draw(img) + w, h = img.size + for _ in range(n): + x = rnd.uniform(0, w) + y = rnd.uniform(0, h) + r = rnd.uniform(rmin, rmax) * SS + c = lighten(base, spread) if rnd.random() < 0.5 else darken(base, spread) + d.ellipse([x - r, y - r * 0.7, x + r, y + r * 0.7], fill=rgba(c, alpha)) + + +def body_texture(th, theme, rnd): + """A cell of ground: a vertical gradient with stones and grain.""" + img = vgrad(S(T), S(T), lighten(th['body'], 0.06), th['body']) + speckle(img, rnd, th['body'], 26, 2, 6) + d = ImageDraw.Draw(img) + if theme == 'meadow': + for _ in range(3): + x, y = rnd.uniform(8, 56), rnd.uniform(14, 58) + r = rnd.uniform(3, 6) + d.ellipse(pts([(x - r, y - r * 0.7), (x + r, y + r * 0.7)]), fill=rgba(th['stone'])) + d.ellipse(pts([(x - r * 0.6, y - r * 0.6), (x + r * 0.2, y - r * 0.1)]), fill=rgba(lighten(th['stone'], 0.4))) + elif theme == 'cavern': + for _ in range(2): + x, y = rnd.uniform(10, 54), rnd.uniform(18, 54) + s = rnd.uniform(4, 8) + d.polygon(pts([(x, y - s), (x + s * 0.5, y), (x, y + s * 0.6), (x - s * 0.5, y)]), + fill=rgba(lighten(th['accent'], 0.2), 200)) + elif theme in ('foundry', 'forge'): + # plates and rivets + d.line(pts([(0, 32), (64, 32)]), fill=rgba(darken(th['body'], 0.25)), width=S(2)) + d.line(pts([(32, 0), (32, 32)]), fill=rgba(darken(th['body'], 0.25)), width=S(2)) + d.line(pts([(16, 32), (16, 64)]), fill=rgba(darken(th['body'], 0.25)), width=S(2)) + for (x, y) in [(6, 6), (58, 6), (6, 38), (58, 38), (26, 38)]: + d.ellipse(pts([(x - 2.2, y - 2.2), (x + 2.2, y + 2.2)]), fill=rgba(lighten(th['body'], 0.35))) + if theme == 'forge': + for _ in range(2): + x0, y0 = rnd.uniform(6, 58), rnd.uniform(36, 60) + pts_ = [(x0, y0)] + for k in range(3): + x0 += rnd.uniform(-7, 7) + y0 += rnd.uniform(-6, 2) + pts_.append((x0, y0)) + d.line(pts(pts_), fill=rgba(th['accent'], 230), width=S(2)) + elif theme == 'sky': + d.line(pts([(0, 40), (64, 40)]), fill=rgba(darken(th['body'], 0.08)), width=S(1)) + for (x, y) in [(20, 52), (46, 24)]: + d.ellipse(pts([(x - 3, y - 2), (x + 3, y + 2)]), fill=rgba(lighten(th['accent'], 0.5), 160)) + return img + + +def cap_band(th, theme, rnd, w, top_y=0): + """The top surface: grass, moss, a steel lip, a gilded rim or embers.""" + img = big(w, 24) + d = ImageDraw.Draw(img) + if theme == 'meadow': + # grass with a scalloped underside and blades on top + poly = [(0, 0), (w, 0), (w, 12)] + steps = w // 8 + for i in range(steps, -1, -1): + x = i * 8 + poly.append((x, 12 + (4 if i % 2 == 0 else 8))) + poly.append((0, 12)) + d.polygon(pts(poly), fill=rgba(th['cap'])) + d.rectangle(pts([(0, 0), (w, 4)]), fill=rgba(th['capl'])) + for i in range(w // 5): + x = i * 5 + rnd.uniform(0, 3) + h = rnd.uniform(2, 5) + d.polygon(pts([(x, 1), (x + 1.5, -h + 1), (x + 3, 1)]), fill=rgba(th['capl'])) + elif theme == 'cavern': + d.rounded_rectangle(pts([(0, 0), (w, 10)]), radius=S(3), fill=rgba(th['cap'], 230)) + d.rectangle(pts([(0, 0), (w, 3)]), fill=rgba(th['capl'])) + for i in range(w // 10): + x = i * 10 + rnd.uniform(1, 6) + d.polygon(pts([(x, 9), (x + 2, 9 + rnd.uniform(4, 9)), (x + 4, 9)]), fill=rgba(th['cap'], 200)) + elif theme == 'foundry': + d.rectangle(pts([(0, 0), (w, 9)]), fill=rgba((70, 66, 72))) + d.rectangle(pts([(0, 0), (w, 2.5)]), fill=rgba((170, 166, 176))) + for i in range(-1, w // 10 + 1): + x = i * 10 + d.polygon(pts([(x, 3), (x + 5, 3), (x + 10, 9), (x + 5, 9)]), fill=rgba(th['cap'])) + elif theme == 'sky': + d.rectangle(pts([(0, 0), (w, 8)]), fill=rgba(th['cap'])) + d.rectangle(pts([(0, 0), (w, 2.5)]), fill=rgba(th['capl'])) + d.line(pts([(0, 8), (w, 8)]), fill=rgba(darken(th['cap'], 0.25)), width=S(1.5)) + elif theme == 'forge': + d.rectangle(pts([(0, 0), (w, 7)]), fill=rgba(darken(th['body'], 0.2))) + d.rectangle(pts([(0, 0), (w, 2)]), fill=rgba(th['cap'])) + for i in range(w // 12): + x = i * 12 + rnd.uniform(0, 6) + d.ellipse(pts([(x, 3), (x + 3, 6)]), fill=rgba(th['capl'], 220)) + return img + + +def solid_cell(th, theme, mask, rnd): + top, right, bottom, left = mask & 1, mask & 2, mask & 4, mask & 8 + img = body_texture(th, theme, rnd) + d = ImageDraw.Draw(img) + edge = darken(th['body'], 0.35) + # open sides get a shaded rim + for side, on in (('l', left), ('r', right), ('b', bottom)): + if not on: + continue + for k in range(8): + a = int(110 * (1 - k / 8)) + if side == 'l': + d.line(pts([(k, 0), (k, 64)]), fill=rgba(edge, a), width=SS) + elif side == 'r': + d.line(pts([(63 - k, 0), (63 - k, 64)]), fill=rgba(edge, a), width=SS) + else: + d.line(pts([(0, 63 - k), (64, 63 - k)]), fill=rgba(edge, a), width=SS) + if top: + band = cap_band(th, theme, rnd, T) + img.alpha_composite(band, (0, 0)) + # round the corners where two open sides meet + m = Image.new('L', img.size, 255) + md = ImageDraw.Draw(m) + rad = 14 + for (on, corner) in ((top and left, 'tl'), (top and right, 'tr'), (bottom and left, 'bl'), (bottom and right, 'br')): + if not on: + continue + r = rad if corner[0] == 't' else 10 + cx = r if corner[1] == 'l' else 64 - r + cy = r if corner[0] == 't' else 64 - r + x0 = 0 if corner[1] == 'l' else 64 - r + y0 = 0 if corner[0] == 't' else 64 - r + md.rectangle(pts([(x0, y0), (x0 + r, y0 + r)]), fill=0) + md.ellipse(pts([(cx - r, cy - r), (cx + r, cy + r)]), fill=255) + img.putalpha(ImageChops.multiply(img.split()[3], m)) + return small(img) + + +SLOPES = { # kind index 16.. : polygon of the solid part, surface from p0 to p1 + 16: ((0, 64), (64, 0)), # '/' SLOPE_UP + 17: ((0, 0), (64, 64)), # '\' SLOPE_DOWN + 18: ((0, 64), (64, 32)), # a SLOPE_UP_LOW + 19: ((0, 32), (64, 0)), # b SLOPE_UP_HIGH + 20: ((0, 0), (64, 32)), # c SLOPE_DOWN_HIGH + 21: ((0, 32), (64, 64)), # d SLOPE_DOWN_LOW +} + + +def slope_cell(th, theme, idx, rnd): + (x0, y0), (x1, y1) = SLOPES[idx] + img = body_texture(th, theme, rnd) + m = shape(T, T, lambda d: d.polygon(pts([(x0, y0), (x1, y1), (64, 64), (0, 64)]), fill=255)) + img.putalpha(m) + # the cap follows the surface: draw a band and shear it + band = small(cap_band(th, theme, rnd, 90)) + ang = math.degrees(math.atan2(y1 - y0, x1 - x0)) + rot = band.rotate(-ang, resample=Image.BICUBIC, expand=True) + cap = Image.new('RGBA', (T, T), (0, 0, 0, 0)) + cx, cy = (x0 + x1) / 2, (y0 + y1) / 2 + off = 6 + cap.alpha_composite(rot, (int(cx - rot.width / 2 + off * math.sin(math.radians(ang))), + int(cy - rot.height / 2 + off * math.cos(math.radians(ang)) - 1))) + cm = small(m) + out = small(img) + cap.putalpha(ImageChops.multiply(cap.split()[3], cm)) + out.alpha_composite(cap) + return out + + +def ledge_cell(th, theme, ends, rnd): + img = big(T, T) + d = ImageDraw.Draw(img) + l = 4 if ends & 1 else -2 + r = 60 if ends & 2 else 66 + wood = mix(th['body'], (150, 100, 60), 0.6) if theme in ('meadow', 'cavern') else th['stone'] + d.rounded_rectangle(pts([(l, 0), (r, 16)]), radius=S(5), fill=rgba(wood)) + d.rounded_rectangle(pts([(l, 0), (r, 5)]), radius=S(3), fill=rgba(lighten(wood, 0.3))) + d.line(pts([(l + 2, 13), (r - 2, 13)]), fill=rgba(darken(wood, 0.3)), width=S(2)) + for x in (16, 48): + d.polygon(pts([(x - 3, 16), (x + 3, 16), (x + 1, 26), (x - 1, 26)]), fill=rgba(darken(wood, 0.25))) + band = cap_band(th, theme, rnd, T) + if theme == 'meadow': + band = band.crop((0, 0, band.width, S(14))) + mk = shape(T, 14, lambda dd: dd.rounded_rectangle(pts([(l, 0), (r, 14)]), radius=S(5), fill=255)) + band.putalpha(ImageChops.multiply(band.split()[3], mk)) + img.alpha_composite(band) + return small(img) + + +def ladder_cell(th): + img = big(T, T) + d = ImageDraw.Draw(img) + wood = (170, 120, 70) + for x in (14, 46): + d.rounded_rectangle(pts([(x, -2), (x + 6, 66)]), radius=S(2), fill=rgba(wood)) + d.line(pts([(x + 1.5, 0), (x + 1.5, 64)]), fill=rgba(lighten(wood, 0.3)), width=S(1.5)) + for y in (10, 32, 54): + d.rounded_rectangle(pts([(18, y), (48, y + 5)]), radius=S(2), fill=rgba(darken(wood, 0.1))) + d.line(pts([(19, y + 1), (47, y + 1)]), fill=rgba(lighten(wood, 0.25)), width=S(1)) + return outline(small(img), th['line'], 1) + + +def spike_cell(th, theme): + img = big(T, T) + d = ImageDraw.Draw(img) + metal = (200, 206, 220) if theme != 'forge' else (255, 150, 70) + d.rectangle(pts([(0, 52), (64, 64)]), fill=rgba(darken(th['body'], 0.2))) + for i in range(4): + x = i * 16 + d.polygon(pts([(x + 1, 54), (x + 8, 22), (x + 15, 54)]), fill=rgba(darken(metal, 0.25))) + d.polygon(pts([(x + 4, 54), (x + 8, 22), (x + 9, 54)]), fill=rgba(lighten(metal, 0.4))) + return outline(small(img), th['line'], 1) + + +def water_cell(surface): + img = big(T, T) + d = ImageDraw.Draw(img) + d.rectangle(pts([(0, 0), (64, 64)]), fill=(70, 150, 230, 120)) + if surface: + poly = [(0, 64), (0, 8)] + for i in range(17): + x = i * 4 + poly.append((x, 8 + 3 * math.sin(i * math.pi / 4))) + poly += [(64, 64)] + img = big(T, T) + d = ImageDraw.Draw(img) + d.polygon(pts(poly), fill=(70, 150, 230, 130)) + d.line(pts(poly[1:-1]), fill=(220, 245, 255, 220), width=S(2)) + return small(img) + + +def make_tiles(): + for theme, th in THEMES.items(): + rnd = random.Random(theme) + atlas = Image.new('RGBA', (8 * T, 4 * T), (0, 0, 0, 0)) + cells = {} + for mask in range(16): + cells[mask] = solid_cell(th, theme, mask, rnd) + for idx in SLOPES: + cells[idx] = slope_cell(th, theme, idx, rnd) + for e in range(4): + cells[22 + e] = ledge_cell(th, theme, e, rnd) + cells[26] = ladder_cell(th) + cells[27] = spike_cell(th, theme) + cells[28] = water_cell(True) + cells[29] = water_cell(False) + for i, c in cells.items(): + atlas.alpha_composite(c, ((i % 8) * T, (i // 8) * T)) + save(atlas, 'tiles_%s.png' % theme) + # the moving platform: left cap, middle, right cap + plat = big(3 * T, 32) + d = ImageDraw.Draw(plat) + top = th['stone'] if theme != 'meadow' else (176, 124, 78) + d.rounded_rectangle(pts([(4, 2), (188, 26)]), radius=S(9), fill=rgba(top)) + d.rounded_rectangle(pts([(4, 2), (188, 9)]), radius=S(4), fill=rgba(lighten(top, 0.35))) + d.line(pts([(14, 22), (178, 22)]), fill=rgba(darken(top, 0.3)), width=S(2)) + d.ellipse(pts([(88, 14), (104, 30)]), fill=rgba(th['accent'])) + d.ellipse(pts([(91, 17), (97, 23)]), fill=rgba(lighten(th['accent'], 0.6))) + plat = soft_glow(outline(small(plat), th['line'], 2), th['accent'], 3, 0.6) + save(plat, 'platform_%s.png' % theme) + + +# -------------------------------------------------------------------- actors +TEAL = (64, 186, 176) +TEAL_D = (34, 120, 128) +SKIN = (255, 228, 200) +SCARF = (255, 118, 72) +SCARF_D = (214, 70, 52) +BOOT = (52, 46, 70) +HERO_LINE = (36, 28, 52) + + +def hero_pose(name): + p = dict(bob=0, sx=1.0, sy=1.0, tilt=0, legs=((0, 0), (0, 0)), arms=(20, -20), scarf=0.0, + eyes='open', fx=None, back=False) + if name == 'idle1': + p.update(bob=1.5, sx=1.04, sy=0.97, scarf=0.15) + elif name.startswith('run'): + k = int(name[-1]) + ph = k * math.pi / 2 + p.update(bob=-abs(math.sin(ph)) * 3, tilt=6, scarf=0.6 + 0.2 * math.sin(ph), + legs=((math.sin(ph) * 9, -max(0, math.cos(ph)) * 7), (-math.sin(ph) * 9, -max(0, -math.cos(ph)) * 7)), + arms=(-math.sin(ph) * 40, math.sin(ph) * 40)) + elif name == 'jump': + p.update(sy=1.08, sx=0.94, legs=((-4, -8), (5, -3)), arms=(-60, -50), scarf=-0.6) + elif name == 'fall': + p.update(sy=1.02, legs=((-5, -2), (5, -5)), arms=(-130, 130), scarf=1.0) + elif name == 'crouch': + p.update(sy=0.72, sx=1.12, bob=0, legs=((-7, 0), (7, 0)), arms=(40, -40), scarf=0.2) + elif name.startswith('climb'): + k = int(name[-1]) + p.update(back=True, legs=((-5, -6 if k else 0), (5, 0 if k else -6)), + arms=((-150, 160) if k else (-160, 150))) + elif name == 'hurt': + p.update(tilt=-14, eyes='x', arms=(-100, 100), legs=((-6, -4), (6, -1)), scarf=0.8) + elif name == 'dash': + p.update(tilt=22, sx=1.12, sy=0.92, legs=((-10, -2), (4, -6)), arms=(70, 60), scarf=1.4, fx='dash') + elif name == 'cling': + p.update(tilt=-6, legs=((-4, -10), (4, -3)), arms=(-140, -40), scarf=0.5, eyes='squint') + elif name == 'glide': + p.update(legs=((-3, -4), (4, -6)), arms=(-95, 95), scarf=1.1, fx='glide') + elif name == 'jet': + p.update(legs=((-3, -3), (3, -5)), arms=(-30, 30), scarf=0.9, fx='jet') + elif name == 'swim': + p.update(tilt=60, legs=((-6, -2), (6, -6)), arms=(-150, -100), scarf=1.0) + elif name == 'cheer': + p.update(bob=-4, arms=(-160, 160), eyes='happy', scarf=0.7, legs=((-5, 0), (5, 0))) + return p + + +def limb(d, x0, y0, length, ang_deg, width, color): + a = math.radians(ang_deg) + x1 = x0 + math.sin(a) * length + y1 = y0 + math.cos(a) * length + d.line(pts([(x0, y0), (x1, y1)]), fill=rgba(color), width=S(width)) + r = width / 2 + d.ellipse(pts([(x1 - r, y1 - r), (x1 + r, y1 + r)]), fill=rgba(color)) + return x1, y1 + + +def draw_hero(name): + W, H = 128, 128 + p = hero_pose(name) + img = big(W, H) + d = ImageDraw.Draw(img) + cx = 64 + feet = 124 + bob = p['bob'] + sx, sy = p['sx'], p['sy'] + body_h = 46 * sy + body_w = 40 * sx + hip = feet - 14 + top = hip - body_h + bob + # legs + for i, (lx, ly) in enumerate(p['legs']): + bx = cx + (-8 if i == 0 else 8) * sx + fx_, fy_ = bx + lx, feet + ly - 2 + d.line(pts([(bx, hip + bob), (fx_, fy_ - 4)]), fill=rgba(BOOT), width=S(8)) + d.rounded_rectangle(pts([(fx_ - 6, fy_ - 8), (fx_ + 8, fy_ + 1)]), radius=S(4), fill=rgba(BOOT)) + d.line(pts([(fx_ - 4, fy_ - 6), (fx_ + 6, fy_ - 6)]), fill=rgba(lighten(BOOT, 0.25)), width=S(2)) + # scarf tail, behind the body + sw = p['scarf'] + neck_y = top + 18 + tail = [(cx - 6, neck_y - 2)] + for k in range(1, 5): + tx = cx - 6 - k * 9 + ty = neck_y + k * 7 * (1 - sw) - k * 5 * sw + math.sin(k * 1.3 + sw * 3) * 3 + tail.append((tx, ty)) + for k in range(len(tail) - 1, -1, -1): + tx, ty = tail[k] + tail.append((tx + 2, ty + 7 - k * 0.6)) + d.polygon(pts(tail), fill=rgba(SCARF_D)) + # cloak body + body = [(cx - body_w / 2 + 4, top + 14), (cx + body_w / 2 - 4, top + 14), + (cx + body_w / 2 + 2, hip + bob + 2), (cx - body_w / 2 - 2, hip + bob + 2)] + d.polygon(pts(body), fill=rgba(TEAL)) + d.polygon(pts([(cx + 2, top + 16), (cx + body_w / 2 - 3, top + 16), (cx + body_w / 2 + 2, hip + bob + 2), + (cx + 6, hip + bob + 2)]), fill=rgba(TEAL_D)) + d.line(pts([(cx - body_w / 2, hip + bob - 3), (cx + body_w / 2, hip + bob - 3)]), + fill=rgba(lighten(TEAL, 0.4)), width=S(3)) + # back arm then front arm + a_back, a_front = p['arms'] + sh_y = top + 22 + limb(d, cx + 10 * sx, sh_y, 16, a_back, 7, TEAL_D) + # head: hood with a face window + hr = 22 + hx, hy = cx + 2, top + 2 + d.ellipse(pts([(hx - hr, hy - hr), (hx + hr, hy + hr)]), fill=rgba(TEAL)) + d.polygon(pts([(hx - 8, hy - hr + 2), (hx - 16, hy - hr - 10), (hx - 2, hy - hr + 1)]), fill=rgba(TEAL)) + if not p['back']: + fr = 15 + d.ellipse(pts([(hx - fr + 3, hy - fr + 3), (hx + fr + 4, hy + fr + 2)]), fill=rgba(SKIN)) + ey = hy + 1 + for ex in (hx + 3, hx + 13): + if p['eyes'] == 'open': + d.ellipse(pts([(ex - 3, ey - 5), (ex + 3, ey + 5)]), fill=rgba((34, 30, 60))) + d.ellipse(pts([(ex - 1.5, ey - 4), (ex + 1, ey - 1)]), fill=(255, 255, 255, 255)) + elif p['eyes'] == 'x': + d.line(pts([(ex - 3, ey - 3), (ex + 3, ey + 3)]), fill=rgba((34, 30, 60)), width=S(2)) + d.line(pts([(ex - 3, ey + 3), (ex + 3, ey - 3)]), fill=rgba((34, 30, 60)), width=S(2)) + elif p['eyes'] == 'happy': + d.arc(pts([(ex - 4, ey - 3), (ex + 4, ey + 4)]), 200, 340, fill=rgba((34, 30, 60)), width=S(2)) + else: + d.line(pts([(ex - 3, ey), (ex + 3, ey)]), fill=rgba((34, 30, 60)), width=S(2)) + d.ellipse(pts([(hx + 15, hy + 6), (hx + 20, hy + 10)]), fill=(255, 150, 150, 160)) + else: + d.ellipse(pts([(hx - 12, hy - 8), (hx + 10, hy + 12)]), fill=rgba(TEAL_D)) + # scarf wrap + d.rounded_rectangle(pts([(cx - 16, neck_y - 5), (cx + 18, neck_y + 4)]), radius=S(4), fill=rgba(SCARF)) + d.line(pts([(cx - 14, neck_y - 3), (cx + 16, neck_y - 3)]), fill=rgba(lighten(SCARF, 0.35)), width=S(2)) + limb(d, cx - 4 * sx, sh_y, 16, a_front, 7, TEAL) + if p['fx'] == 'glide': + # a leaf parasol held overhead + d.pieslice(pts([(cx - 40, top - 52), (cx + 40, top + 4)]), 180, 360, fill=rgba((120, 200, 90))) + for k in range(5): + a = math.radians(180 + 36 * k + 18) + d.line(pts([(cx, top - 24), (cx + math.cos(a) * 38, top - 24 + math.sin(a) * 26)]), + fill=rgba((80, 150, 70)), width=S(2)) + d.line(pts([(cx, top - 24), (cx, top + 10)]), fill=rgba((120, 80, 50)), width=S(3)) + if p['fx'] == 'jet': + d.rounded_rectangle(pts([(cx - 26, top + 18), (cx - 14, top + 44)]), radius=S(4), fill=rgba((200, 200, 214))) + d.polygon(pts([(cx - 25, top + 44), (cx - 15, top + 44), (cx - 20, top + 66)]), fill=(255, 190, 80, 255)) + d.polygon(pts([(cx - 23, top + 44), (cx - 17, top + 44), (cx - 20, top + 56)]), fill=(255, 250, 200, 255)) + if p['tilt']: + img = img.rotate(-p['tilt'], resample=Image.BICUBIC, center=(S(cx), S(feet - 30))) + out = outline(small(img), HERO_LINE, 2) + if p['fx'] == 'dash': + streak = Image.new('RGBA', out.size, (0, 0, 0, 0)) + sd = ImageDraw.Draw(streak) + for k, y in enumerate((60, 78, 96)): + sd.line([(4, y), (40 - k * 6, y)], fill=(160, 220, 255, 170 - k * 30), width=4) + streak.alpha_composite(out) + out = streak + if p['fx'] == 'jet': + out = soft_glow(out, (255, 180, 80), 4, 0.5) + return out + + +def sheet(frames): + w, h = frames[0].size + out = Image.new('RGBA', (w * len(frames), h), (0, 0, 0, 0)) + for i, f in enumerate(frames): + out.alpha_composite(f, (i * w, 0)) + return out + + +def eye(d, x, y, r, look=1.0, angry=False): + d.ellipse(pts([(x - r, y - r), (x + r, y + r)]), fill=(255, 255, 255, 255)) + pr = r * 0.55 + d.ellipse(pts([(x - pr + look * r * 0.3, y - pr), (x + pr + look * r * 0.3, y + pr)]), fill=rgba((30, 24, 40))) + if angry: + d.line(pts([(x - r * 1.2, y - r * 1.3), (x + r * 1.1, y - r * 0.5)]), fill=rgba((30, 24, 40)), width=S(2.5)) + + +def draw_slime(k): + img = big(96, 96) + d = ImageDraw.Draw(img) + sq = [1.0, 0.86, 1.1, 0.94][k] + w, h = 56 / math.sqrt(sq), 38 * sq + base = 92 + green, dark = (120, 210, 90), (70, 160, 70) + d.ellipse(pts([(48 - w / 2, base - h), (48 + w / 2, base + h * 0.35)]), fill=rgba(dark)) + d.ellipse(pts([(48 - w / 2 + 2, base - h), (48 + w / 2 - 2, base + h * 0.1)]), fill=rgba(green)) + d.rectangle(pts([(0, base), (96, 96)]), fill=(0, 0, 0, 0)) + d.ellipse(pts([(48 - w / 3, base - h * 0.85), (48 - w / 3 + 9, base - h * 0.65)]), fill=(255, 255, 255, 210)) + eye(d, 52, base - h * 0.45, 5) + eye(d, 66, base - h * 0.45, 5) + return outline(small(img), (30, 50, 30), 2) + + +def draw_beetle(k): + img = big(96, 96) + d = ImageDraw.Draw(img) + shell, dark = (150, 96, 220), (96, 56, 160) + base = 92 + for i in range(3): + ph = (k + i) % 4 + lx = 30 + i * 16 + d.line(pts([(lx, base - 12), (lx + (4 if ph < 2 else -4), base)]), fill=rgba((40, 30, 50)), width=S(4)) + d.ellipse(pts([(18, base - 44), (78, base - 8)]), fill=rgba(shell)) + d.chord(pts([(18, base - 44), (78, base - 8)]), 0, 180, fill=rgba(dark)) + d.line(pts([(48, base - 44), (48, base - 26)]), fill=rgba(dark), width=S(2)) + d.ellipse(pts([(28, base - 40), (40, base - 33)]), fill=(255, 255, 255, 170)) + d.ellipse(pts([(66, base - 34), (88, base - 14)]), fill=rgba((60, 40, 70))) + eye(d, 80, base - 26, 4) + return outline(small(img), (30, 20, 40), 2) + + +def draw_brute(k): + img = big(96, 96) + d = ImageDraw.Draw(img) + red, dark = (226, 92, 70), (160, 52, 50) + base = 92 + ph = k * math.pi / 2 + for i, s in enumerate((-1, 1)): + lx = 48 + s * 12 + math.sin(ph) * 6 * s + d.rounded_rectangle(pts([(lx - 6, base - 18), (lx + 6, base)]), radius=S(3), fill=rgba(dark)) + bob = abs(math.sin(ph)) * 2 + d.rounded_rectangle(pts([(20, base - 56 - bob), (76, base - 12 - bob)]), radius=S(16), fill=rgba(red)) + d.rounded_rectangle(pts([(20, base - 30 - bob), (76, base - 12 - bob)]), radius=S(10), fill=rgba(dark)) + for s in (-1, 1): + d.polygon(pts([(48 + s * 18, base - 50 - bob), (48 + s * 30, base - 70 - bob), (48 + s * 10, base - 54 - bob)]), + fill=rgba((250, 236, 210))) + eye(d, 56, base - 40 - bob, 5, angry=True) + eye(d, 70, base - 40 - bob, 5, angry=True) + d.line(pts([(56, base - 26 - bob), (72, base - 26 - bob)]), fill=rgba((60, 20, 20)), width=S(3)) + return outline(small(img), (40, 16, 16), 2) + + +def draw_turret(k): + img = big(96, 96) + d = ImageDraw.Draw(img) + stone, dark = (150, 140, 170), (96, 88, 120) + base = 92 + d.rounded_rectangle(pts([(22, base - 60), (74, base)]), radius=S(10), fill=rgba(stone)) + d.rectangle(pts([(22, base - 16), (74, base)]), fill=rgba(dark)) + glow = [(255, 120, 80), (255, 180, 80), (255, 240, 160)][k] + d.ellipse(pts([(38, base - 50), (62, base - 26)]), fill=rgba((40, 30, 50))) + d.ellipse(pts([(42 + k, base - 46), (58 - k, base - 30)]), fill=rgba(glow)) + d.rounded_rectangle(pts([(60, base - 44), (84, base - 32)]), radius=S(4), fill=rgba(dark)) + out = outline(small(img), (30, 24, 40), 2) + return soft_glow(out, glow, 3, 0.4 + 0.3 * k) + + +def draw_frog(k): + img = big(96, 96) + d = ImageDraw.Draw(img) + body, dark = (250, 180, 60), (220, 120, 40) + base = 92 + if k == 2: # leap + d.ellipse(pts([(26, base - 48), (74, base - 18)]), fill=rgba(body)) + d.line(pts([(30, base - 22), (16, base - 4)]), fill=rgba(dark), width=S(6)) + d.line(pts([(66, base - 22), (80, base - 6)]), fill=rgba(dark), width=S(6)) + top = base - 48 + else: + h = 30 if k == 0 else 24 + d.ellipse(pts([(22, base - h - 4), (76, base)]), fill=rgba(body)) + d.ellipse(pts([(16, base - 14), (36, base)]), fill=rgba(dark)) + d.ellipse(pts([(60, base - 14), (80, base)]), fill=rgba(dark)) + top = base - h - 4 + d.chord(pts([(30, top + 8), (70, top + 30)]), 0, 180, fill=rgba((255, 230, 170))) + eye(d, 40, top + 2, 7) + eye(d, 60, top + 2, 7) + return outline(small(img), (60, 30, 10), 2) + + +def draw_bat(k): + img = big(96, 96) + d = ImageDraw.Draw(img) + body, wing = (110, 80, 160), (70, 50, 120) + cy = 60 + flap = [-22, -6, 12, -6][k] + for s in (-1, 1): + d.polygon(pts([(48 + s * 8, cy - 4), (48 + s * 40, cy + flap - 8), (48 + s * 34, cy + flap + 6), + (48 + s * 22, cy + flap / 2 + 4), (48 + s * 12, cy + 8)]), fill=rgba(wing)) + d.ellipse(pts([(34, cy - 16), (62, cy + 14)]), fill=rgba(body)) + for s in (-1, 1): + d.polygon(pts([(48 + s * 4, cy - 12), (48 + s * 12, cy - 24), (48 + s * 12, cy - 10)]), fill=rgba(body)) + eye(d, 43, cy - 2, 4, 0.0) + eye(d, 53, cy - 2, 4, 0.0) + d.polygon(pts([(45, cy + 7), (47, cy + 11), (49, cy + 7)]), fill=(255, 255, 255, 255)) + return outline(small(img), (24, 16, 40), 2) + + +def draw_golem(k): + img = big(192, 192) + d = ImageDraw.Draw(img) + rock, dark, lava = (96, 74, 82), (62, 46, 54), (255, 120, 50) + if k >= 4: + lava = (255, 70, 40) + base = 188 + ph = (k % 4) * math.pi / 2 + for s in (-1, 1): + lx = 96 + s * 30 + math.sin(ph) * 8 * s + d.rounded_rectangle(pts([(lx - 16, base - 40), (lx + 16, base)]), radius=S(8), fill=rgba(dark)) + bob = abs(math.sin(ph)) * 4 + body = [(46, base - 40 - bob), (36, base - 110 - bob), (70, base - 150 - bob), (126, base - 152 - bob), + (158, base - 112 - bob), (148, base - 40 - bob)] + d.polygon(pts(body), fill=rgba(rock)) + d.polygon(pts([(96, base - 150 - bob), (126, base - 152 - bob), (158, base - 112 - bob), (148, base - 40 - bob), + (100, base - 40 - bob)]), fill=rgba(dark)) + # glowing cracks and core + for crack in ([(70, 70), (80, 92), (74, 110)], [(122, 64), (114, 88), (126, 104)], [(92, 120), (102, 136)]): + d.line(pts([(x, base - 192 + y + 40 - bob) for x, y in crack]), fill=rgba(lava), width=S(4)) + d.ellipse(pts([(78, base - 108 - bob), (118, base - 68 - bob)]), fill=rgba(lava)) + d.ellipse(pts([(88, base - 98 - bob), (108, base - 78 - bob)]), fill=rgba(lighten(lava, 0.6))) + for s in (-1, 1): + ax = 96 + s * 66 + d.rounded_rectangle(pts([(ax - 16, base - 120 - bob + math.sin(ph) * 6 * s), (ax + 16, base - 54 - bob)]), + radius=S(12), fill=rgba(rock)) + for ex in (84, 112): + d.ellipse(pts([(ex - 7, base - 134 - bob), (ex + 7, base - 122 - bob)]), fill=rgba(lighten(lava, 0.5))) + if k == 6: + img = Image.blend(img, Image.new('RGBA', img.size, (255, 255, 255, 0)), 0.0) + out = outline(small(img), (24, 14, 18), 3) + return soft_glow(out, lava, 6, 0.6) + + +def make_actors(): + save(sheet([draw_hero(n) for n in HERO_FRAMES]), 'hero.png') + save(sheet([draw_slime(k) for k in range(4)]), 'enemy_slime.png') + save(sheet([draw_beetle(k) for k in range(4)]), 'enemy_beetle.png') + save(sheet([draw_brute(k) for k in range(4)]), 'enemy_brute.png') + save(sheet([draw_turret(k) for k in range(3)]), 'enemy_turret.png') + save(sheet([draw_frog(k) for k in range(3)]), 'enemy_frog.png') + save(sheet([draw_bat(k) for k in range(4)]), 'enemy_bat.png') + save(sheet([draw_golem(k) for k in range(6)]), 'enemy_golem.png') + + +# --------------------------------------------------------------------- items +GOLD = (255, 204, 64) +GOLD_D = (214, 140, 30) + + +def item(size, fn, line=(50, 34, 30), glow=None): + img = big(*size) + fn(ImageDraw.Draw(img)) + out = outline(small(img), line, 2) + if glow: + out = soft_glow(out, glow, 4, 0.7) + return out + + +def coin_frame(k): + def f(d): + w = 22 * abs(math.cos(k * math.pi / 6)) + 3 + d.ellipse(pts([(32 - w, 14), (32 + w, 50)]), fill=rgba(GOLD_D)) + d.ellipse(pts([(32 - w + 3, 16), (32 + w - 3, 47)]), fill=rgba(GOLD)) + if w > 10: + d.rounded_rectangle(pts([(32 - w * 0.25, 22), (32 + w * 0.25, 40)]), radius=S(2), fill=rgba(GOLD_D)) + d.ellipse(pts([(32 - w * 0.6, 18), (32 - w * 0.2, 26)]), fill=(255, 255, 230, 220)) + return item((64, 64), f, glow=(255, 220, 120)) + + +def gem_frame(k): + def f(d): + c = (90, 210, 255) + d.polygon(pts([(32, 10), (50, 26), (32, 54), (14, 26)]), fill=rgba(darken(c, 0.25))) + d.polygon(pts([(32, 10), (50, 26), (32, 30), (14, 26)]), fill=rgba(c)) + d.polygon(pts([(32, 10), (40, 26), (32, 30), (24, 26)]), fill=rgba(lighten(c, 0.5))) + s = [(20, 18), (44, 20), (36, 40), (26, 34)][k] + d.polygon(pts([(s[0], s[1] - 4), (s[0] + 2, s[1]), (s[0], s[1] + 4), (s[0] - 2, s[1])]), fill=(255, 255, 255, 255)) + return item((64, 64), f, line=(20, 40, 70), glow=(120, 220, 255)) + + +def heart(d, cx, cy, s, c): + d.ellipse(pts([(cx - s, cy - s * 0.8), (cx, cy + s * 0.2)]), fill=rgba(c)) + d.ellipse(pts([(cx, cy - s * 0.8), (cx + s, cy + s * 0.2)]), fill=rgba(c)) + d.polygon(pts([(cx - s * 0.96, cy - s * 0.1), (cx + s * 0.96, cy - s * 0.1), (cx, cy + s)]), fill=rgba(c)) + + +def make_items(): + save(sheet([coin_frame(k) for k in range(6)]), 'item_coin.png') + save(sheet([gem_frame(k) for k in range(4)]), 'item_gem.png') + + def f_heart(d): + heart(d, 32, 32, 18, (255, 84, 110)) + d.ellipse(pts([(20, 22), (28, 30)]), fill=(255, 255, 255, 200)) + save(item((64, 64), f_heart, line=(70, 20, 30), glow=(255, 120, 140)), 'item_heart.png') + + def f_life(d): + d.ellipse(pts([(10, 10), (54, 54)]), fill=rgba(TEAL)) + d.ellipse(pts([(18, 18), (50, 50)]), fill=rgba(SKIN)) + d.ellipse(pts([(26, 28), (32, 38)]), fill=rgba((34, 30, 60))) + d.ellipse(pts([(38, 28), (44, 38)]), fill=rgba((34, 30, 60))) + d.rounded_rectangle(pts([(12, 46), (52, 56)]), radius=S(4), fill=rgba(SCARF)) + save(item((64, 64), f_life, line=HERO_LINE, glow=(140, 255, 200)), 'item_life.png') + + def f_key(d): + d.ellipse(pts([(10, 20), (32, 42)]), fill=rgba(GOLD)) + d.ellipse(pts([(16, 26), (26, 36)]), fill=(0, 0, 0, 0)) + d.rectangle(pts([(30, 28), (56, 34)]), fill=rgba(GOLD)) + d.rectangle(pts([(46, 34), (50, 42)]), fill=rgba(GOLD)) + d.rectangle(pts([(52, 34), (56, 40)]), fill=rgba(GOLD)) + d.line(pts([(32, 29), (54, 29)]), fill=(255, 250, 210, 255), width=S(1.5)) + save(item((64, 64), f_key, glow=(255, 220, 120)), 'item_key.png') + + for k in range(2): + def f_spring(d, k=k): + top = 30 if k == 0 else 44 + d.rounded_rectangle(pts([(10, 54), (54, 62)]), radius=S(3), fill=rgba((90, 90, 110))) + n = 4 + for i in range(n): + y0 = 54 - (54 - top - 6) * i / n + y1 = 54 - (54 - top - 6) * (i + 1) / n + d.line(pts([(18, y0), (46, (y0 + y1) / 2), (18, y1)]), fill=rgba((200, 200, 220)), width=S(3)) + d.rounded_rectangle(pts([(8, top), (56, top + 8)]), radius=S(4), fill=rgba((255, 90, 90))) + d.rounded_rectangle(pts([(10, top), (54, top + 3)]), radius=S(2), fill=rgba((255, 170, 170))) + save(item((64, 64), f_spring), 'item_spring%d.png' % k) + + for k in range(2): + def f_flag(d, k=k): + d.rounded_rectangle(pts([(28, 10), (34, 126)]), radius=S(3), fill=rgba((150, 130, 120))) + d.ellipse(pts([(24, 4), (38, 18)]), fill=rgba(GOLD)) + c = (110, 230, 140) if k else (170, 160, 170) + wave = [(34, 16), (60, 22), (54, 32), (62, 44), (34, 42)] + d.polygon(pts(wave), fill=rgba(c)) + d.ellipse(pts([(18, 118), (44, 128)]), fill=rgba((90, 80, 90))) + save(item((64, 128), f_flag, glow=(140, 255, 170) if k else None), 'item_checkpoint%d.png' % k) + + def f_door(d): + d.rounded_rectangle(pts([(4, 2), (60, 126)]), radius=S(8), fill=rgba((120, 76, 50))) + for x in (16, 32, 48): + d.line(pts([(x, 8), (x, 122)]), fill=rgba((90, 56, 36)), width=S(2)) + for y in (24, 100): + d.rectangle(pts([(4, y), (60, y + 6)]), fill=rgba((80, 80, 96))) + d.ellipse(pts([(24, 54), (40, 70)]), fill=rgba(GOLD)) + d.rectangle(pts([(30, 64), (34, 76)]), fill=rgba((40, 30, 30))) + save(item((64, 128), f_door), 'item_door.png') + + def f_gate(d): + d.rectangle(pts([(2, 2), (62, 14)]), fill=rgba((80, 80, 100))) + for x in (10, 24, 38, 52): + d.rectangle(pts([(x - 3, 12), (x + 3, 186)]), fill=rgba((150, 150, 170))) + d.polygon(pts([(x - 5, 184), (x, 192), (x + 5, 184)]), fill=rgba((150, 150, 170))) + d.line(pts([(x - 1.5, 14), (x - 1.5, 182)]), fill=rgba((220, 220, 236)), width=S(1.5)) + d.rectangle(pts([(2, 90), (62, 98)]), fill=rgba((80, 80, 100))) + save(item((64, 192), f_gate), 'item_gate.png') + + for k in range(2): + def f_lever(d, k=k): + d.rounded_rectangle(pts([(14, 46), (50, 62)]), radius=S(4), fill=rgba((110, 100, 120))) + a = math.radians(-35 if k == 0 else 35) + x1, y1 = 32 + math.sin(a) * 30, 50 - math.cos(a) * 30 + d.line(pts([(32, 50), (x1, y1)]), fill=rgba((90, 70, 60)), width=S(5)) + d.ellipse(pts([(x1 - 7, y1 - 7), (x1 + 7, y1 + 7)]), fill=rgba((255, 90, 90) if k == 0 else (110, 230, 140))) + save(item((64, 64), f_lever), 'item_lever%d.png' % k) + + for k in range(2): + def f_plate(d, k=k): + y = 50 if k == 0 else 56 + d.rounded_rectangle(pts([(6, 58), (58, 64)]), radius=S(2), fill=rgba((80, 80, 96))) + d.rounded_rectangle(pts([(10, y), (54, 60)]), radius=S(3), fill=rgba((230, 190, 80) if k else (190, 170, 120))) + save(item((64, 64), f_plate), 'item_plate%d.png' % k) + + for k in range(3): + def f_crumble(d, k=k): + c = (214, 170, 110) + d.rounded_rectangle(pts([(2, 2), (62, 62)]), radius=S(6), fill=rgba(c)) + d.rounded_rectangle(pts([(2, 2), (62, 12)]), radius=S(4), fill=rgba(lighten(c, 0.3))) + d.line(pts([(2, 32), (62, 32)]), fill=rgba(darken(c, 0.2)), width=S(2)) + d.line(pts([(32, 2), (32, 32)]), fill=rgba(darken(c, 0.2)), width=S(2)) + if k >= 1: + d.line(pts([(12, 8), (24, 26), (18, 44), (30, 58)]), fill=rgba(darken(c, 0.5)), width=S(2.5)) + if k >= 2: + d.line(pts([(50, 6), (40, 24), (52, 40), (44, 58)]), fill=rgba(darken(c, 0.5)), width=S(2.5)) + save(item((64, 64), f_crumble), 'item_crumble%d.png' % k) + + for name, c, sym in (('jetpack', (255, 160, 70), 'jet'), ('glide', (120, 220, 110), 'leaf'), + ('weapon', (130, 200, 255), 'bolt')): + def f_power(d, c=c, sym=sym): + d.ellipse(pts([(6, 6), (58, 58)]), fill=rgba(darken(c, 0.2))) + d.ellipse(pts([(10, 10), (54, 54)]), fill=rgba(c)) + d.ellipse(pts([(16, 14), (30, 24)]), fill=(255, 255, 255, 180)) + if sym == 'jet': + d.rounded_rectangle(pts([(24, 18), (40, 40)]), radius=S(4), fill=(255, 255, 255, 255)) + d.polygon(pts([(26, 40), (38, 40), (32, 50)]), fill=rgba((255, 220, 120))) + elif sym == 'leaf': + d.pieslice(pts([(16, 18), (48, 46)]), 180, 360, fill=(255, 255, 255, 255)) + d.line(pts([(32, 32), (32, 48)]), fill=(255, 255, 255, 255), width=S(3)) + else: + d.polygon(pts([(34, 14), (22, 34), (32, 34), (28, 50), (42, 28), (32, 28)]), fill=(255, 255, 255, 255)) + save(item((64, 64), f_power, glow=c), 'item_power_%s.png' % name) + + goal = [] + for k in range(4): + def f_goal(d, k=k): + d.rounded_rectangle(pts([(8, 20), (88, 160)]), radius=S(40), fill=rgba((90, 70, 140))) + d.rounded_rectangle(pts([(18, 30), (78, 156)]), radius=S(30), fill=rgba((40, 30, 80))) + for i in range(4): + r = 8 + ((i * 7 + k * 3) % 26) + d.ellipse(pts([(48 - r, 92 - r * 1.4), (48 + r, 92 + r * 1.4)]), + outline=rgba(lighten((150, 200, 255), i * 0.15), 200), width=S(2)) + d.ellipse(pts([(40, 2), (56, 18)]), fill=rgba(GOLD)) + goal.append(item((96, 160), f_goal, line=(30, 20, 50), glow=(160, 200, 255))) + save(sheet(goal), 'item_goal.png') + + def f_orb(d): + d.ellipse(pts([(4, 4), (28, 28)]), fill=rgba((255, 110, 70))) + d.ellipse(pts([(9, 9), (19, 19)]), fill=rgba((255, 230, 180))) + save(soft_glow(small(_draw(32, 32, f_orb)), (255, 120, 60), 3, 0.9), 'shot_orb.png') + + def f_bolt(d): + d.rounded_rectangle(pts([(4, 8), (44, 16)]), radius=S(4), fill=rgba((130, 220, 255))) + d.rounded_rectangle(pts([(10, 10), (42, 14)]), radius=S(2), fill=(255, 255, 255, 255)) + save(soft_glow(small(_draw(48, 24, f_bolt)), (120, 200, 255), 3, 0.9), 'shot_bolt.png') + + +def _draw(w, h, fn): + img = big(w, h) + fn(ImageDraw.Draw(img)) + return img + + +# ----------------------------------------------------------------- backdrops +def periodic_noise(width, octaves, rnd): + """A 1-D function that repeats every `width` pixels.""" + terms = [] + for o in range(octaves): + f = 2 ** o + terms.append((f, rnd.uniform(0, math.tau), 1.0 / f)) + + def fn(x): + v = 0 + for f, ph, a in terms: + v += math.sin(x / width * math.tau * f + ph) * a + return v + return fn + + +def ridge_layer(w, h, color, base, amp, octaves, rnd, top_color=None, extras=None): + img = Image.new('RGBA', (w, h), (0, 0, 0, 0)) + d = ImageDraw.Draw(img) + n = periodic_noise(w, octaves, rnd) + poly = [(0, h)] + for x in range(0, w + 1, 4): + poly.append((x, base - n(x) * amp)) + poly.append((w, h)) + d.polygon(poly, fill=rgba(color)) + if top_color: + for x in range(0, w + 1, 4): + y = base - n(x) * amp + d.line([(x, y), (x + 4, base - n(x + 4) * amp)], fill=rgba(top_color), width=4) + if extras: + extras(d, n) + return img + + +def make_backdrops(): + W, H = 1024, 1024 + for theme in THEMES: + rnd = random.Random('bg' + theme) + if theme == 'meadow': + sky = vgrad(W, H, (255, 214, 168), (120, 190, 255)) + sky = Image.composite(vgrad(W, H, (92, 150, 240), (255, 200, 160)), sky, + vgrad(W, H, (255, 255, 255), (0, 0, 0)).convert('L')) + sd = ImageDraw.Draw(sky) + sd.ellipse([700, 300, 860, 460], fill=(255, 240, 200, 255)) + sky = sky.filter(ImageFilter.GaussianBlur(2)) + for _ in range(7): + x, y = rnd.uniform(0, W), rnd.uniform(80, 420) + for k in range(5): + r = rnd.uniform(30, 60) + for dx in (-W, 0, W): + cx = x + k * 40 + dx + sd.ellipse([cx - r, y - r * 0.6, cx + r, y + r * 0.6], fill=(255, 250, 245, 200)) + layers = [sky, + ridge_layer(W, H, (150, 170, 220), 640, 90, 4, rnd, (190, 205, 240)), + ridge_layer(W, H, (96, 160, 120), 760, 60, 4, rnd, (140, 200, 140), + extras=lambda d, n: trees(d, n, 760, 60, W, (70, 130, 100), rnd))] + elif theme == 'cavern': + sky = vgrad(W, H, (24, 22, 54), (40, 52, 92)) + sd = ImageDraw.Draw(sky) + for _ in range(80): + x, y, r = rnd.uniform(0, W), rnd.uniform(0, H), rnd.uniform(1, 3) + sd.ellipse([x - r, y - r, x + r, y + r], fill=(160, 255, 240, int(rnd.uniform(60, 200)))) + stal = Image.new('RGBA', (W, H)) + dd = ImageDraw.Draw(stal) + for i in range(24): + x = i * W / 24 + rnd.uniform(-10, 10) + hgt = rnd.uniform(120, 360) + for dx in (-W, 0, W): + dd.polygon([(x + dx - 26, 0), (x + dx + 26, 0), (x + dx, hgt)], fill=(46, 50, 90, 255)) + layers = [sky, stal, + ridge_layer(W, H, (52, 60, 104), 780, 80, 5, rnd, (90, 210, 200), + extras=lambda d, n: crystals(d, n, 780, 80, W, rnd))] + elif theme == 'foundry': + sky = vgrad(W, H, (64, 30, 40), (210, 110, 70)) + sd = ImageDraw.Draw(sky) + for _ in range(10): + x, y, r = rnd.uniform(0, W), rnd.uniform(100, 600), rnd.uniform(60, 140) + for cx in (x - W, x, x + W): + sd.ellipse([cx - r, y - r * 0.5, cx + r, y + r * 0.5], fill=(120, 80, 90, 90)) + sky = sky.filter(ImageFilter.GaussianBlur(6)) + far = Image.new('RGBA', (W, H)) + fd = ImageDraw.Draw(far) + for i in range(9): + x = i * W / 9 + rnd.uniform(0, 40) + w_ = rnd.uniform(30, 60) + top = rnd.uniform(260, 520) + fd.rectangle([x, top, x + w_, H], fill=(90, 54, 64, 255)) + fd.rectangle([x - 6, top, x + w_ + 6, top + 14], fill=(110, 66, 76, 255)) + fd.rectangle([0, 700, W, H], fill=(90, 54, 64, 255)) + layers = [sky, far, + ridge_layer(W, H, (60, 40, 48), 820, 30, 3, rnd, (255, 140, 70))] + elif theme == 'sky': + sky = vgrad(W, H, (110, 170, 255), (255, 220, 240)) + sd = ImageDraw.Draw(sky) + sd.ellipse([180, 180, 300, 300], fill=(255, 250, 230, 255)) + far = Image.new('RGBA', (W, H)) + fd = ImageDraw.Draw(far) + for _ in range(12): + x, y = rnd.uniform(0, W), rnd.uniform(500, 800) + for k in range(6): + r = rnd.uniform(40, 80) + # Drawn again a layer's width either side, so a cloud + # crossing an edge carries on in the next copy instead + # of ending in a straight cut. + for dx in (-W, 0, W): + cx = x + k * 50 + dx + fd.ellipse([cx - r, y - r * 0.6, cx + r, y + r * 0.6], fill=(255, 255, 255, 170)) + near = ridge_layer(W, H, (250, 246, 255), 860, 40, 5, rnd, (255, 255, 255)) + layers = [sky, far, near] + else: # forge + sky = vgrad(W, H, (30, 12, 20), (120, 30, 20)) + sd = ImageDraw.Draw(sky) + for _ in range(140): + x, y, r = rnd.uniform(0, W), rnd.uniform(0, H), rnd.uniform(1, 3) + sd.ellipse([x - r, y - r, x + r, y + r], fill=(255, 160, 80, int(rnd.uniform(40, 200)))) + layers = [sky, + ridge_layer(W, H, (70, 30, 34), 620, 120, 4, rnd, (200, 70, 40)), + ridge_layer(W, H, (40, 18, 22), 820, 50, 4, rnd, (255, 110, 50))] + for i, img in enumerate(layers): + save(img.convert('RGB') if i == 0 else img, 'bg_%s_%d.png' % (theme, i)) + + +def trees(d, n, base, amp, w, color, rnd): + for i in range(30): + x = (i * w / 30 + rnd.uniform(-8, 8)) % w + y = base - n(x) * amp + 6 + h = rnd.uniform(50, 110) + # Drawn a layer's width either side too, so the row wraps cleanly. + for cx in (x - w, x, x + w): + d.ellipse([cx - h * 0.3, y - h, cx + h * 0.3, y - h * 0.25], fill=rgba(color)) + d.rectangle([cx - 3, y - h * 0.3, cx + 3, y], fill=rgba(darken(color, 0.3))) + + +def crystals(d, n, base, amp, w, rnd): + for i in range(18): + x = (i * w / 18 + rnd.uniform(-10, 10)) % w + y = base - n(x) * amp + 8 + h = rnd.uniform(30, 90) + c = (120, 240, 230) if i % 3 else (232, 140, 255) + for cx in (x - w, x, x + w): + d.polygon([(cx - 10, y), (cx, y - h), (cx + 10, y)], fill=rgba(c, 220)) + d.polygon([(cx - 2, y), (cx, y - h), (cx + 4, y)], fill=rgba(lighten(c, 0.5), 220)) + + +# ------------------------------------------------------------------------ ui +def make_ui(): + # the app icon: the hero's face on a sunrise + icon = vgrad(512 * 2, 512 * 2, (255, 190, 120), (90, 150, 240)) + d = ImageDraw.Draw(icon) + d.ellipse([200, 360, 824, 984], fill=(255, 236, 190, 255)) + d.rectangle([0, 760, 1024, 1024], fill=(98, 186, 84, 255)) + d.rectangle([0, 760, 1024, 790], fill=(170, 230, 120, 255)) + face = draw_hero('cheer').resize((900, 900), Image.LANCZOS) + icon.alpha_composite(face, (62, 40)) + icon = icon.resize((512, 512), Image.LANCZOS) + m = shape(512, 512, lambda dd: dd.rounded_rectangle([0, 0, 512 * SS, 512 * SS], radius=110 * SS, fill=255)) + icon.putalpha(small(m)) + save(icon, 'app_icon.png') + icon.save(os.path.join(HERE, '..', 'common', 'icon.png')) + # a soft spark for particles and a vignette for the play screen + spark = big(32, 32) + ImageDraw.Draw(spark).ellipse(pts([(4, 4), (28, 28)]), fill=(255, 255, 255, 255)) + save(small(spark).filter(ImageFilter.GaussianBlur(2)), 'fx_spark.png') + + +# ----------------------------------------------------------------------- sfx +RATE = 22050 + + +def tone(freqs, dur, kind='square', vol=0.35, attack=0.005, decay=None, slide=None, noise=0.0): + n = int(RATE * dur) + out = [] + ph = 0.0 + rnd = random.Random(int(sum(freqs) * 1000 + dur * 100)) + for i in range(n): + t = i / n + f = freqs[min(len(freqs) - 1, int(t * len(freqs)))] + if slide: + f *= slide ** t + ph += f / RATE + if kind == 'square': + v = 1.0 if (ph % 1.0) < 0.5 else -1.0 + elif kind == 'tri': + v = 4 * abs((ph % 1.0) - 0.5) - 1 + else: + v = math.sin(ph * math.tau) + if noise: + v = v * (1 - noise) + rnd.uniform(-1, 1) * noise + env = min(1.0, i / max(1, attack * RATE)) + env *= (1 - t) ** (decay if decay else 1.5) + out.append(v * env * vol) + return out + + +def write_wav(name, samples): + path = os.path.join(OUT, name) + with wave.open(path, 'wb') as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(RATE) + w.writeframes(b''.join(struct.pack('