Browse Source

Compose Web Example - Compose Bird (#797)

* add new compose web example - compose bird

* bump compose web version and fix breaking changes

* refresh .gitignore with new rules

* update README
pull/807/head
theapache64 3 years ago committed by GitHub
parent
commit
7f90700f8d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 1
      README.md
  2. 15
      examples/compose-bird/.gitignore
  3. 35
      examples/compose-bird/README.md
  4. 28
      examples/compose-bird/build.gradle.kts
  5. BIN
      examples/compose-bird/cover.jpeg
  6. BIN
      examples/compose-bird/demo.gif
  7. 2
      examples/compose-bird/gradle.properties
  8. BIN
      examples/compose-bird/gradle/wrapper/gradle-wrapper.jar
  9. 5
      examples/compose-bird/gradle/wrapper/gradle-wrapper.properties
  10. 185
      examples/compose-bird/gradlew
  11. 89
      examples/compose-bird/gradlew.bat
  12. 8
      examples/compose-bird/settings.gradle.kts
  13. 145
      examples/compose-bird/src/jsMain/kotlin/core/ComposeBirdGame.kt
  14. 10
      examples/compose-bird/src/jsMain/kotlin/core/Game.kt
  15. 9
      examples/compose-bird/src/jsMain/kotlin/data/GameFrame.kt
  16. 6
      examples/compose-bird/src/jsMain/kotlin/data/Tube.kt
  17. 185
      examples/compose-bird/src/jsMain/kotlin/main.kt
  18. 17
      examples/compose-bird/src/jsMain/resources/index.html

1
README.md

@ -19,6 +19,7 @@ at https://android.googlesource.com/platform/frameworks/support.
* [issues](examples/issues) - GitHub issue tracker with an adaptive UI and ktor-client * [issues](examples/issues) - GitHub issue tracker with an adaptive UI and ktor-client
* [game](examples/falling_balls) - Simple game * [game](examples/falling_balls) - Simple game
* [game](examples/falling_balls_with_web) - Simple game for web target * [game](examples/falling_balls_with_web) - Simple game for web target
* [compose-bird](examples/compose-bird) - A flappy bird clone using Compose for Web
* [notepad](examples/notepad) - Notepad, using the new experimental Composable Window API * [notepad](examples/notepad) - Notepad, using the new experimental Composable Window API
* [todoapp](examples/todoapp) - TODO items tracker with persistence and multiple screens * [todoapp](examples/todoapp) - TODO items tracker with persistence and multiple screens
* [widgetsgallery](examples/widgetsgallery) - Gallery of standard widgets * [widgetsgallery](examples/widgetsgallery) - Gallery of standard widgets

15
examples/compose-bird/.gitignore vendored

@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
build/
/captures
.externalNativeBuild
.cxx

35
examples/compose-bird/README.md

@ -0,0 +1,35 @@
# 🐦 Compose Bird
![](demo.gif)
![latestVersion](https://img.shields.io/github/v/release/theapache64/compose-bird)
<a href="https://twitter.com/theapache64" target="_blank">
<img alt="Twitter: theapache64" src="https://img.shields.io/twitter/follow/theapache64.svg?style=social" />
</a>
> A flappy bird clone using Compose Web and radio buttons
## ▶ Play
- https://theapache64.github.io/compose-bird/
## 🏃 Run
```
./gradlew jsBrowserRun
```
## 📦 Distribute
```
./gradlew jsBrowserDistribution // and then open index.html (build/distributions)
```
## ✍ Author
👤 **theapache64**
* Twitter: <a href="https://twitter.com/theapache64" target="_blank">@theapache64</a>
* Email: theapache64@gmail.com
Feel free to ping me 😉

28
examples/compose-bird/build.gradle.kts

@ -0,0 +1,28 @@
// Add compose gradle plugin
plugins {
kotlin("multiplatform") version "1.5.10"
id("org.jetbrains.compose") version "0.5.0-build225"
}
group = "com.theapache64.composebird"
version = "1.0.0-alpha01"
// Add maven repositories
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
kotlin {
js(IR) {
browser()
binaries.executable()
}
sourceSets {
val jsMain by getting {
dependencies {
implementation(compose.web.core)
implementation(compose.runtime)
}
}
}
}

BIN
examples/compose-bird/cover.jpeg

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

BIN
examples/compose-bird/demo.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 MiB

2
examples/compose-bird/gradle.properties

@ -0,0 +1,2 @@
kotlin.code.style=official
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

BIN
examples/compose-bird/gradle/wrapper/gradle-wrapper.jar vendored

Binary file not shown.

5
examples/compose-bird/gradle/wrapper/gradle-wrapper.properties vendored

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
examples/compose-bird/gradlew vendored

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
examples/compose-bird/gradlew.bat vendored

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

8
examples/compose-bird/settings.gradle.kts

@ -0,0 +1,8 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
}
rootProject.name = "compose-bird"

145
examples/compose-bird/src/jsMain/kotlin/core/ComposeBirdGame.kt

@ -0,0 +1,145 @@
package core
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import data.GameFrame
import data.Tube
import kotlin.js.Date
class ComposeBirdGame : Game {
companion object {
const val COLUMNS = 15
const val ROWS = 9
const val BIRD_COLUMN = 1
private const val TUBES_START_FROM = (COLUMNS * 0.75).toInt()
const val TOTAL_TUBES = 10
private const val TUBE_HORIZONTAL_DISTANCE = 3
private const val TUBE_VERTICAL_DISTANCE = 3
private const val TUBE_WEIGHT = 500
private const val BIRD_WEIGHT = 300
}
private val tubeGapRange = TUBE_VERTICAL_DISTANCE until ROWS
private var tubeLastSteppedAt = 0.0
private var birdLastSteppedAt = 0.0
private var shouldMoveBirdUp = false
private val _gameFrame: MutableState<GameFrame> by lazy {
mutableStateOf(
// First frame
GameFrame(
birdPos = ROWS / 2,
tubes = buildLevel(),
isGameOver = false,
isGameWon = false,
score = 0
)
)
}
private fun buildLevel(): List<Tube> {
return mutableListOf<Tube>().apply {
var tubesAdded = 0
var tubePosition = 0
while (tubesAdded < TOTAL_TUBES) {
if (tubePosition > TUBES_START_FROM && tubePosition % TUBE_HORIZONTAL_DISTANCE == 0) { // To give space to each tube
add(
Tube(
tubePosition,
buildRandomTube()
)
)
tubesAdded++
}
tubePosition++
}
}
}
private fun buildRandomTube(): List<Boolean> {
// creating a full tube
val tube = mutableListOf<Boolean>().apply {
repeat(ROWS) {
add(true)
}
}
// Adding gaps in random middle positions to make it two tubes.
val gap1 = tubeGapRange.random()
repeat(TUBE_VERTICAL_DISTANCE) { index ->
tube[gap1 - index] = false
}
return tube
}
override val gameFrame: State<GameFrame> = _gameFrame
override fun step() {
update {
val now = Date().getTime()
// Stepping tube
val tubeDiff = now - tubeLastSteppedAt
val newTubes = if (tubeDiff > TUBE_WEIGHT) {
tubeLastSteppedAt = now
tubes.map {
it.copy(position = it.position - 1)
}
} else {
tubes
}
// Stepping bird position
val birdDiff = now - birdLastSteppedAt
val newBirdPos = when {
shouldMoveBirdUp -> {
birdLastSteppedAt = now
shouldMoveBirdUp = false
birdPos - 1 // move up
}
birdDiff > BIRD_WEIGHT -> {
birdLastSteppedAt = now
birdPos + 1 // move down
}
else -> {
birdPos
}
}
val newScore = newTubes.filter { it.position < BIRD_COLUMN }.size // All passed tube
val newIsGameWon = newScore >= TOTAL_TUBES // If all tubes passed
// Checking if bird gone out
val newIsGameOver = if (newBirdPos < 0 || newBirdPos >= ROWS || isCollidedWithTube(newBirdPos, tubes)) {
true
} else {
isGameOver
}
copy(
isGameOver = newIsGameOver,
tubes = newTubes,
birdPos = newBirdPos,
score = newScore,
isGameWon = newIsGameWon
)
}
}
private fun isCollidedWithTube(newBirdPos: Int, tubes: List<Tube>): Boolean {
val birdTube = tubes.find { it.position == BIRD_COLUMN }
return birdTube?.coordinates?.get(newBirdPos) ?: false
}
override fun moveBirdUp() {
shouldMoveBirdUp = true
}
private inline fun update(func: GameFrame.() -> GameFrame) {
_gameFrame.value = _gameFrame.value.func()
}
}

10
examples/compose-bird/src/jsMain/kotlin/core/Game.kt

@ -0,0 +1,10 @@
package core
import androidx.compose.runtime.State
import data.GameFrame
interface Game {
val gameFrame: State<GameFrame>
fun step()
fun moveBirdUp()
}

9
examples/compose-bird/src/jsMain/kotlin/data/GameFrame.kt

@ -0,0 +1,9 @@
package data
data class GameFrame(
val birdPos: Int,
val tubes: List<Tube>,
val isGameOver: Boolean,
val isGameWon : Boolean,
val score: Int,
)

6
examples/compose-bird/src/jsMain/kotlin/data/Tube.kt

@ -0,0 +1,6 @@
package data
data class Tube(
var position: Int,
val coordinates: List<Boolean>
)

185
examples/compose-bird/src/jsMain/kotlin/main.kt

@ -0,0 +1,185 @@
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import core.ComposeBirdGame
import core.Game
import data.GameFrame
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.coroutines.delay
import org.jetbrains.compose.web.attributes.*
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import org.jetbrains.compose.web.renderComposable
import org.w3c.dom.HTMLElement
import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.get
fun main() {
val game: Game = ComposeBirdGame()
val body = document.getElementsByTagName("body")[0] as HTMLElement
// Enabling keyboard control
body.addEventListener("keyup", {
when ((it as KeyboardEvent).keyCode) {
38 -> { // Arrow up
game.moveBirdUp()
}
}
})
body.onclick = {
game.moveBirdUp()
}
renderComposable(rootElementId = "root") {
Div(
attrs = {
style {
display(DisplayStyle.Flex)
justifyContent(JustifyContent.Center)
}
onClick {
game.moveBirdUp()
}
}
) {
// The current frame!
val gameFrame by game.gameFrame
// Igniting the game loop
LaunchedEffect(Unit) {
while (!gameFrame.isGameOver) {
delay(60)
game.step()
}
}
Div {
// Title
GameTitle()
Score(gameFrame)
Br()
if (gameFrame.isGameOver || gameFrame.isGameWon) {
Div(
attrs = {
style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Column)
justifyContent(JustifyContent.Center)
}
}
) {
GameStatus(gameFrame)
TryAgain()
}
} else {
repeat(ComposeBirdGame.ROWS) { rowIndex ->
Div {
repeat(ComposeBirdGame.COLUMNS) { columnIndex ->
Input(
InputType.Radio,
attrs = {
style {
width(25.px)
height(25.px)
}
val tube = gameFrame.tubes.find { it.position == columnIndex }
val isTube = tube?.coordinates?.get(rowIndex) ?: false
val isBird =
!isTube && columnIndex == ComposeBirdGame.BIRD_COLUMN && rowIndex == gameFrame.birdPos
if (isTube || isBird) {
// if it's either a tube node or bird, check it
checked()
}
if (!isBird) {
// if it's a bird, enable it. (to change to blue color)
disabled()
}
}
)
}
}
}
}
}
}
}
}
@Composable
private fun TryAgain() {
Button(
attrs = {
onClick {
window.location.reload()
}
}
) {
Text("Try Again!")
}
}
@Composable
private fun GameStatus(gameFrame: GameFrame) {
H2(
attrs = {
style {
alignSelf(AlignSelf.Center)
}
}
) {
if (gameFrame.isGameWon) {
Text("🚀 Won the game! 🚀")
} else {
// core.Game over
Text("💀 Game Over 💀")
}
}
}
@Composable
private fun Score(gameFrame: GameFrame) {
Div(
attrs = {
style {
display(DisplayStyle.Flex)
justifyContent(JustifyContent.Center)
}
}
) {
Text("Your Score: ${gameFrame.score} || Top Score: ${ComposeBirdGame.TOTAL_TUBES}")
}
}
@Composable
private fun GameTitle() {
H1(
attrs = {
style {
display(DisplayStyle.Flex)
justifyContent(JustifyContent.Center)
}
}
) {
Text("🐦 Compose Bird!")
}
}

17
examples/compose-bird/src/jsMain/resources/index.html

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>compose-bird</title>
<style>
input[type=radio]{
width:25px;
height:25px;
}
</style>
</head>
<body>
<div id="root"></div>
<script src="compose-bird.js"></script>
</body>
</html>
Loading…
Cancel
Save