games-logicgate: ktlint rollout — format module and fix residue
- Commit
e22742f58a318e05b8f5127d10510c24b335de92- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 19:47 UTC (4 days ago)
- Parents
8b6c68a
Ran ./format games/logicgate over the whole module: 2,573 violations in 94 files at census (main 1,606, test 879, screenshotTest 79, androidTest 9) are down to zero, verified by ktlintCheck on every source set. Manual fixes for the three non-autocorrectable residues, all standard:max-line-length: - Split the on/completed ternary colour expressions in BusValueDialog and ProgressionScreen into multiline if/else expressions; the colours chosen are unchanged. - GatePainterW6Test: imported NodeId and used the short name in fixture() instead of the fully-qualified name in its return type. No ktlint rule was disabled, no detekt or lint config was touched, and no baseline was added. Expansion surfaced no new detekt findings. Verified: ./gradlew :games:logicgate:detekt :games:logicgate:lint :games:logicgate:ktlintCheck :games:logicgate:compileDevKotlin green; :games:logicgate:testDevUnitTest green (122 tests, 0 failures).
Diff
games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/FullE2eTest.kt
diff --git a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/FullE2eTest.kt b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/FullE2eTest.ktindex 61678d2a31..071c313832 100644--- a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/FullE2eTest.kt+++ b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/FullE2eTest.kt@@ -8,12 +8,12 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until-import java.io.IOException import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith+import java.io.IOException /** * Full e2e test: launches the app, grants every requested permission, and asserts it@@ -24,7 +24,6 @@ import org.junit.runner.RunWith */ @RunWith(AndroidJUnit4::class) class FullE2eTest {- @Test fun launch_grantsPermissions_showsLevelMap() { val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -55,11 +54,12 @@ class FullE2eTest { packageManager: PackageManager, packageName: String, ) {- val info = try {- packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)- } catch (e: PackageManager.NameNotFoundException) {- throw AssertionError("package $packageName not installed", e)- }+ val info =+ try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ } for (permission in info.requestedPermissions.orEmpty()) { try { uiAutomation.executeShellCommand("pm grant $packageName $permission").close()
games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt
diff --git a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.ktindex 3774113c15..06a219ff22 100644--- a/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt+++ b/games/logicgate/src/androidTest/java/com/vayunmathur/games/logicgate/ui/GamePlayTest.kt@@ -6,11 +6,11 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until-import java.util.regex.Pattern import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Test import org.junit.runner.RunWith+import java.util.regex.Pattern /** * Journey test: open the first level from the map, tap NAND in the chip tray, see the circuit@@ -22,7 +22,6 @@ import org.junit.runner.RunWith */ @RunWith(AndroidJUnit4::class) class GamePlayTest {- @Test fun play_openNot_placeNand_undoRemovesIt() { val instrumentation = InstrumentationRegistry.getInstrumentation()
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.ktindex 3054ad157f..bea069c052 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt@@ -34,10 +34,11 @@ fun Navigation(viewModel: LogicViewModel) { val catalog by viewModel.catalog.collectAsState() val names = remember(catalog) { catalog.customs.associate { it.id to it.name } } GameHubComposeHook("logicgate", viewModel.achievementsManager)- val pages: List<BottomBarItem<out Route>> = listOf(- BottomBarItem(stringResource(R.string.lg_tab_computer), Route.Progression) { IconMemory() },- BottomBarItem(stringResource(R.string.lg_tab_sandbox), Route.Sandbox) { IconScience() },- )+ val pages: List<BottomBarItem<out Route>> =+ listOf(+ BottomBarItem(stringResource(R.string.lg_tab_computer), Route.Progression) { IconMemory() },+ BottomBarItem(stringResource(R.string.lg_tab_sandbox), Route.Sandbox) { IconScience() },+ ) CompositionLocalProvider(LocalChipNames provides names) { Box(modifier = Modifier.fillMaxSize()) { MainNavigation(
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.ktindex 4ea2bfe76f..13956fc098 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt@@ -10,13 +10,17 @@ sealed interface Route : NavKey { @Serializable data object Progression : Route /** The circuit editor for one level. */- @Serializable data class Game(val levelId: String) : Route+ @Serializable data class Game(+ val levelId: String,+ ) : Route /** The player's components (Sandbox tab). */ @Serializable data object Sandbox : Route /** The editor for one sandbox component. */- @Serializable data class Component(val componentId: String) : Route+ @Serializable data class Component(+ val componentId: String,+ ) : Route /** Achievements. */ @Serializable data object GameCenter : Route
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.ktindex a84c2ab68c..e66f84767d 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt@@ -22,10 +22,10 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext-import kotlin.coroutines.coroutineContext-import kotlinx.serialization.SerializationException import kotlinx.serialization.Serializable+import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json+import kotlin.coroutines.coroutineContext /** Saved node. [kind] is `gate`, `in` or `out`. */ @Serializable@@ -40,15 +40,26 @@ data class NodeDto( /** Saved pin reference. */ @Serializable-data class PinDto(val node: Int, val out: Boolean, val index: Int)+data class PinDto(+ val node: Int,+ val out: Boolean,+ val index: Int,+) /** Saved wire. */ @Serializable-data class WireDto(val from: PinDto, val to: PinDto)+data class WireDto(+ val from: PinDto,+ val to: PinDto,+) /** Saved circuit draft. */ @Serializable-data class CircuitDto(val nodes: List<NodeDto>, val wires: List<WireDto>, val nextId: Int)+data class CircuitDto(+ val nodes: List<NodeDto>,+ val wires: List<WireDto>,+ val nextId: Int,+) /** * Per-level circuit drafts, as one JSON map in the shared DataStore. Saves are debounced on the@@ -60,7 +71,10 @@ data class CircuitDto(val nodes: List<NodeDto>, val wires: List<WireDto>, val ne * [rewriteAll] must transform unsaved drafts too, so a debounced save can never overwrite a * rewrite with a stale circuit. */-class CircuitStore(context: Context, dispatcher: CoroutineDispatcher) {+class CircuitStore(+ context: Context,+ dispatcher: CoroutineDispatcher,+) { private val ds = DataStoreUtils.getInstance(context) private val scope = CoroutineScope(SupervisorJob() + dispatcher) private val json = Json { ignoreUnknownKeys = true }@@ -72,13 +86,17 @@ class CircuitStore(context: Context, dispatcher: CoroutineDispatcher) { synchronized(lock) { latest[levelId] }?.toDomain() ?: decode(ds.getStringAwait(KEY))[levelId]?.toDomain() - fun save(levelId: String, circuit: Circuit) {+ fun save(+ levelId: String,+ circuit: Circuit,+ ) { synchronized(lock) { latest[levelId] = circuit.toDto() } flush?.cancel()- flush = scope.launch {- delay(SAVE_DEBOUNCE_MS)- writePending()- }+ flush =+ scope.launch {+ delay(SAVE_DEBOUNCE_MS)+ writePending()+ } } /** Applies [transform] to every saved draft, e.g. to follow a component whose pins moved. */@@ -93,9 +111,10 @@ class CircuitStore(context: Context, dispatcher: CoroutineDispatcher) { } catch (_: CancellationException) { coroutineContext.ensureActive() }- val snapshot: Map<String, CircuitDto> = synchronized(lock) {- latest.toMap().also { latest.clear() }- }+ val snapshot: Map<String, CircuitDto> =+ synchronized(lock) {+ latest.toMap().also { latest.clear() }+ } ds.updateString(KEY) { old -> val merged = decode(old) + snapshot json.encodeToString(merged.mapValues { (_, dto) -> transform(dto.toDomain()).toDto() })@@ -103,10 +122,11 @@ class CircuitStore(context: Context, dispatcher: CoroutineDispatcher) { } private suspend fun writePending() {- val snapshot: Map<String, CircuitDto> = synchronized(lock) {- if (latest.isEmpty()) return- latest.toMap().also { latest.clear() }- }+ val snapshot: Map<String, CircuitDto> =+ synchronized(lock) {+ if (latest.isEmpty()) return+ latest.toMap().also { latest.clear() }+ } // Past this point the snapshot lives only in this job: a cancel must not drop it. withContext(NonCancellable) { ds.updateString(KEY) { old -> json.encodeToString(decode(old) + snapshot) }@@ -132,11 +152,12 @@ private fun PinRef.toDto() = PinDto(node.raw, side == PinSide.OUT, index) private fun PinDto.toDomain() = PinRef(NodeId(node), if (out) PinSide.OUT else PinSide.IN, index) -private fun Node.toDto(): NodeDto = when (this) {- is Gate -> NodeDto(id.raw, "gate", chip = chipId, x = pos.x, y = pos.y)- is LevelInput -> NodeDto(id.raw, "in", index = index, x = pos.x, y = pos.y)- is LevelOutput -> NodeDto(id.raw, "out", index = index, x = pos.x, y = pos.y)-}+private fun Node.toDto(): NodeDto =+ when (this) {+ is Gate -> NodeDto(id.raw, "gate", chip = chipId, x = pos.x, y = pos.y)+ is LevelInput -> NodeDto(id.raw, "in", index = index, x = pos.x, y = pos.y)+ is LevelOutput -> NodeDto(id.raw, "out", index = index, x = pos.x, y = pos.y)+ } private fun NodeDto.toDomain(): Node? { val p = Point(x, y)@@ -148,14 +169,16 @@ private fun NodeDto.toDomain(): Node? { } } -internal fun Circuit.toDto() = CircuitDto(- nodes = nodes.map { it.toDto() },- wires = wires.map { WireDto(it.from.toDto(), it.to.toDto()) },- nextId = nextId,-)--internal fun CircuitDto.toDomain() = Circuit(- nodes = nodes.mapNotNull { it.toDomain() },- wires = wires.map { Wire(it.from.toDomain(), it.to.toDomain()) },- nextId = nextId,-)+internal fun Circuit.toDto() =+ CircuitDto(+ nodes = nodes.map { it.toDto() },+ wires = wires.map { WireDto(it.from.toDto(), it.to.toDto()) },+ nextId = nextId,+ )++internal fun CircuitDto.toDomain() =+ Circuit(+ nodes = nodes.mapNotNull { it.toDomain() },+ wires = wires.map { Wire(it.from.toDomain(), it.to.toDomain()) },+ nextId = nextId,+ )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.ktindex 56726f3b5c..68d5f2cbd6 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.kt@@ -12,13 +12,16 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch-import kotlinx.serialization.SerializationException import kotlinx.serialization.Serializable+import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json /** Saved pin of a component's board. */ @Serializable-data class PinSpecDto(val name: String, val width: Int)+data class PinSpecDto(+ val name: String,+ val width: Int,+) /** Saved sandbox component. */ @Serializable@@ -35,7 +38,10 @@ data class ComponentDto( * The player's sandbox components, as one JSON list in the shared DataStore. Like [CircuitStore], * saves are debounced on the store's own scope so the last edit lands after the screen closes. */-class ComponentStore(context: Context, dispatcher: CoroutineDispatcher) {+class ComponentStore(+ context: Context,+ dispatcher: CoroutineDispatcher,+) { private val ds = DataStoreUtils.getInstance(context) private val scope = CoroutineScope(SupervisorJob() + dispatcher) private val json = Json { ignoreUnknownKeys = true }@@ -45,11 +51,12 @@ class ComponentStore(context: Context, dispatcher: CoroutineDispatcher) { fun save(components: List<CustomChip>) { pending?.cancel()- pending = scope.launch {- delay(SAVE_DEBOUNCE_MS)- val dto = components.map { it.toDto() }- ds.updateString(KEY) { json.encodeToString(dto) }- }+ pending =+ scope.launch {+ delay(SAVE_DEBOUNCE_MS)+ val dto = components.map { it.toDto() }+ ds.updateString(KEY) { json.encodeToString(dto) }+ } } private fun decode(raw: String?): List<ComponentDto> {@@ -75,18 +82,20 @@ private fun PinSpecDto.toDomain() = Pin(name, if (width in VALID_WIDTHS) width e private val VALID_WIDTHS = setOf(1, 4, 8) -private fun CustomChip.toDto() = ComponentDto(- id = id,- name = name,- group = group,- inputs = board.io.inputs.map { it.toDto() },- outputs = board.io.outputs.map { it.toDto() },- circuit = board.circuit.toDto(),-)+private fun CustomChip.toDto() =+ ComponentDto(+ id = id,+ name = name,+ group = group,+ inputs = board.io.inputs.map { it.toDto() },+ outputs = board.io.outputs.map { it.toDto() },+ circuit = board.circuit.toDto(),+ ) -private fun ComponentDto.toDomain() = CustomChip(- id = id,- name = name,- group = group,- board = Board(circuit.toDomain(), LevelIo(inputs.map { it.toDomain() }, outputs.map { it.toDomain() })),-)+private fun ComponentDto.toDomain() =+ CustomChip(+ id = id,+ name = name,+ group = group,+ board = Board(circuit.toDomain(), LevelIo(inputs.map { it.toDomain() }, outputs.map { it.toDomain() })),+ )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.ktindex c8ecacd437..50259ec0ce 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ProgressStore.kt@@ -8,13 +8,18 @@ import com.vayunmathur.library.util.LevelStatsRepository * Which levels are solved and at what best NAND cost (lower wins), plus which level briefs the * player has already seen. A level is complete exactly when it has a best cost. */-class ProgressStore(context: Context) {+class ProgressStore(+ context: Context,+) { private val stats = LevelStatsRepository(context, PREFS_NAME) private val ds = DataStoreUtils.getInstance(context) fun bestCosts(): Map<String, Int> = stats.getLevelStats().mapValues { it.value.bestScore } - fun record(levelId: String, cost: Int) = stats.updateBestScore(levelId, cost)+ fun record(+ levelId: String,+ cost: Int,+ ) = stats.updateBestScore(levelId, cost) /** Marks the brief for [levelId] seen; true when this is the first visit. */ suspend fun markBriefSeen(levelId: String): Boolean = ds.addStringToSetIfAbsent(BRIEFS_KEY, levelId)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.ktindex 1d83829fd9..88c4a0cdd1 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ArithmeticLevels.kt@@ -3,77 +3,94 @@ package com.vayunmathur.games.logicgate.domain.levels import com.vayunmathur.games.logicgate.R import com.vayunmathur.games.logicgate.domain.model.Chips -internal val arithmeticLevels: List<LevelDef> = listOf(- chipLevel(- Chapter.ARITHMETIC, "half_adder", Chips.HALF,- LevelText(- R.string.lg_level_half_adder_title,- R.string.lg_level_half_adder_brief,- R.string.lg_level_half_adder_hint,+internal val arithmeticLevels: List<LevelDef> =+ listOf(+ chipLevel(+ Chapter.ARITHMETIC,+ "half_adder",+ Chips.HALF,+ LevelText(+ R.string.lg_level_half_adder_title,+ R.string.lg_level_half_adder_brief,+ R.string.lg_level_half_adder_hint,+ ),+ title = RowTitles.half, ),- title = RowTitles.half,- ),- chipLevel(- Chapter.ARITHMETIC, "full_adder", Chips.FULL,- LevelText(- R.string.lg_level_full_adder_title,- R.string.lg_level_full_adder_brief,- R.string.lg_level_full_adder_hint,+ chipLevel(+ Chapter.ARITHMETIC,+ "full_adder",+ Chips.FULL,+ LevelText(+ R.string.lg_level_full_adder_title,+ R.string.lg_level_full_adder_brief,+ R.string.lg_level_full_adder_hint,+ ),+ title = RowTitles.full, ),- title = RowTitles.full,- ),- chipLevel(- Chapter.ARITHMETIC, "add4", Chips.ADD4,- LevelText(- R.string.lg_level_add4_title,- R.string.lg_level_add4_brief,- R.string.lg_level_add4_hint,+ chipLevel(+ Chapter.ARITHMETIC,+ "add4",+ Chips.ADD4,+ LevelText(+ R.string.lg_level_add4_title,+ R.string.lg_level_add4_brief,+ R.string.lg_level_add4_hint,+ ),+ title = RowTitles.add, ),- title = RowTitles.add,- ),- chipLevel(- Chapter.ARITHMETIC, "add8", Chips.ADD8,- LevelText(- R.string.lg_level_add8_title,- R.string.lg_level_add8_brief,- R.string.lg_level_add8_hint,+ chipLevel(+ Chapter.ARITHMETIC,+ "add8",+ Chips.ADD8,+ LevelText(+ R.string.lg_level_add8_title,+ R.string.lg_level_add8_brief,+ R.string.lg_level_add8_hint,+ ),+ title = RowTitles.add, ),- title = RowTitles.add,- ),- chipLevel(- Chapter.ARITHMETIC, "inc4", Chips.INC4,- LevelText(- R.string.lg_level_inc4_title,- R.string.lg_level_inc4_brief,- R.string.lg_level_inc4_hint,+ chipLevel(+ Chapter.ARITHMETIC,+ "inc4",+ Chips.INC4,+ LevelText(+ R.string.lg_level_inc4_title,+ R.string.lg_level_inc4_brief,+ R.string.lg_level_inc4_hint,+ ),+ title = RowTitles.inc, ),- title = RowTitles.inc,- ),- chipLevel(- Chapter.ARITHMETIC, "sub8", Chips.SUB8,- LevelText(- R.string.lg_level_sub8_title,- R.string.lg_level_sub8_brief,- R.string.lg_level_sub8_hint,+ chipLevel(+ Chapter.ARITHMETIC,+ "sub8",+ Chips.SUB8,+ LevelText(+ R.string.lg_level_sub8_title,+ R.string.lg_level_sub8_brief,+ R.string.lg_level_sub8_hint,+ ),+ title = RowTitles.sub, ),- title = RowTitles.sub,- ),- chipLevel(- Chapter.ARITHMETIC, "zero8", Chips.ZERO8,- LevelText(- R.string.lg_level_zero8_title,- R.string.lg_level_zero8_brief,- R.string.lg_level_zero8_hint,+ chipLevel(+ Chapter.ARITHMETIC,+ "zero8",+ Chips.ZERO8,+ LevelText(+ R.string.lg_level_zero8_title,+ R.string.lg_level_zero8_brief,+ R.string.lg_level_zero8_hint,+ ),+ title = RowTitles.zero, ),- title = RowTitles.zero,- ),- chipLevel(- Chapter.ARITHMETIC, "alu8", Chips.ALU8,- LevelText(- R.string.lg_level_alu8_title,- R.string.lg_level_alu8_brief,- R.string.lg_level_alu8_hint,+ chipLevel(+ Chapter.ARITHMETIC,+ "alu8",+ Chips.ALU8,+ LevelText(+ R.string.lg_level_alu8_title,+ R.string.lg_level_alu8_brief,+ R.string.lg_level_alu8_hint,+ ),+ title = RowTitles.alu, ),- title = RowTitles.alu,- ),-)+ )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.ktindex 39fa405162..68b1665364 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/BasicsLevels.kt@@ -3,59 +3,72 @@ package com.vayunmathur.games.logicgate.domain.levels import com.vayunmathur.games.logicgate.R import com.vayunmathur.games.logicgate.domain.model.Chips -internal val basicsLevels: List<LevelDef> = listOf(- chipLevel(- Chapter.BASICS, "not", Chips.NOT,- LevelText(- R.string.lg_level_not_title,- R.string.lg_level_not_brief,- R.string.lg_level_not_hint,+internal val basicsLevels: List<LevelDef> =+ listOf(+ chipLevel(+ Chapter.BASICS,+ "not",+ Chips.NOT,+ LevelText(+ R.string.lg_level_not_title,+ R.string.lg_level_not_brief,+ R.string.lg_level_not_hint,+ ),+ title = RowTitles.not, ),- title = RowTitles.not,- ),- chipLevel(- Chapter.BASICS, "and", Chips.AND,- LevelText(- R.string.lg_level_and_title,- R.string.lg_level_and_brief,- R.string.lg_level_and_hint,+ chipLevel(+ Chapter.BASICS,+ "and",+ Chips.AND,+ LevelText(+ R.string.lg_level_and_title,+ R.string.lg_level_and_brief,+ R.string.lg_level_and_hint,+ ),+ title = RowTitles.infix("AND"), ),- title = RowTitles.infix("AND"),- ),- chipLevel(- Chapter.BASICS, "or", Chips.OR,- LevelText(- R.string.lg_level_or_title,- R.string.lg_level_or_brief,- R.string.lg_level_or_hint,+ chipLevel(+ Chapter.BASICS,+ "or",+ Chips.OR,+ LevelText(+ R.string.lg_level_or_title,+ R.string.lg_level_or_brief,+ R.string.lg_level_or_hint,+ ),+ title = RowTitles.infix("OR"), ),- title = RowTitles.infix("OR"),- ),- chipLevel(- Chapter.BASICS, "nor", Chips.NOR,- LevelText(- R.string.lg_level_nor_title,- R.string.lg_level_nor_brief,- R.string.lg_level_nor_hint,+ chipLevel(+ Chapter.BASICS,+ "nor",+ Chips.NOR,+ LevelText(+ R.string.lg_level_nor_title,+ R.string.lg_level_nor_brief,+ R.string.lg_level_nor_hint,+ ),+ title = RowTitles.infix("NOR"), ),- title = RowTitles.infix("NOR"),- ),- chipLevel(- Chapter.BASICS, "xor", Chips.XOR,- LevelText(- R.string.lg_level_xor_title,- R.string.lg_level_xor_brief,- R.string.lg_level_xor_hint,+ chipLevel(+ Chapter.BASICS,+ "xor",+ Chips.XOR,+ LevelText(+ R.string.lg_level_xor_title,+ R.string.lg_level_xor_brief,+ R.string.lg_level_xor_hint,+ ),+ title = RowTitles.infix("XOR"), ),- title = RowTitles.infix("XOR"),- ),- chipLevel(- Chapter.BASICS, "xnor", Chips.XNOR,- LevelText(- R.string.lg_level_xnor_title,- R.string.lg_level_xnor_brief,- R.string.lg_level_xnor_hint,+ chipLevel(+ Chapter.BASICS,+ "xnor",+ Chips.XNOR,+ LevelText(+ R.string.lg_level_xnor_title,+ R.string.lg_level_xnor_brief,+ R.string.lg_level_xnor_hint,+ ),+ title = RowTitles.infix("XNOR"), ),- title = RowTitles.infix("XNOR"),- ),-)+ )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.ktindex e01a239e06..e3bd4d0a0e 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.kt@@ -11,45 +11,61 @@ sealed interface TrayGroup { data object Pins : TrayGroup /** Built-in chips first earned or gifted in [chapter]. */- data class Builtin(val chapter: Chapter) : TrayGroup+ data class Builtin(+ val chapter: Chapter,+ ) : TrayGroup /** Player-built chips the player filed under [name]. */- data class Custom(val name: String) : TrayGroup+ data class Custom(+ val name: String,+ ) : TrayGroup } /** One tray tab and its chips, in tray order. */-data class TraySection(val group: TrayGroup, val chips: List<ChipSpec>)+data class TraySection(+ val group: TrayGroup,+ val chips: List<ChipSpec>,+) /** Sorts chips into tray tabs: pins, then built-ins by chapter, then the player's groups A-Z. */ object ChipGroups {- private val chapterOf: Map<String, Chapter> = buildMap {- for (id in Chips.base) put(id, Chapter.BASICS)- for (level in LevelRegistry.levels) {- for (id in level.gifts + level.unlocks) putIfAbsent(id, level.chapter)+ private val chapterOf: Map<String, Chapter> =+ buildMap {+ for (id in Chips.base) put(id, Chapter.BASICS)+ for (level in LevelRegistry.levels) {+ for (id in level.gifts + level.unlocks) putIfAbsent(id, level.chapter)+ } }- } fun chapterOf(chipId: String): Chapter = chapterOf[chipId] ?: Chapter.BASICS - fun groupOf(chipId: String, catalog: ChipCatalog): TrayGroup = when {- PinChips.isPin(chipId) -> TrayGroup.Pins- else -> catalog.custom(chipId)?.let { TrayGroup.Custom(it.group) } ?: TrayGroup.Builtin(chapterOf(chipId))- }+ fun groupOf(+ chipId: String,+ catalog: ChipCatalog,+ ): TrayGroup =+ when {+ PinChips.isPin(chipId) -> TrayGroup.Pins+ else -> catalog.custom(chipId)?.let { TrayGroup.Custom(it.group) } ?: TrayGroup.Builtin(chapterOf(chipId))+ } - fun sections(chips: List<ChipSpec>, catalog: ChipCatalog): List<TraySection> {+ fun sections(+ chips: List<ChipSpec>,+ catalog: ChipCatalog,+ ): List<TraySection> { val grouped = chips.groupBy { groupOf(it.id, catalog) } return grouped.keys.sortedWith(ORDER).map { TraySection(it, grouped.getValue(it)) } } - private val ORDER = compareBy<TrayGroup>(- {- when (it) {- TrayGroup.Pins -> 0- is TrayGroup.Builtin -> 1- is TrayGroup.Custom -> 2- }- },- { (it as? TrayGroup.Builtin)?.chapter?.ordinal ?: 0 },- { (it as? TrayGroup.Custom)?.name?.lowercase().orEmpty() },- )+ private val ORDER =+ compareBy<TrayGroup>(+ {+ when (it) {+ TrayGroup.Pins -> 0+ is TrayGroup.Builtin -> 1+ is TrayGroup.Custom -> 2+ }+ },+ { (it as? TrayGroup.Builtin)?.chapter?.ordinal ?: 0 },+ { (it as? TrayGroup.Custom)?.name?.lowercase().orEmpty() },+ ) }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.ktindex 4d9a0e9eb7..62443bd9b2 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipLevel.kt@@ -29,4 +29,8 @@ internal fun chipLevel( } /** The words of a level. */-internal data class LevelText(@StringRes val title: Int, @StringRes val brief: Int, @StringRes val hint: Int)+internal data class LevelText(+ @StringRes val title: Int,+ @StringRes val brief: Int,+ @StringRes val hint: Int,+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.ktindex c9e524d2fe..44c17b0cb9 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/CpuLevels.kt@@ -9,73 +9,107 @@ import com.vayunmathur.games.logicgate.domain.sim.Case import com.vayunmathur.games.logicgate.domain.sim.ProgramTest import com.vayunmathur.games.logicgate.domain.sim.TestSpec -private fun program(name: String, maxTicks: Int, expectAcc: Int, vararg cells: Pair<Int, Int>): ProgramTest {+private fun program(+ name: String,+ maxTicks: Int,+ expectAcc: Int,+ vararg cells: Pair<Int, Int>,+): ProgramTest { val ram = MutableList(16) { 0 } for ((addr, value) in cells) ram[addr] = value return ProgramTest(name, ram, maxTicks, expectAcc) } /** Add two numbers, count down to zero with JZ, and multiply 3 × 4 by repeated addition. */-internal val cpuPrograms: List<ProgramTest> = listOf(- program(- "2 + 3 = 5", 16, 5,- 0 to encode(Isa.LDA, 14), 1 to encode(Isa.ADD, 15), 2 to encode(Isa.HLT),- 14 to 2, 15 to 3,- ),- program(- "count 5 down to 0", 64, 0,- 0 to encode(Isa.LDI, 5), 1 to encode(Isa.SUB, 15), 2 to encode(Isa.JZ, 4), 3 to encode(Isa.JMP, 1),- 4 to encode(Isa.HLT),- 15 to 1,- ),- program(- "3 × 4 = 12", 128, 12,- 0 to encode(Isa.LDA, 13), 1 to encode(Isa.ADD, 14), 2 to encode(Isa.STA, 13),- 3 to encode(Isa.LDA, 12), 4 to encode(Isa.SUB, 15), 5 to encode(Isa.STA, 12),- 6 to encode(Isa.JZ, 8), 7 to encode(Isa.JMP, 0), 8 to encode(Isa.LDA, 13), 9 to encode(Isa.HLT),- 12 to 4, 13 to 0, 14 to 3, 15 to 1,- ),-)+internal val cpuPrograms: List<ProgramTest> =+ listOf(+ program(+ "2 + 3 = 5",+ 16,+ 5,+ 0 to encode(Isa.LDA, 14),+ 1 to encode(Isa.ADD, 15),+ 2 to encode(Isa.HLT),+ 14 to 2,+ 15 to 3,+ ),+ program(+ "count 5 down to 0",+ 64,+ 0,+ 0 to encode(Isa.LDI, 5),+ 1 to encode(Isa.SUB, 15),+ 2 to encode(Isa.JZ, 4),+ 3 to encode(Isa.JMP, 1),+ 4 to encode(Isa.HLT),+ 15 to 1,+ ),+ program(+ "3 × 4 = 12",+ 128,+ 12,+ 0 to encode(Isa.LDA, 13),+ 1 to encode(Isa.ADD, 14),+ 2 to encode(Isa.STA, 13),+ 3 to encode(Isa.LDA, 12),+ 4 to encode(Isa.SUB, 15),+ 5 to encode(Isa.STA, 12),+ 6 to encode(Isa.JZ, 8),+ 7 to encode(Isa.JMP, 0),+ 8 to encode(Isa.LDA, 13),+ 9 to encode(Isa.HLT),+ 12 to 4,+ 13 to 0,+ 14 to 3,+ 15 to 1,+ ),+ ) -private val decoderTests = TestSpec.Comb(- (0..7).flatMap { op ->- (0..1).map { z ->- val lines = Isa.decode(op, z)- val aluCare = lines[2] == 1- val expected = lines.mapIndexed { i, v -> if (i < 2 && !aluCare) null else v }- Case(listOf(op, z), expected, RowTitles.decoder(listOf(op, z), expected))- }- },-)+private val decoderTests =+ TestSpec.Comb(+ (0..7).flatMap { op ->+ (0..1).map { z ->+ val lines = Isa.decode(op, z)+ val aluCare = lines[2] == 1+ val expected = lines.mapIndexed { i, v -> if (i < 2 && !aluCare) null else v }+ Case(listOf(op, z), expected, RowTitles.decoder(listOf(op, z), expected))+ }+ },+ ) -internal val cpuLevels: List<LevelDef> = listOf(- chipLevel(- Chapter.CPU, "decoder", Chips.DECODER,- LevelText(- R.string.lg_level_decoder_title,- R.string.lg_level_decoder_brief,- R.string.lg_level_decoder_hint,+internal val cpuLevels: List<LevelDef> =+ listOf(+ chipLevel(+ Chapter.CPU,+ "decoder",+ Chips.DECODER,+ LevelText(+ R.string.lg_level_decoder_title,+ R.string.lg_level_decoder_brief,+ R.string.lg_level_decoder_hint,+ ),+ tests = decoderTests,+ ),+ chipLevel(+ Chapter.CPU,+ "cpu",+ Chips.CPU,+ LevelText(+ R.string.lg_level_cpu_title,+ R.string.lg_level_cpu_brief,+ R.string.lg_level_cpu_hint,+ ),+ tests = TestSpec.Programs(cpuPrograms, harness = true), ),- tests = decoderTests,- ),- chipLevel(- Chapter.CPU, "cpu", Chips.CPU,- LevelText(- R.string.lg_level_cpu_title,- R.string.lg_level_cpu_brief,- R.string.lg_level_cpu_hint,+ LevelDef(+ id = "computer",+ chapter = Chapter.CPU,+ title = R.string.lg_level_computer_title,+ brief = R.string.lg_level_computer_brief,+ hint = R.string.lg_level_computer_hint,+ inputs = emptyList(),+ outputs = listOf(Pin("acc", 8), Pin("halt")),+ tests = TestSpec.Programs(cpuPrograms, harness = false),+ par = TestGen.chip(Chips.CPU).nandCost + TestGen.chip(Chips.RAM16).nandCost, ),- tests = TestSpec.Programs(cpuPrograms, harness = true),- ),- LevelDef(- id = "computer",- chapter = Chapter.CPU,- title = R.string.lg_level_computer_title,- brief = R.string.lg_level_computer_brief,- hint = R.string.lg_level_computer_hint,- inputs = emptyList(),- outputs = listOf(Pin("acc", 8), Pin("halt")),- tests = TestSpec.Programs(cpuPrograms, harness = false),- par = TestGen.chip(Chips.CPU).nandCost + TestGen.chip(Chips.RAM16).nandCost,- ),-)+ )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.ktindex 657120b111..a7d64aa6c5 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt@@ -20,7 +20,10 @@ object LevelRegistry { * The first level is always open. Otherwise a level opens once the previous level of its * chapter is solved; a chapter's first level needs the previous chapter's last level. */- fun isUnlocked(id: String, completed: Set<String>): Boolean {+ fun isUnlocked(+ id: String,+ completed: Set<String>,+ ): Boolean { val i = indexOf(id) return i == 0 || (i > 0 && levels[i - 1].id in completed) }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.ktindex 7980e294dc..094ade7aed 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/MemoryLevels.kt@@ -6,119 +6,170 @@ import com.vayunmathur.games.logicgate.domain.model.Pin import com.vayunmathur.games.logicgate.domain.sim.Case import com.vayunmathur.games.logicgate.domain.sim.TestSpec -private fun ticks(title: RowTitle, vararg rows: Pair<List<Int>, List<Int?>>) =- TestSpec.Seq(rows.map { (i, o) -> Case(i, o, title(i, o)) })+private fun ticks(+ title: RowTitle,+ vararg rows: Pair<List<Int>, List<Int?>>,+) = TestSpec.Seq(rows.map { (i, o) -> Case(i, o, title(i, o)) }) -internal val memoryLevels: List<LevelDef> = listOf(- LevelDef(- id = "sr_latch",- chapter = Chapter.MEMORY,- title = R.string.lg_level_sr_latch_title,- brief = R.string.lg_level_sr_latch_brief,- hint = R.string.lg_level_sr_latch_hint,- inputs = listOf(Pin("s"), Pin("r")),- outputs = listOf(Pin("q"), Pin("nq")),- tests = ticks(- RowTitles.srLatch,- listOf(1, 0) to listOf(1, 0),- listOf(0, 0) to listOf(1, 0),- listOf(0, 1) to listOf(0, 1),- listOf(0, 0) to listOf(0, 1),- listOf(1, 0) to listOf(1, 0),- listOf(0, 0) to listOf(1, 0),- listOf(0, 1) to listOf(0, 1),- listOf(0, 0) to listOf(0, 1),+internal val memoryLevels: List<LevelDef> =+ listOf(+ LevelDef(+ id = "sr_latch",+ chapter = Chapter.MEMORY,+ title = R.string.lg_level_sr_latch_title,+ brief = R.string.lg_level_sr_latch_brief,+ hint = R.string.lg_level_sr_latch_hint,+ inputs = listOf(Pin("s"), Pin("r")),+ outputs = listOf(Pin("q"), Pin("nq")),+ tests =+ ticks(+ RowTitles.srLatch,+ listOf(1, 0) to listOf(1, 0),+ listOf(0, 0) to listOf(1, 0),+ listOf(0, 1) to listOf(0, 1),+ listOf(0, 0) to listOf(0, 1),+ listOf(1, 0) to listOf(1, 0),+ listOf(0, 0) to listOf(1, 0),+ listOf(0, 1) to listOf(0, 1),+ listOf(0, 0) to listOf(0, 1),+ ),+ par = 4, ),- par = 4,- ),- LevelDef(- id = "d_latch",- chapter = Chapter.MEMORY,- title = R.string.lg_level_d_latch_title,- brief = R.string.lg_level_d_latch_brief,- hint = R.string.lg_level_d_latch_hint,- inputs = listOf(Pin("d"), Pin("en")),- outputs = listOf(Pin("q")),- tests = ticks(- RowTitles.dLatch,- listOf(1, 1) to listOf(1),- listOf(0, 0) to listOf(1),- listOf(0, 1) to listOf(0),- listOf(1, 0) to listOf(0),- listOf(1, 1) to listOf(1),- listOf(0, 0) to listOf(1),- listOf(1, 0) to listOf(1),- listOf(0, 1) to listOf(0),- listOf(0, 0) to listOf(0),+ LevelDef(+ id = "d_latch",+ chapter = Chapter.MEMORY,+ title = R.string.lg_level_d_latch_title,+ brief = R.string.lg_level_d_latch_brief,+ hint = R.string.lg_level_d_latch_hint,+ inputs = listOf(Pin("d"), Pin("en")),+ outputs = listOf(Pin("q")),+ tests =+ ticks(+ RowTitles.dLatch,+ listOf(1, 1) to listOf(1),+ listOf(0, 0) to listOf(1),+ listOf(0, 1) to listOf(0),+ listOf(1, 0) to listOf(0),+ listOf(1, 1) to listOf(1),+ listOf(0, 0) to listOf(1),+ listOf(1, 0) to listOf(1),+ listOf(0, 1) to listOf(0),+ listOf(0, 0) to listOf(0),+ ),+ par = 4,+ unlocks = listOf(Chips.DFF, Chips.DFF4, Chips.DFF8), ),- par = 4,- unlocks = listOf(Chips.DFF, Chips.DFF4, Chips.DFF8),- ),- chipLevel(- Chapter.MEMORY, "bit", Chips.BIT,- LevelText(- R.string.lg_level_bit_title,- R.string.lg_level_bit_brief,- R.string.lg_level_bit_hint,- ),- tests = TestGen.seqFromChip(+ chipLevel(+ Chapter.MEMORY,+ "bit", Chips.BIT,- RowTitles.bit,- listOf(- listOf(1, 1), listOf(0, 0), listOf(0, 0), listOf(0, 1), listOf(1, 0),- listOf(1, 0), listOf(1, 1), listOf(0, 0), listOf(0, 1), listOf(1, 1),+ LevelText(+ R.string.lg_level_bit_title,+ R.string.lg_level_bit_brief,+ R.string.lg_level_bit_hint, ),+ tests =+ TestGen.seqFromChip(+ Chips.BIT,+ RowTitles.bit,+ listOf(+ listOf(1, 1),+ listOf(0, 0),+ listOf(0, 0),+ listOf(0, 1),+ listOf(1, 0),+ listOf(1, 0),+ listOf(1, 1),+ listOf(0, 0),+ listOf(0, 1),+ listOf(1, 1),+ ),+ ), ),- ),- chipLevel(- Chapter.MEMORY, "reg8", Chips.REG8,- LevelText(- R.string.lg_level_reg8_title,- R.string.lg_level_reg8_brief,- R.string.lg_level_reg8_hint,- ),- tests = TestGen.seqFromChip(+ chipLevel(+ Chapter.MEMORY,+ "reg8", Chips.REG8,- RowTitles.reg8,- listOf(- listOf(0x5A, 1), listOf(0, 0), listOf(0xFF, 0), listOf(0xFF, 1), listOf(0x12, 0),- listOf(0x80, 1), listOf(0, 0), listOf(0x01, 1), listOf(0, 0),+ LevelText(+ R.string.lg_level_reg8_title,+ R.string.lg_level_reg8_brief,+ R.string.lg_level_reg8_hint, ),+ tests =+ TestGen.seqFromChip(+ Chips.REG8,+ RowTitles.reg8,+ listOf(+ listOf(0x5A, 1),+ listOf(0, 0),+ listOf(0xFF, 0),+ listOf(0xFF, 1),+ listOf(0x12, 0),+ listOf(0x80, 1),+ listOf(0, 0),+ listOf(0x01, 1),+ listOf(0, 0),+ ),+ ), ),- ),- chipLevel(- Chapter.MEMORY, "pc4", Chips.PC4,- LevelText(- R.string.lg_level_pc4_title,- R.string.lg_level_pc4_brief,- R.string.lg_level_pc4_hint,- ),- tests = TestGen.seqFromChip(+ chipLevel(+ Chapter.MEMORY,+ "pc4", Chips.PC4,- RowTitles.pc4,- listOf(- listOf(1, 0, 0), listOf(1, 0, 0), listOf(0, 0, 0), listOf(1, 0, 0), listOf(0, 1, 9),- listOf(1, 0, 0), listOf(1, 0, 0), listOf(1, 1, 15), listOf(1, 0, 0), listOf(1, 0, 0),- listOf(0, 0, 3), listOf(0, 1, 4), listOf(0, 0, 0),+ LevelText(+ R.string.lg_level_pc4_title,+ R.string.lg_level_pc4_brief,+ R.string.lg_level_pc4_hint, ),+ tests =+ TestGen.seqFromChip(+ Chips.PC4,+ RowTitles.pc4,+ listOf(+ listOf(1, 0, 0),+ listOf(1, 0, 0),+ listOf(0, 0, 0),+ listOf(1, 0, 0),+ listOf(0, 1, 9),+ listOf(1, 0, 0),+ listOf(1, 0, 0),+ listOf(1, 1, 15),+ listOf(1, 0, 0),+ listOf(1, 0, 0),+ listOf(0, 0, 3),+ listOf(0, 1, 4),+ listOf(0, 0, 0),+ ),+ ), ),- ),- chipLevel(- Chapter.MEMORY, "ram4", Chips.RAM4,- LevelText(- R.string.lg_level_ram4_title,- R.string.lg_level_ram4_brief,- R.string.lg_level_ram4_hint,- ),- unlocks = listOf(Chips.RAM4, Chips.RAM16),- tests = TestGen.seqFromChip(+ chipLevel(+ Chapter.MEMORY,+ "ram4", Chips.RAM4,- RowTitles.ram4,- listOf(- listOf(0, 0, 0x11, 1), listOf(0, 1, 0x22, 1), listOf(0, 0, 0, 0), listOf(0, 1, 0, 0),- listOf(1, 0, 0x33, 0), listOf(1, 0, 0, 0), listOf(1, 1, 0x44, 1), listOf(1, 1, 0, 0),- listOf(0, 0, 0x99, 0), listOf(1, 0, 0x55, 1), listOf(1, 0, 0, 0), listOf(0, 1, 0, 0),+ LevelText(+ R.string.lg_level_ram4_title,+ R.string.lg_level_ram4_brief,+ R.string.lg_level_ram4_hint, ),+ unlocks = listOf(Chips.RAM4, Chips.RAM16),+ tests =+ TestGen.seqFromChip(+ Chips.RAM4,+ RowTitles.ram4,+ listOf(+ listOf(0, 0, 0x11, 1),+ listOf(0, 1, 0x22, 1),+ listOf(0, 0, 0, 0),+ listOf(0, 1, 0, 0),+ listOf(1, 0, 0x33, 0),+ listOf(1, 0, 0, 0),+ listOf(1, 1, 0x44, 1),+ listOf(1, 1, 0, 0),+ listOf(0, 0, 0x99, 0),+ listOf(1, 0, 0x55, 1),+ listOf(1, 0, 0, 0),+ listOf(0, 1, 0, 0),+ ),+ ), ),- ),-)+ )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.ktindex 50690bb6ad..df037524b9 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RoutingLevels.kt@@ -10,56 +10,66 @@ internal val busGifts = listOf(Chips.NIB_SPLIT, Chips.NIB_JOIN, Chips.SPLIT8, Ch /** The bus-wide gates handed over for solving the bus MUX. */ internal val bitwisePack = listOf(Chips.NOT8, Chips.AND8, Chips.OR8, Chips.XOR8, Chips.MUX8B, Chips.MUX4B) -internal val routingLevels: List<LevelDef> = listOf(- chipLevel(- Chapter.ROUTING, "mux", Chips.MUX,- LevelText(- R.string.lg_level_mux_title,- R.string.lg_level_mux_brief,- R.string.lg_level_mux_hint,+internal val routingLevels: List<LevelDef> =+ listOf(+ chipLevel(+ Chapter.ROUTING,+ "mux",+ Chips.MUX,+ LevelText(+ R.string.lg_level_mux_title,+ R.string.lg_level_mux_brief,+ R.string.lg_level_mux_hint,+ ),+ title = RowTitles.mux, ),- title = RowTitles.mux,- ),- chipLevel(- Chapter.ROUTING, "dmux", Chips.DMUX,- LevelText(- R.string.lg_level_dmux_title,- R.string.lg_level_dmux_brief,- R.string.lg_level_dmux_hint,+ chipLevel(+ Chapter.ROUTING,+ "dmux",+ Chips.DMUX,+ LevelText(+ R.string.lg_level_dmux_title,+ R.string.lg_level_dmux_brief,+ R.string.lg_level_dmux_hint,+ ),+ title = RowTitles.dmux, ),- title = RowTitles.dmux,- ),- chipLevel(- Chapter.ROUTING, "dec2", Chips.DEC2,- LevelText(- R.string.lg_level_dec2_title,- R.string.lg_level_dec2_brief,- R.string.lg_level_dec2_hint,+ chipLevel(+ Chapter.ROUTING,+ "dec2",+ Chips.DEC2,+ LevelText(+ R.string.lg_level_dec2_title,+ R.string.lg_level_dec2_brief,+ R.string.lg_level_dec2_hint,+ ),+ title = RowTitles.dec2, ),- title = RowTitles.dec2,- ),- LevelDef(- id = "nibble_swap",- chapter = Chapter.ROUTING,- title = R.string.lg_level_nibble_swap_title,- brief = R.string.lg_level_nibble_swap_brief,- hint = R.string.lg_level_nibble_swap_hint,- inputs = listOf(Pin("x", 8)),- outputs = listOf(Pin("y", 8)),- tests = TestGen.comb(listOf(Pin("x", 8)), seed = 10, RowTitles.nibbleSwap) {- listOf(((it[0] shl 4) or (it[0] shr 4)) and 0xFF)- },- par = 0,- gifts = busGifts,- ),- chipLevel(- Chapter.ROUTING, "bus_mux", Chips.MUX8B,- LevelText(- R.string.lg_level_bus_mux_title,- R.string.lg_level_bus_mux_brief,- R.string.lg_level_bus_mux_hint,+ LevelDef(+ id = "nibble_swap",+ chapter = Chapter.ROUTING,+ title = R.string.lg_level_nibble_swap_title,+ brief = R.string.lg_level_nibble_swap_brief,+ hint = R.string.lg_level_nibble_swap_hint,+ inputs = listOf(Pin("x", 8)),+ outputs = listOf(Pin("y", 8)),+ tests =+ TestGen.comb(listOf(Pin("x", 8)), seed = 10, RowTitles.nibbleSwap) {+ listOf(((it[0] shl 4) or (it[0] shr 4)) and 0xFF)+ },+ par = 0,+ gifts = busGifts, ),- title = RowTitles.busMux,- unlocks = bitwisePack,- ),-)+ chipLevel(+ Chapter.ROUTING,+ "bus_mux",+ Chips.MUX8B,+ LevelText(+ R.string.lg_level_bus_mux_title,+ R.string.lg_level_bus_mux_brief,+ R.string.lg_level_bus_mux_hint,+ ),+ title = RowTitles.busMux,+ unlocks = bitwisePack,+ ),+ )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.ktindex 5603c94def..e73cf98b5d 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/RowTitles.kt@@ -12,6 +12,7 @@ typealias RowTitle = (inputs: List<Int>, expected: List<Int?>) -> String */ internal object RowTitles { private fun hex8(v: Int?) = v?.let { formatValue(it, 8) } ?: "?"+ private fun carry(c: Int?) = if (c == 1) ", carry 1" else "" fun infix(op: String): RowTitle = { i, e -> "${i[0]} $op ${i[1]} = ${e[0]}" }@@ -44,12 +45,13 @@ internal object RowTitles { val zero: RowTitle = { i, e -> "${i[0]} is zero? ${if (e[0] == 1) "yes" else "no"}" } val alu: RowTitle = { i, e ->- val body = when (i[2] * 2 + i[3]) {- 0 -> "${i[0]} + ${i[1]}"- 1 -> "${i[0]} − ${i[1]}"- 2 -> "${i[0]} AND ${i[1]}"- else -> "pass ${i[1]}"- }+ val body =+ when (i[2] * 2 + i[3]) {+ 0 -> "${i[0]} + ${i[1]}"+ 1 -> "${i[0]} − ${i[1]}"+ 2 -> "${i[0]} AND ${i[1]}"+ else -> "pass ${i[1]}"+ } "$body = ${e[0]}${if (e[1] == 1) ", zero" else ""}" } @@ -68,11 +70,12 @@ internal object RowTitles { } val srLatch: RowTitle = { i, e ->- val action = when {- i[0] == 1 -> "set"- i[1] == 1 -> "reset"- else -> "hold"- }+ val action =+ when {+ i[0] == 1 -> "set"+ i[1] == 1 -> "reset"+ else -> "hold"+ } "$action → q=${e[0]}" } @@ -83,11 +86,12 @@ internal object RowTitles { val reg8: RowTitle = { i, e -> "q=${hex8(e[0])}, then ${if (i[1] == 1) "store ${hex8(i[0])}" else "hold"}" } val pc4: RowTitle = { i, e ->- val next = when {- i[1] == 1 -> "jump to ${i[2]}"- i[0] == 1 -> "count"- else -> "hold"- }+ val next =+ when {+ i[1] == 1 -> "jump to ${i[2]}"+ i[0] == 1 -> "count"+ else -> "hold"+ } "pc=${e[0]}, then $next" }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.ktindex 834b0694f9..fcc6f6b3d1 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/TestGen.kt@@ -19,7 +19,12 @@ internal object TestGen { * Exhaustive when the inputs total at most [EXHAUSTIVE_BITS] bits; otherwise edge values for * every input (0, 1, 0x7F, 0x80, max) crossed together, plus seeded random vectors. */- fun comb(inputs: List<Pin>, seed: Int, title: RowTitle, f: (IntArray) -> List<Int?>): TestSpec.Comb {+ fun comb(+ inputs: List<Pin>,+ seed: Int,+ title: RowTitle,+ f: (IntArray) -> List<Int?>,+ ): TestSpec.Comb { val vectors = if (inputs.sumOf { it.width } <= EXHAUSTIVE_BITS) exhaustive(inputs) else sampled(inputs, seed) return TestSpec.Comb( vectors.map { v ->@@ -29,14 +34,21 @@ internal object TestGen { ) } - fun fromChip(id: String, title: RowTitle): TestSpec.Comb {+ fun fromChip(+ id: String,+ title: RowTitle,+ ): TestSpec.Comb { val spec = chip(id) val eval = (spec.behavior as Behavior.Comb).eval return comb(spec.inputs, id.hashCode(), title) { eval(it).toList() } } /** Expected outputs come from running the native chip over [ticks]. */- fun seqFromChip(id: String, title: RowTitle, ticks: List<List<Int>>): TestSpec.Seq {+ fun seqFromChip(+ id: String,+ title: RowTitle,+ ticks: List<List<Int>>,+ ): TestSpec.Seq { val seq = chip(id).behavior as Behavior.Seq var state = seq.init return TestSpec.Seq(@@ -53,15 +65,20 @@ internal object TestGen { val total = 1 shl inputs.sumOf { it.width } return (0 until total).map { code -> var rest = code- inputs.asReversed().map { p ->- val v = rest and p.mask- rest = rest shr p.width- v- }.asReversed()+ inputs+ .asReversed()+ .map { p ->+ val v = rest and p.mask+ rest = rest shr p.width+ v+ }.asReversed() } } - private fun sampled(inputs: List<Pin>, seed: Int): List<List<Int>> {+ private fun sampled(+ inputs: List<Pin>,+ seed: Int,+ ): List<List<Int>> { val edges = inputs.map { p -> listOf(0, 1, 0x7F, 0x80, p.mask).map { it and p.mask }.distinct() } val crossed = edges.fold(listOf(emptyList<Int>())) { acc, vals -> acc.flatMap { pre -> vals.map { pre + it } } } val rng = Random(seed)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.ktindex 9a7fcf8125..a2b09bc45e 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.kt@@ -4,16 +4,23 @@ package com.vayunmathur.games.logicgate.domain.model * What the editor works on: a circuit plus the pins its input/output nodes carry. In a level the * pins are fixed; in the sandbox the player adds, removes and renames them. */-data class Board(val circuit: Circuit, val io: LevelIo) {-+data class Board(+ val circuit: Circuit,+ val io: LevelIo,+) { /** Adds a [width]-bit input or output node at [pos] with the first unused default name. */- fun addPin(input: Boolean, width: Int, pos: Point): Board {+ fun addPin(+ input: Boolean,+ width: Int,+ pos: Point,+ ): Board { val pins = if (input) io.inputs else io.outputs val taken = pins.map { it.name }.toSet() val names = if (input) INPUT_NAMES else OUTPUT_NAMES- val name = names.firstOrNull { it !in taken } ?: generateSequence(pins.size + 1) { it + 1 }- .map { (if (input) "in" else "out") + it }- .first { it !in taken }+ val name =+ names.firstOrNull { it !in taken } ?: generateSequence(pins.size + 1) { it + 1 }+ .map { (if (input) "in" else "out") + it }+ .first { it !in taken } val pin = Pin(name, width) val id = NodeId(circuit.nextId) val node = if (input) LevelInput(id, io.inputs.size, pos) else LevelOutput(id, io.outputs.size, pos)@@ -24,24 +31,29 @@ data class Board(val circuit: Circuit, val io: LevelIo) { /** Removes an input or output node, its wires and its pin; later pins shift down one index. */ fun removePin(id: NodeId): Board { val node = circuit.node(id)- val (ins, outs) = when (node) {- is LevelInput -> io.inputs.filterIndexed { i, _ -> i != node.index } to io.outputs- is LevelOutput -> io.inputs to io.outputs.filterIndexed { i, _ -> i != node.index }- else -> return this- }- val nodes = circuit.nodes.filterNot { it.id == id }.map { n ->- when {- node is LevelInput && n is LevelInput && n.index > node.index -> n.copy(index = n.index - 1)- node is LevelOutput && n is LevelOutput && n.index > node.index -> n.copy(index = n.index - 1)- else -> n+ val (ins, outs) =+ when (node) {+ is LevelInput -> io.inputs.filterIndexed { i, _ -> i != node.index } to io.outputs+ is LevelOutput -> io.inputs to io.outputs.filterIndexed { i, _ -> i != node.index }+ else -> return this+ }+ val nodes =+ circuit.nodes.filterNot { it.id == id }.map { n ->+ when {+ node is LevelInput && n is LevelInput && n.index > node.index -> n.copy(index = n.index - 1)+ node is LevelOutput && n is LevelOutput && n.index > node.index -> n.copy(index = n.index - 1)+ else -> n+ } }- } val wires = circuit.wires.filterNot { it.from.node == id || it.to.node == id } return Board(circuit.copy(nodes = nodes, wires = wires), LevelIo(ins, outs)) } /** Renames the pin behind an input or output node. Blank names are ignored. */- fun renamePin(id: NodeId, name: String): Board {+ fun renamePin(+ id: NodeId,+ name: String,+ ): Board { val trimmed = name.trim().take(MAX_PIN_NAME) if (trimmed.isEmpty()) return this return when (val node = circuit.node(id)) {@@ -51,8 +63,10 @@ data class Board(val circuit: Circuit, val io: LevelIo) { } } - private fun List<Pin>.rename(index: Int, name: String) =- mapIndexed { i, p -> if (i == index) p.copy(name = name) else p }+ private fun List<Pin>.rename(+ index: Int,+ name: String,+ ) = mapIndexed { i, p -> if (i == index) p.copy(name = name) else p } /** Default pin names. */ companion object {
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.ktindex a83859b587..5fc8bfb5c5 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt@@ -6,7 +6,9 @@ package com.vayunmathur.games.logicgate.domain.model * that contains itself, directly or not, resolves to nothing and drops out like an unknown chip, * as does one nested more than [MAX_DEPTH] components deep (the simulator's inlining cap). */-class ChipCatalog(val customs: List<CustomChip> = emptyList()) {+class ChipCatalog(+ val customs: List<CustomChip> = emptyList(),+) { private val byId: Map<String, CustomChip> = customs.associateBy { it.id } private val specs: Map<String, ChipSpec> @@ -18,7 +20,11 @@ class ChipCatalog(val customs: List<CustomChip> = emptyList()) { // walk would let cached children shortcut the count and disagree with the simulator, // which inlines at most MAX_DEPTH layers from whichever chip is placed). A component on // or above a containment cycle never becomes ready, so it resolves to nothing too.- val gates = byId.mapValues { (_, chip) -> chip.board.circuit.nodes.filterIsInstance<Gate>() }+ val gates =+ byId.mapValues { (_, chip) ->+ chip.board.circuit.nodes+ .filterIsInstance<Gate>()+ } val deps = gates.mapValues { (_, gs) -> gs.map { it.chipId }.filter { it in byId }.distinct() } val parents = HashMap<String, MutableList<String>>() for ((id, ds) in deps) for (d in ds) parents.getOrPut(d) { mutableListOf() } += id@@ -44,9 +50,11 @@ class ChipCatalog(val customs: List<CustomChip> = emptyList()) { if (left == 0) queue.addLast(p) } }- specs = byId.values.mapNotNull { chip ->- height[chip.id]?.takeIf { it <= MAX_DEPTH }?.let { chip.id to chip.toSpec(cost[chip.id] ?: 0) }- }.toMap()+ specs =+ byId.values+ .mapNotNull { chip ->+ height[chip.id]?.takeIf { it <= MAX_DEPTH }?.let { chip.id to chip.toSpec(cost[chip.id] ?: 0) }+ }.toMap() } operator fun get(id: String): ChipSpec? = Chips[id] ?: specs[id]@@ -56,13 +64,24 @@ class ChipCatalog(val customs: List<CustomChip> = emptyList()) { fun lookup(io: LevelIo): PinLookup = Chips.lookup(io, ::get) /** True when [id] is [target] or contains it at any depth. */- fun uses(id: String, target: String): Boolean {+ fun uses(+ id: String,+ target: String,+ ): Boolean { val seen = HashSet<String>()- fun visit(c: String, depth: Int): Boolean {++ fun visit(+ c: String,+ depth: Int,+ ): Boolean { if (c == target) return true if (depth >= MAX_DEPTH) return false if (!seen.add(c)) return false- return byId[c]?.board?.circuit?.nodes?.any { it is Gate && visit(it.chipId, depth + 1) } == true+ return byId[c]+ ?.board+ ?.circuit+ ?.nodes+ ?.any { it is Gate && visit(it.chipId, depth + 1) } == true } return visit(id, 0) }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.ktindex 42fdccd949..06e2b96b27 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt@@ -8,63 +8,64 @@ import com.vayunmathur.games.logicgate.R * chip card in the tray is tapped. Every chip in [Chips.all] has an entry (guarded by a test). */ object ChipInfo {+ private class ChipText(+ @StringRes val label: Int,+ @StringRes val blurb: Int,+ ) - private class ChipText(@StringRes val label: Int, @StringRes val blurb: Int)-- private val texts = mapOf(- Chips.NAND to ChipText(R.string.lg_chip_nand_label, R.string.lg_chip_nand_info),- Chips.HIGH to ChipText(R.string.lg_chip_high_label, R.string.lg_chip_high_info),- Chips.LOW to ChipText(R.string.lg_chip_low_label, R.string.lg_chip_low_info),- Chips.NOT to ChipText(R.string.lg_chip_not_label, R.string.lg_chip_not_info),- Chips.AND to ChipText(R.string.lg_chip_and_label, R.string.lg_chip_and_info),- Chips.OR to ChipText(R.string.lg_chip_or_label, R.string.lg_chip_or_info),- Chips.NOR to ChipText(R.string.lg_chip_nor_label, R.string.lg_chip_nor_info),- Chips.XOR to ChipText(R.string.lg_chip_xor_label, R.string.lg_chip_xor_info),- Chips.XNOR to ChipText(R.string.lg_chip_xnor_label, R.string.lg_chip_xnor_info),-- Chips.MUX to ChipText(R.string.lg_chip_mux_label, R.string.lg_chip_mux_info),- Chips.DMUX to ChipText(R.string.lg_chip_dmux_label, R.string.lg_chip_dmux_info),- Chips.DEC2 to ChipText(R.string.lg_chip_dec2_label, R.string.lg_chip_dec2_info),- Chips.SPLIT8 to ChipText(R.string.lg_chip_split8_label, R.string.lg_chip_split8_info),- Chips.JOIN8 to ChipText(R.string.lg_chip_join8_label, R.string.lg_chip_join8_info),- Chips.SPLIT4 to ChipText(R.string.lg_chip_split4_label, R.string.lg_chip_split4_info),- Chips.JOIN4 to ChipText(R.string.lg_chip_join4_label, R.string.lg_chip_join4_info),- Chips.NIB_SPLIT to ChipText(R.string.lg_chip_nib_split_label, R.string.lg_chip_nib_split_info),- Chips.NIB_JOIN to ChipText(R.string.lg_chip_nib_join_label, R.string.lg_chip_nib_join_info),- Chips.NOT8 to ChipText(R.string.lg_chip_not8_label, R.string.lg_chip_not8_info),- Chips.AND8 to ChipText(R.string.lg_chip_and8_label, R.string.lg_chip_and8_info),- Chips.OR8 to ChipText(R.string.lg_chip_or8_label, R.string.lg_chip_or8_info),- Chips.XOR8 to ChipText(R.string.lg_chip_xor8_label, R.string.lg_chip_xor8_info),- Chips.MUX8B to ChipText(R.string.lg_chip_mux8b_label, R.string.lg_chip_mux8b_info),- Chips.MUX4B to ChipText(R.string.lg_chip_mux4b_label, R.string.lg_chip_mux4b_info),-- Chips.HALF to ChipText(R.string.lg_chip_half_label, R.string.lg_chip_half_info),- Chips.FULL to ChipText(R.string.lg_chip_full_label, R.string.lg_chip_full_info),- Chips.ADD4 to ChipText(R.string.lg_chip_add4_label, R.string.lg_chip_add4_info),- Chips.ADD8 to ChipText(R.string.lg_chip_add8_label, R.string.lg_chip_add8_info),- Chips.INC4 to ChipText(R.string.lg_chip_inc4_label, R.string.lg_chip_inc4_info),- Chips.SUB8 to ChipText(R.string.lg_chip_sub8_label, R.string.lg_chip_sub8_info),- Chips.ZERO8 to ChipText(R.string.lg_chip_zero8_label, R.string.lg_chip_zero8_info),- Chips.ALU8 to ChipText(R.string.lg_chip_alu8_label, R.string.lg_chip_alu8_info),-- Chips.DFF to ChipText(R.string.lg_chip_dff_label, R.string.lg_chip_dff_info),- Chips.DFF4 to ChipText(R.string.lg_chip_dff4_label, R.string.lg_chip_dff4_info),- Chips.DFF8 to ChipText(R.string.lg_chip_dff8_label, R.string.lg_chip_dff8_info),- Chips.BIT to ChipText(R.string.lg_chip_bit_label, R.string.lg_chip_bit_info),- Chips.REG8 to ChipText(R.string.lg_chip_reg8_label, R.string.lg_chip_reg8_info),- Chips.PC4 to ChipText(R.string.lg_chip_pc4_label, R.string.lg_chip_pc4_info),- Chips.RAM4 to ChipText(R.string.lg_chip_ram4_label, R.string.lg_chip_ram4_info),- Chips.RAM16 to ChipText(R.string.lg_chip_ram16_label, R.string.lg_chip_ram16_info),-- Chips.DECODER to ChipText(R.string.lg_chip_decoder_label, R.string.lg_chip_decoder_info),- Chips.CPU to ChipText(R.string.lg_chip_cpu_label, R.string.lg_chip_cpu_info),- ) + PinChips.all.associate { pin ->- pin.id to if (PinChips.isInput(pin.id)) {- ChipText(R.string.lg_chip_input_label, R.string.lg_chip_input_info)- } else {- ChipText(R.string.lg_chip_output_label, R.string.lg_chip_output_info)- }- }+ private val texts =+ mapOf(+ Chips.NAND to ChipText(R.string.lg_chip_nand_label, R.string.lg_chip_nand_info),+ Chips.HIGH to ChipText(R.string.lg_chip_high_label, R.string.lg_chip_high_info),+ Chips.LOW to ChipText(R.string.lg_chip_low_label, R.string.lg_chip_low_info),+ Chips.NOT to ChipText(R.string.lg_chip_not_label, R.string.lg_chip_not_info),+ Chips.AND to ChipText(R.string.lg_chip_and_label, R.string.lg_chip_and_info),+ Chips.OR to ChipText(R.string.lg_chip_or_label, R.string.lg_chip_or_info),+ Chips.NOR to ChipText(R.string.lg_chip_nor_label, R.string.lg_chip_nor_info),+ Chips.XOR to ChipText(R.string.lg_chip_xor_label, R.string.lg_chip_xor_info),+ Chips.XNOR to ChipText(R.string.lg_chip_xnor_label, R.string.lg_chip_xnor_info),+ Chips.MUX to ChipText(R.string.lg_chip_mux_label, R.string.lg_chip_mux_info),+ Chips.DMUX to ChipText(R.string.lg_chip_dmux_label, R.string.lg_chip_dmux_info),+ Chips.DEC2 to ChipText(R.string.lg_chip_dec2_label, R.string.lg_chip_dec2_info),+ Chips.SPLIT8 to ChipText(R.string.lg_chip_split8_label, R.string.lg_chip_split8_info),+ Chips.JOIN8 to ChipText(R.string.lg_chip_join8_label, R.string.lg_chip_join8_info),+ Chips.SPLIT4 to ChipText(R.string.lg_chip_split4_label, R.string.lg_chip_split4_info),+ Chips.JOIN4 to ChipText(R.string.lg_chip_join4_label, R.string.lg_chip_join4_info),+ Chips.NIB_SPLIT to ChipText(R.string.lg_chip_nib_split_label, R.string.lg_chip_nib_split_info),+ Chips.NIB_JOIN to ChipText(R.string.lg_chip_nib_join_label, R.string.lg_chip_nib_join_info),+ Chips.NOT8 to ChipText(R.string.lg_chip_not8_label, R.string.lg_chip_not8_info),+ Chips.AND8 to ChipText(R.string.lg_chip_and8_label, R.string.lg_chip_and8_info),+ Chips.OR8 to ChipText(R.string.lg_chip_or8_label, R.string.lg_chip_or8_info),+ Chips.XOR8 to ChipText(R.string.lg_chip_xor8_label, R.string.lg_chip_xor8_info),+ Chips.MUX8B to ChipText(R.string.lg_chip_mux8b_label, R.string.lg_chip_mux8b_info),+ Chips.MUX4B to ChipText(R.string.lg_chip_mux4b_label, R.string.lg_chip_mux4b_info),+ Chips.HALF to ChipText(R.string.lg_chip_half_label, R.string.lg_chip_half_info),+ Chips.FULL to ChipText(R.string.lg_chip_full_label, R.string.lg_chip_full_info),+ Chips.ADD4 to ChipText(R.string.lg_chip_add4_label, R.string.lg_chip_add4_info),+ Chips.ADD8 to ChipText(R.string.lg_chip_add8_label, R.string.lg_chip_add8_info),+ Chips.INC4 to ChipText(R.string.lg_chip_inc4_label, R.string.lg_chip_inc4_info),+ Chips.SUB8 to ChipText(R.string.lg_chip_sub8_label, R.string.lg_chip_sub8_info),+ Chips.ZERO8 to ChipText(R.string.lg_chip_zero8_label, R.string.lg_chip_zero8_info),+ Chips.ALU8 to ChipText(R.string.lg_chip_alu8_label, R.string.lg_chip_alu8_info),+ Chips.DFF to ChipText(R.string.lg_chip_dff_label, R.string.lg_chip_dff_info),+ Chips.DFF4 to ChipText(R.string.lg_chip_dff4_label, R.string.lg_chip_dff4_info),+ Chips.DFF8 to ChipText(R.string.lg_chip_dff8_label, R.string.lg_chip_dff8_info),+ Chips.BIT to ChipText(R.string.lg_chip_bit_label, R.string.lg_chip_bit_info),+ Chips.REG8 to ChipText(R.string.lg_chip_reg8_label, R.string.lg_chip_reg8_info),+ Chips.PC4 to ChipText(R.string.lg_chip_pc4_label, R.string.lg_chip_pc4_info),+ Chips.RAM4 to ChipText(R.string.lg_chip_ram4_label, R.string.lg_chip_ram4_info),+ Chips.RAM16 to ChipText(R.string.lg_chip_ram16_label, R.string.lg_chip_ram16_info),+ Chips.DECODER to ChipText(R.string.lg_chip_decoder_label, R.string.lg_chip_decoder_info),+ Chips.CPU to ChipText(R.string.lg_chip_cpu_label, R.string.lg_chip_cpu_info),+ ) ++ PinChips.all.associate { pin ->+ pin.id to+ if (PinChips.isInput(pin.id)) {+ ChipText(R.string.lg_chip_input_label, R.string.lg_chip_input_info)+ } else {+ ChipText(R.string.lg_chip_output_label, R.string.lg_chip_output_info)+ }+ } /** The name of [chipId] as a string resource, or null for a chip with no entry. */ @StringRes
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.ktindex c13de7a998..186e5811b7 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt@@ -1,14 +1,19 @@ package com.vayunmathur.games.logicgate.domain.model /** A named pin carrying a [width]-bit signal (1, 4 or 8). Signals are bit masks in an `Int`. */-data class Pin(val name: String, val width: Int = 1) {+data class Pin(+ val name: String,+ val width: Int = 1,+) { val mask: Int get() = (1 shl width) - 1 } /** How a chip turns input signals into output signals. */ sealed interface Behavior { /** Outputs are a pure function of inputs. */- class Comb(val eval: (IntArray) -> IntArray) : Behavior+ class Comb(+ val eval: (IntArray) -> IntArray,+ ) : Behavior /** * Clocked state. [outputs] reads the current state (and, when [readsInputs], the inputs too —@@ -25,7 +30,11 @@ sealed interface Behavior { * A player-built chip. The simulator inlines [circuit] rather than running it as a black box; * chip input `k` feeds inner node [inputNodes]`[k]` and chip output `k` reads [outputNodes]`[k]`. */- class Composite(val circuit: Circuit, val inputNodes: List<NodeId>, val outputNodes: List<NodeId>) : Behavior+ class Composite(+ val circuit: Circuit,+ val inputNodes: List<NodeId>,+ val outputNodes: List<NodeId>,+ ) : Behavior } /** A placeable chip: its pins, what it costs in NAND gates, and its trusted native behaviour. */
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.ktindex 9a54a4b461..e03c4fc024 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt@@ -51,8 +51,15 @@ object Chips { /** Chips every level offers. */ val base: List<String> = listOf(NAND, HIGH, LOW) - private fun p(name: String, width: Int = 1) = Pin(name, width)- private fun bits(prefix: String, n: Int) = (0 until n).map { p("$prefix$it") }+ private fun p(+ name: String,+ width: Int = 1,+ ) = Pin(name, width)++ private fun bits(+ prefix: String,+ n: Int,+ ) = (0 until n).map { p("$prefix$it") } private fun comb( id: String,@@ -62,94 +69,115 @@ object Chips { f: (IntArray) -> IntArray, ) = ChipSpec(id, inputs, outputs, cost, Behavior.Comb(f)) - private fun gate2(id: String, cost: Int, f: (Int, Int) -> Int) =- comb(id, listOf(p("a"), p("b")), listOf(p("o")), cost) { intArrayOf(f(it[0], it[1]) and 1) }+ private fun gate2(+ id: String,+ cost: Int,+ f: (Int, Int) -> Int,+ ) = comb(id, listOf(p("a"), p("b")), listOf(p("o")), cost) { intArrayOf(f(it[0], it[1]) and 1) }++ private fun split(+ id: String,+ n: Int,+ ) = comb(id, listOf(p("x", n)), bits("b", n), 0) { v -> IntArray(n) { (v[0] shr it) and 1 } } - private fun split(id: String, n: Int) =- comb(id, listOf(p("x", n)), bits("b", n), 0) { v -> IntArray(n) { (v[0] shr it) and 1 } }+ private fun join(+ id: String,+ n: Int,+ ) = comb(id, bits("b", n), listOf(p("x", n)), 0) { v ->+ intArrayOf(v.foldIndexed(0) { i, acc, b -> acc or ((b and 1) shl i) })+ } - private fun join(id: String, n: Int) =- comb(id, bits("b", n), listOf(p("x", n)), 0) { v ->- intArrayOf(v.foldIndexed(0) { i, acc, b -> acc or ((b and 1) shl i) })- }+ private fun bitwise8(+ id: String,+ cost: Int,+ f: (Int, Int) -> Int,+ ) = comb(id, listOf(p("a", 8), p("b", 8)), listOf(p("o", 8)), cost) { intArrayOf(f(it[0], it[1]) and 0xFF) }++ private val logic =+ listOf(+ gate2(NAND, 1) { a, b -> (a and b) xor 1 },+ comb(HIGH, emptyList(), listOf(p("o")), 0) { intArrayOf(1) },+ comb(LOW, emptyList(), listOf(p("o")), 0) { intArrayOf(0) },+ comb(NOT, listOf(p("a")), listOf(p("o")), 1) { intArrayOf(it[0] xor 1) },+ gate2(AND, 2) { a, b -> a and b },+ gate2(OR, 3) { a, b -> a or b },+ gate2(NOR, 4) { a, b -> (a or b) xor 1 },+ gate2(XOR, 4) { a, b -> a xor b },+ gate2(XNOR, 5) { a, b -> a xor b xor 1 },+ )++ private val routing =+ listOf(+ comb(MUX, listOf(p("a"), p("b"), p("s")), listOf(p("o")), 4) {+ intArrayOf(if (it[2] == 1) it[1] else it[0])+ },+ comb(DMUX, listOf(p("in"), p("s")), listOf(p("a"), p("b")), 5) {+ intArrayOf(it[0] and (it[1] xor 1), it[0] and it[1])+ },+ comb(DEC2, listOf(p("s1"), p("s0")), bits("y", 4), 10) { v ->+ val sel = v[0] * 2 + v[1]+ IntArray(4) { if (it == sel) 1 else 0 }+ },+ split(SPLIT8, 8),+ join(JOIN8, 8),+ split(SPLIT4, 4),+ join(JOIN4, 4),+ comb(NIB_SPLIT, listOf(p("x", 8)), listOf(p("lo", 4), p("hi", 4)), 0) {+ intArrayOf(it[0] and 0xF, it[0] shr 4)+ },+ comb(NIB_JOIN, listOf(p("lo", 4), p("hi", 4)), listOf(p("x", 8)), 0) {+ intArrayOf(it[0] or (it[1] shl 4))+ },+ comb(NOT8, listOf(p("a", 8)), listOf(p("o", 8)), 8) { intArrayOf(it[0].inv() and 0xFF) },+ bitwise8(AND8, 16) { a, b -> a and b },+ bitwise8(OR8, 24) { a, b -> a or b },+ bitwise8(XOR8, 32) { a, b -> a xor b },+ comb(MUX8B, listOf(p("a", 8), p("b", 8), p("s")), listOf(p("o", 8)), 32) {+ intArrayOf(if (it[2] == 1) it[1] else it[0])+ },+ comb(MUX4B, listOf(p("a", 4), p("b", 4), p("s")), listOf(p("o", 4)), 16) {+ intArrayOf(if (it[2] == 1) it[1] else it[0])+ },+ )++ private val arithmetic =+ listOf(+ comb(HALF, listOf(p("a"), p("b")), listOf(p("s"), p("c")), 5) {+ intArrayOf(it[0] xor it[1], it[0] and it[1])+ },+ comb(FULL, listOf(p("a"), p("b"), p("cin")), listOf(p("s"), p("cout")), 9) {+ val t = it[0] + it[1] + it[2]+ intArrayOf(t and 1, t shr 1)+ },+ comb(ADD4, listOf(p("a", 4), p("b", 4), p("cin")), listOf(p("s", 4), p("cout")), 36) {+ val t = it[0] + it[1] + it[2]+ intArrayOf(t and 0xF, t shr 4)+ },+ comb(ADD8, listOf(p("a", 8), p("b", 8), p("cin")), listOf(p("s", 8), p("cout")), 72) {+ val t = it[0] + it[1] + it[2]+ intArrayOf(t and 0xFF, t shr 8)+ },+ comb(INC4, listOf(p("a", 4)), listOf(p("o", 4)), 16) { intArrayOf((it[0] + 1) and 0xF) },+ comb(SUB8, listOf(p("a", 8), p("b", 8)), listOf(p("d", 8)), 80) { intArrayOf((it[0] - it[1]) and 0xFF) },+ comb(ZERO8, listOf(p("a", 8)), listOf(p("z")), 22) { intArrayOf(if (it[0] == 0) 1 else 0) },+ comb(ALU8, listOf(p("a", 8), p("b", 8), p("op1"), p("op0")), listOf(p("o", 8), p("z")), 206) {+ val r = alu(it[0], it[1], it[2] * 2 + it[3])+ intArrayOf(r, if (r == 0) 1 else 0)+ },+ ) - private fun bitwise8(id: String, cost: Int, f: (Int, Int) -> Int) =- comb(id, listOf(p("a", 8), p("b", 8)), listOf(p("o", 8)), cost) { intArrayOf(f(it[0], it[1]) and 0xFF) }-- private val logic = listOf(- gate2(NAND, 1) { a, b -> (a and b) xor 1 },- comb(HIGH, emptyList(), listOf(p("o")), 0) { intArrayOf(1) },- comb(LOW, emptyList(), listOf(p("o")), 0) { intArrayOf(0) },- comb(NOT, listOf(p("a")), listOf(p("o")), 1) { intArrayOf(it[0] xor 1) },- gate2(AND, 2) { a, b -> a and b },- gate2(OR, 3) { a, b -> a or b },- gate2(NOR, 4) { a, b -> (a or b) xor 1 },- gate2(XOR, 4) { a, b -> a xor b },- gate2(XNOR, 5) { a, b -> a xor b xor 1 },- )-- private val routing = listOf(- comb(MUX, listOf(p("a"), p("b"), p("s")), listOf(p("o")), 4) {- intArrayOf(if (it[2] == 1) it[1] else it[0])- },- comb(DMUX, listOf(p("in"), p("s")), listOf(p("a"), p("b")), 5) {- intArrayOf(it[0] and (it[1] xor 1), it[0] and it[1])- },- comb(DEC2, listOf(p("s1"), p("s0")), bits("y", 4), 10) { v ->- val sel = v[0] * 2 + v[1]- IntArray(4) { if (it == sel) 1 else 0 }- },- split(SPLIT8, 8),- join(JOIN8, 8),- split(SPLIT4, 4),- join(JOIN4, 4),- comb(NIB_SPLIT, listOf(p("x", 8)), listOf(p("lo", 4), p("hi", 4)), 0) {- intArrayOf(it[0] and 0xF, it[0] shr 4)- },- comb(NIB_JOIN, listOf(p("lo", 4), p("hi", 4)), listOf(p("x", 8)), 0) {- intArrayOf(it[0] or (it[1] shl 4))- },- comb(NOT8, listOf(p("a", 8)), listOf(p("o", 8)), 8) { intArrayOf(it[0].inv() and 0xFF) },- bitwise8(AND8, 16) { a, b -> a and b },- bitwise8(OR8, 24) { a, b -> a or b },- bitwise8(XOR8, 32) { a, b -> a xor b },- comb(MUX8B, listOf(p("a", 8), p("b", 8), p("s")), listOf(p("o", 8)), 32) {- intArrayOf(if (it[2] == 1) it[1] else it[0])- },- comb(MUX4B, listOf(p("a", 4), p("b", 4), p("s")), listOf(p("o", 4)), 16) {- intArrayOf(if (it[2] == 1) it[1] else it[0])- },- )-- private val arithmetic = listOf(- comb(HALF, listOf(p("a"), p("b")), listOf(p("s"), p("c")), 5) {- intArrayOf(it[0] xor it[1], it[0] and it[1])- },- comb(FULL, listOf(p("a"), p("b"), p("cin")), listOf(p("s"), p("cout")), 9) {- val t = it[0] + it[1] + it[2]- intArrayOf(t and 1, t shr 1)- },- comb(ADD4, listOf(p("a", 4), p("b", 4), p("cin")), listOf(p("s", 4), p("cout")), 36) {- val t = it[0] + it[1] + it[2]- intArrayOf(t and 0xF, t shr 4)- },- comb(ADD8, listOf(p("a", 8), p("b", 8), p("cin")), listOf(p("s", 8), p("cout")), 72) {- val t = it[0] + it[1] + it[2]- intArrayOf(t and 0xFF, t shr 8)- },- comb(INC4, listOf(p("a", 4)), listOf(p("o", 4)), 16) { intArrayOf((it[0] + 1) and 0xF) },- comb(SUB8, listOf(p("a", 8), p("b", 8)), listOf(p("d", 8)), 80) { intArrayOf((it[0] - it[1]) and 0xFF) },- comb(ZERO8, listOf(p("a", 8)), listOf(p("z")), 22) { intArrayOf(if (it[0] == 0) 1 else 0) },- comb(ALU8, listOf(p("a", 8), p("b", 8), p("op1"), p("op0")), listOf(p("o", 8), p("z")), 206) {- val r = alu(it[0], it[1], it[2] * 2 + it[3])- intArrayOf(r, if (r == 0) 1 else 0)- },- )-- private fun register(id: String, width: Int, cost: Int, withLoad: Boolean): ChipSpec {+ private fun register(+ id: String,+ width: Int,+ cost: Int,+ withLoad: Boolean,+ ): ChipSpec { val ins = if (withLoad) listOf(p("d", width), p("load")) else listOf(p("d", width)) return ChipSpec(- id, ins, listOf(p("q", width)), cost,+ id,+ ins,+ listOf(p("q", width)),+ cost, Behavior.Seq( init = IntArray(1), outputs = { s, _ -> intArrayOf(s[0]) },@@ -158,53 +186,66 @@ object Chips { ) } - private val memory = listOf(- register(DFF, 1, 8, withLoad = false),- register(DFF4, 4, 32, withLoad = false),- register(DFF8, 8, 64, withLoad = false),- register(BIT, 1, 12, withLoad = true),- register(REG8, 8, 96, withLoad = true),- ChipSpec(- PC4, listOf(p("en"), p("load"), p("v", 4)), listOf(p("pc", 4)), 80,- Behavior.Seq(- init = IntArray(1),- outputs = { s, _ -> intArrayOf(s[0]) },- next = { s, i -> intArrayOf(pcNext(s[0], i[0], i[1], i[2])) },+ private val memory =+ listOf(+ register(DFF, 1, 8, withLoad = false),+ register(DFF4, 4, 32, withLoad = false),+ register(DFF8, 8, 64, withLoad = false),+ register(BIT, 1, 12, withLoad = true),+ register(REG8, 8, 96, withLoad = true),+ ChipSpec(+ PC4,+ listOf(p("en"), p("load"), p("v", 4)),+ listOf(p("pc", 4)),+ 80,+ Behavior.Seq(+ init = IntArray(1),+ outputs = { s, _ -> intArrayOf(s[0]) },+ next = { s, i -> intArrayOf(pcNext(s[0], i[0], i[1], i[2])) },+ ), ),- ),- ChipSpec(- RAM4, listOf(p("a1"), p("a0"), p("din", 8), p("we")), listOf(p("dout", 8)), 498,- Behavior.Seq(- init = IntArray(4),- outputs = { s, i -> intArrayOf(s[i[0] * 2 + i[1]]) },- next = { s, i -> s.copyOf().also { if (i[3] == 1) it[i[0] * 2 + i[1]] = i[2] } },- readsInputs = true,+ ChipSpec(+ RAM4,+ listOf(p("a1"), p("a0"), p("din", 8), p("we")),+ listOf(p("dout", 8)),+ 498,+ Behavior.Seq(+ init = IntArray(4),+ outputs = { s, i -> intArrayOf(s[i[0] * 2 + i[1]]) },+ next = { s, i -> s.copyOf().also { if (i[3] == 1) it[i[0] * 2 + i[1]] = i[2] } },+ readsInputs = true,+ ), ),- ),- ChipSpec(- RAM16, listOf(p("iaddr", 4), p("daddr", 4), p("din", 8), p("we")),- listOf(p("instr", 8), p("dout", 8)), 2560,- Behavior.Seq(- init = IntArray(16),- outputs = { s, i -> intArrayOf(s[i[0]], s[i[1]]) },- next = { s, i -> s.copyOf().also { if (i[3] == 1) it[i[1]] = i[2] } },- readsInputs = true,+ ChipSpec(+ RAM16,+ listOf(p("iaddr", 4), p("daddr", 4), p("din", 8), p("we")),+ listOf(p("instr", 8), p("dout", 8)),+ 2560,+ Behavior.Seq(+ init = IntArray(16),+ outputs = { s, i -> intArrayOf(s[i[0]], s[i[1]]) },+ next = { s, i -> s.copyOf().also { if (i[3] == 1) it[i[1]] = i[2] } },+ readsInputs = true,+ ), ),- ),- )+ ) - private val cpu = listOf(- comb(DECODER, listOf(p("op", 4), p("z")), Isa.decoderOutputs, 44) { Isa.decode(it[0], it[1]) },- ChipSpec(- CPU, listOf(p("instr", 8), p("data", 8)), Isa.cpuOutputs, 481,- Behavior.Seq(- init = IntArray(2),- outputs = { s, i -> Isa.cpuOut(s[0], s[1], i[0]) },- next = { s, i -> Isa.cpuNext(s[0], s[1], i[0], i[1]) },- readsInputs = true,+ private val cpu =+ listOf(+ comb(DECODER, listOf(p("op", 4), p("z")), Isa.decoderOutputs, 44) { Isa.decode(it[0], it[1]) },+ ChipSpec(+ CPU,+ listOf(p("instr", 8), p("data", 8)),+ Isa.cpuOutputs,+ 481,+ Behavior.Seq(+ init = IntArray(2),+ outputs = { s, i -> Isa.cpuOut(s[0], s[1], i[0]) },+ next = { s, i -> Isa.cpuNext(s[0], s[1], i[0], i[1]) },+ readsInputs = true,+ ), ),- ),- )+ ) val all: List<ChipSpec> = logic + routing + arithmetic + memory + cpu @@ -213,25 +254,40 @@ object Chips { operator fun get(id: String): ChipSpec? = byId[id] /** Pin lookup for a board with the level pins [io], resolving chips through [spec]. */- fun lookup(io: LevelIo, spec: (String) -> ChipSpec? = { byId[it] }): PinLookup = PinLookup { node ->- when (node) {- is Gate -> spec(node.chipId)?.let { NodePins(it.inputs, it.outputs) }- is LevelInput -> io.inputs.getOrNull(node.index)?.let { NodePins(emptyList(), listOf(it)) }- is LevelOutput -> io.outputs.getOrNull(node.index)?.let { NodePins(listOf(it), emptyList()) }+ fun lookup(+ io: LevelIo,+ spec: (String) -> ChipSpec? = { byId[it] },+ ): PinLookup =+ PinLookup { node ->+ when (node) {+ is Gate -> spec(node.chipId)?.let { NodePins(it.inputs, it.outputs) }+ is LevelInput -> io.inputs.getOrNull(node.index)?.let { NodePins(emptyList(), listOf(it)) }+ is LevelOutput -> io.outputs.getOrNull(node.index)?.let { NodePins(listOf(it), emptyList()) }+ } }- } /** `00` ADD · `01` SUB · `10` AND · `11` PASS B, all 8-bit wrapping. */- fun alu(a: Int, b: Int, op: Int): Int = when (op) {- 0 -> a + b- 1 -> a - b- 2 -> a and b- else -> b- } and 0xFF-- fun pcNext(pc: Int, en: Int, load: Int, v: Int): Int = when {- load == 1 -> v- en == 1 -> (pc + 1) and 0xF- else -> pc- }+ fun alu(+ a: Int,+ b: Int,+ op: Int,+ ): Int =+ when (op) {+ 0 -> a + b+ 1 -> a - b+ 2 -> a and b+ else -> b+ } and 0xFF++ fun pcNext(+ pc: Int,+ en: Int,+ load: Int,+ v: Int,+ ): Int =+ when {+ load == 1 -> v+ en == 1 -> (pc + 1) and 0xF+ else -> pc+ } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.ktindex 332501e63d..654837a46a 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Circuit.kt@@ -2,50 +2,83 @@ package com.vayunmathur.games.logicgate.domain.model /** Stable identity of a node within one circuit. */ @JvmInline-value class NodeId(val raw: Int)+value class NodeId(+ val raw: Int,+) /** Which edge of a node a pin sits on. */ enum class PinSide { IN, OUT } /** One pin of one node. */-data class PinRef(val node: NodeId, val side: PinSide, val index: Int)+data class PinRef(+ val node: NodeId,+ val side: PinSide,+ val index: Int,+) /** A position in world units. */-data class Point(val x: Float, val y: Float)+data class Point(+ val x: Float,+ val y: Float,+) /** Something on the board: a chip, or one of the level's own inputs/outputs. */ sealed interface Node { val id: NodeId val pos: Point+ fun moved(to: Point): Node } /** A placed chip. */-data class Gate(override val id: NodeId, val chipId: String, override val pos: Point) : Node {+data class Gate(+ override val id: NodeId,+ val chipId: String,+ override val pos: Point,+) : Node { override fun moved(to: Point) = copy(pos = to) } /** The level's input [index], drawn as a source on the left of the board. */-data class LevelInput(override val id: NodeId, val index: Int, override val pos: Point) : Node {+data class LevelInput(+ override val id: NodeId,+ val index: Int,+ override val pos: Point,+) : Node { override fun moved(to: Point) = copy(pos = to) } /** The level's output [index], drawn as a sink on the right of the board. */-data class LevelOutput(override val id: NodeId, val index: Int, override val pos: Point) : Node {+data class LevelOutput(+ override val id: NodeId,+ val index: Int,+ override val pos: Point,+) : Node { override fun moved(to: Point) = copy(pos = to) } /** A connection from an output pin to an input pin. */-data class Wire(val from: PinRef, val to: PinRef)+data class Wire(+ val from: PinRef,+ val to: PinRef,+) /** The pins a node exposes. */-data class NodePins(val inputs: List<Pin>, val outputs: List<Pin>) {- fun pin(side: PinSide, index: Int): Pin? =- (if (side == PinSide.IN) inputs else outputs).getOrNull(index)+data class NodePins(+ val inputs: List<Pin>,+ val outputs: List<Pin>,+) {+ fun pin(+ side: PinSide,+ index: Int,+ ): Pin? = (if (side == PinSide.IN) inputs else outputs).getOrNull(index) } /** The pin layout of a level's board. */-data class LevelIo(val inputs: List<Pin>, val outputs: List<Pin>)+data class LevelIo(+ val inputs: List<Pin>,+ val outputs: List<Pin>,+) /** Resolves the pins of a node; null when the node's chip is unknown. */ fun interface PinLookup {@@ -55,13 +88,20 @@ fun interface PinLookup { /** Outcome of asking whether two pins may be wired together. */ sealed interface ConnectCheck { /** Allowed; [wire] is the normalised output-to-input connection. */- data class Ok(val wire: Wire) : ConnectCheck+ data class Ok(+ val wire: Wire,+ ) : ConnectCheck /** Both ends are inputs, or both are outputs. */- data class SameSide(val side: PinSide) : ConnectCheck+ data class SameSide(+ val side: PinSide,+ ) : ConnectCheck /** The pins carry different bus widths. */- data class WidthMismatch(val fromWidth: Int, val toWidth: Int) : ConnectCheck+ data class WidthMismatch(+ val fromWidth: Int,+ val toWidth: Int,+ ) : ConnectCheck /** One end does not exist. */ data object MissingPin : ConnectCheck@@ -75,13 +115,18 @@ data class Circuit( ) { fun node(id: NodeId): Node? = nodes.firstOrNull { it.id == id } - fun addGate(chipId: String, pos: Point): Pair<Circuit, NodeId> {+ fun addGate(+ chipId: String,+ pos: Point,+ ): Pair<Circuit, NodeId> { val id = NodeId(nextId) return copy(nodes = nodes + Gate(id, chipId, pos), nextId = nextId + 1) to id } - fun moveNode(id: NodeId, pos: Point): Circuit =- copy(nodes = nodes.map { if (it.id == id) it.moved(pos) else it })+ fun moveNode(+ id: NodeId,+ pos: Point,+ ): Circuit = copy(nodes = nodes.map { if (it.id == id) it.moved(pos) else it }) /** Removes a gate and every wire touching it. Level inputs/outputs cannot be removed. */ fun removeNode(id: NodeId): Circuit {@@ -96,10 +141,16 @@ data class Circuit( fun wireInto(pin: PinRef): Wire? = wires.firstOrNull { it.to == pin } - fun pin(ref: PinRef, lookup: PinLookup): Pin? =- node(ref.node)?.let { lookup.pins(it) }?.pin(ref.side, ref.index)+ fun pin(+ ref: PinRef,+ lookup: PinLookup,+ ): Pin? = node(ref.node)?.let { lookup.pins(it) }?.pin(ref.side, ref.index) - fun check(a: PinRef, b: PinRef, lookup: PinLookup): ConnectCheck {+ fun check(+ a: PinRef,+ b: PinRef,+ lookup: PinLookup,+ ): ConnectCheck { if (a.side == b.side) return ConnectCheck.SameSide(a.side) val (from, to) = if (a.side == PinSide.OUT) a to b else b to a val fromPin = pin(from, lookup) ?: return ConnectCheck.MissingPin@@ -109,7 +160,11 @@ data class Circuit( } /** Wires [a] to [b] in whichever direction is valid, replacing any wire already on the input. */- fun connect(a: PinRef, b: PinRef, lookup: PinLookup): Circuit? {+ fun connect(+ a: PinRef,+ b: PinRef,+ lookup: PinLookup,+ ): Circuit? { val ok = check(a, b, lookup) as? ConnectCheck.Ok ?: return null return copy(wires = wires.filterNot { it.to == ok.wire.to } + ok.wire) }@@ -119,14 +174,18 @@ data class Circuit( * wires to missing pins or of mismatched width, and second wires into one input. Also makes * sure every level input/output node exists. */- fun sanitized(io: LevelIo, lookup: PinLookup): Circuit {+ fun sanitized(+ io: LevelIo,+ lookup: PinLookup,+ ): Circuit { val withIo = withLevelIo(io) val keptNodes = withIo.nodes.filter { lookup.pins(it) != null } val base = withIo.copy(nodes = keptNodes) val seenInputs = HashSet<PinRef>()- val keptWires = base.wires.filter { w ->- base.check(w.from, w.to, lookup) == ConnectCheck.Ok(w) && seenInputs.add(w.to)- }+ val keptWires =+ base.wires.filter { w ->+ base.check(w.from, w.to, lookup) == ConnectCheck.Ok(w) && seenInputs.add(w.to)+ } val maxId = keptNodes.maxOfOrNull { it.id.raw } ?: -1 return base.copy(wires = keptWires, nextId = maxOf(base.nextId, maxId + 1)) }@@ -138,19 +197,22 @@ data class Circuit( // A stale save can carry a nextId that is already taken by an existing node; fresh // level pins must be allocated above every id present, never on top of one. var next = maxOf(nextId, (nodes.maxOfOrNull { it.id.raw } ?: -1) + 1)- val missing = fresh.nodes.filter {- (it is LevelInput && it.index !in inIdx) || (it is LevelOutput && it.index !in outIdx)- }.map { n ->- val id = NodeId(next++)- when (n) {- is LevelInput -> n.copy(id = id)- is LevelOutput -> n.copy(id = id)- is Gate -> n+ val missing =+ fresh.nodes+ .filter {+ (it is LevelInput && it.index !in inIdx) || (it is LevelOutput && it.index !in outIdx)+ }.map { n ->+ val id = NodeId(next++)+ when (n) {+ is LevelInput -> n.copy(id = id)+ is LevelOutput -> n.copy(id = id)+ is Gate -> n+ }+ }+ val pruned =+ nodes.filterNot {+ (it is LevelInput && it.index >= io.inputs.size) || (it is LevelOutput && it.index >= io.outputs.size) }- }- val pruned = nodes.filterNot {- (it is LevelInput && it.index >= io.inputs.size) || (it is LevelOutput && it.index >= io.outputs.size)- } return copy(nodes = pruned + missing, nextId = next) } @@ -162,15 +224,20 @@ data class Circuit( /** An empty board with the level's inputs down the left and outputs down the right. */ fun forLevel(io: LevelIo): Circuit { var id = 0- val ins = io.inputs.indices.map { i ->- LevelInput(NodeId(id++), i, Point(0f, column(i, io.inputs.size)))- }- val outs = io.outputs.indices.map { i ->- LevelOutput(NodeId(id++), i, Point(OUTPUT_X, column(i, io.outputs.size)))- }+ val ins =+ io.inputs.indices.map { i ->+ LevelInput(NodeId(id++), i, Point(0f, column(i, io.inputs.size)))+ }+ val outs =+ io.outputs.indices.map { i ->+ LevelOutput(NodeId(id++), i, Point(OUTPUT_X, column(i, io.outputs.size)))+ } return Circuit(nodes = ins + outs, nextId = id) } - private fun column(i: Int, n: Int) = (i - (n - 1) / 2f) * IO_SPACING+ private fun column(+ i: Int,+ n: Int,+ ) = (i - (n - 1) / 2f) * IO_SPACING } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.ktindex 715fada637..fea6a5dd6f 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.kt@@ -11,25 +11,30 @@ data class CustomChip( val board: Board, ) { val inputNodes: List<LevelInput>- get() = board.circuit.nodes.filterIsInstance<LevelInput>()- .filter { it.index in board.io.inputs.indices }- .sortedWith(BOARD_ORDER)+ get() =+ board.circuit.nodes+ .filterIsInstance<LevelInput>()+ .filter { it.index in board.io.inputs.indices }+ .sortedWith(BOARD_ORDER) val outputNodes: List<LevelOutput>- get() = board.circuit.nodes.filterIsInstance<LevelOutput>()- .filter { it.index in board.io.outputs.indices }- .sortedWith(BOARD_ORDER)+ get() =+ board.circuit.nodes+ .filterIsInstance<LevelOutput>()+ .filter { it.index in board.io.outputs.indices }+ .sortedWith(BOARD_ORDER) val inputs: List<Pin> get() = inputNodes.map { board.io.inputs[it.index] } val outputs: List<Pin> get() = outputNodes.map { board.io.outputs[it.index] } - fun toSpec(nandCost: Int): ChipSpec = ChipSpec(- id = id,- inputs = inputs,- outputs = outputs,- nandCost = nandCost,- behavior = Behavior.Composite(board.circuit, inputNodes.map { it.id }, outputNodes.map { it.id }),- )+ fun toSpec(nandCost: Int): ChipSpec =+ ChipSpec(+ id = id,+ inputs = inputs,+ outputs = outputs,+ nandCost = nandCost,+ behavior = Behavior.Composite(board.circuit, inputNodes.map { it.id }, outputNodes.map { it.id }),+ ) /** Ids and naming. */ companion object {@@ -46,8 +51,14 @@ data class CustomChip( * How [old]'s chip pins moved in [new]: for each old input/output position, its new position or * -1 when the pin is gone. Null when nothing moved. */-fun pinRemap(old: CustomChip, new: CustomChip): Pair<IntArray, IntArray>? {- fun map(before: List<Node>, after: List<Node>): IntArray {+fun pinRemap(+ old: CustomChip,+ new: CustomChip,+): Pair<IntArray, IntArray>? {+ fun map(+ before: List<Node>,+ after: List<Node>,+ ): IntArray { val pos = after.withIndex().associate { (i, n) -> n.id to i } return IntArray(before.size) { pos[before[it].id] ?: -1 } }@@ -61,14 +72,19 @@ fun pinRemap(old: CustomChip, new: CustomChip): Pair<IntArray, IntArray>? { * Rewires every [chipId] gate after its pins moved: [inMap]/[outMap] give each old pin index its * new one (-1 drops the wire). */-fun Circuit.remapChipPins(chipId: String, inMap: IntArray, outMap: IntArray): Circuit {+fun Circuit.remapChipPins(+ chipId: String,+ inMap: IntArray,+ outMap: IntArray,+): Circuit { val gates = nodes.filter { it is Gate && it.chipId == chipId }.map { it.id }.toSet() if (gates.isEmpty()) return this- val rewired = wires.mapNotNull { w ->- val from = if (w.from.node in gates) w.from.copy(index = outMap.getOrElse(w.from.index) { -1 }) else w.from- val to = if (w.to.node in gates) w.to.copy(index = inMap.getOrElse(w.to.index) { -1 }) else w.to- if (from.index < 0 || to.index < 0) null else Wire(from, to)- }+ val rewired =+ wires.mapNotNull { w ->+ val from = if (w.from.node in gates) w.from.copy(index = outMap.getOrElse(w.from.index) { -1 }) else w.from+ val to = if (w.to.node in gates) w.to.copy(index = inMap.getOrElse(w.to.index) { -1 }) else w.to+ if (from.index < 0 || to.index < 0) null else Wire(from, to)+ } return copy(wires = rewired) } @@ -88,6 +104,9 @@ object PinChips { fun width(chipId: String): Int = chipId.substringAfterLast(':').toIntOrNull() ?: 1 - private fun spec(id: String, inputs: List<Pin>, outputs: List<Pin>) =- ChipSpec(id, inputs, outputs, 0, Behavior.Comb { IntArray(outputs.size) })+ private fun spec(+ id: String,+ inputs: List<Pin>,+ outputs: List<Pin>,+ ) = ChipSpec(id, inputs, outputs, 0, Behavior.Comb { IntArray(outputs.size) }) }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.ktindex 77790e4660..4c0cf442ed 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Isa.kt@@ -18,24 +18,44 @@ object Isa { private const val ALU_SUB = 1 private const val ALU_PASS_B = 3 - val decoderOutputs: List<Pin> = listOf(- Pin("aluOp1"), Pin("aluOp0"), Pin("accLoad"), Pin("memWrite"), Pin("useImm"), Pin("jump"), Pin("halt"),- )+ val decoderOutputs: List<Pin> =+ listOf(+ Pin("aluOp1"),+ Pin("aluOp0"),+ Pin("accLoad"),+ Pin("memWrite"),+ Pin("useImm"),+ Pin("jump"),+ Pin("halt"),+ ) - val cpuOutputs: List<Pin> = listOf(- Pin("pc", 4), Pin("addr", 4), Pin("dout", 8), Pin("we"), Pin("acc", 8), Pin("halt"),- )+ val cpuOutputs: List<Pin> =+ listOf(+ Pin("pc", 4),+ Pin("addr", 4),+ Pin("dout", 8),+ Pin("we"),+ Pin("acc", 8),+ Pin("halt"),+ ) - fun encode(op: Int, operand: Int = 0): Int = (op shl 4) or (operand and 0xF)+ fun encode(+ op: Int,+ operand: Int = 0,+ ): Int = (op shl 4) or (operand and 0xF) /** Control lines for [op] (the top bit is ignored) given the accumulator-zero flag [z]. */- fun decode(op: Int, z: Int): IntArray {+ fun decode(+ op: Int,+ z: Int,+ ): IntArray { val o = op and 7- val aluOp = when (o) {- LDA, LDI -> ALU_PASS_B- SUB -> ALU_SUB- else -> ALU_ADD- }+ val aluOp =+ when (o) {+ LDA, LDI -> ALU_PASS_B+ SUB -> ALU_SUB+ else -> ALU_ADD+ } return intArrayOf( aluOp shr 1, aluOp and 1,@@ -47,13 +67,22 @@ object Isa { ) } - fun cpuOut(pc: Int, acc: Int, instr: Int): IntArray {+ fun cpuOut(+ pc: Int,+ acc: Int,+ instr: Int,+ ): IntArray { val o = (instr shr 4) and 7 return intArrayOf(pc, instr and 0xF, acc, bit(o == STA), acc, bit(o == HLT)) } /** Next `[pc, acc]` after executing [instr] with [data] read from its operand address. */- fun cpuNext(pc: Int, acc: Int, instr: Int, data: Int): IntArray {+ fun cpuNext(+ pc: Int,+ acc: Int,+ instr: Int,+ data: Int,+ ): IntArray { val c = decode(instr shr 4, bit(acc == 0)) val operand = instr and 0xF val b = if (c[4] == 1) operand else data
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.ktindex 853cdc6f3f..360ce4c737 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ValueFormat.kt@@ -1,7 +1,10 @@ package com.vayunmathur.games.logicgate.domain.model /** Signal text: 1-bit as 0/1, buses as zero-padded upper-case hex (one digit per nibble). */-fun formatValue(value: Int, width: Int): String =+fun formatValue(+ value: Int,+ width: Int,+): String = // Widths come from persisted sandbox components; a corrupt width // must not turn padStart negative and crash rendering. if (width <= 1) value.toString() else value.toString(HEX).uppercase().padStart((width + 3) / 4, '0')
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.ktindex 9a2e63d665..ab2c0d70cb 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.kt@@ -28,8 +28,10 @@ internal class Flattened( * keep their ids. A wire chased through ports into a loop with no gate on it reads 0. */ internal object Flattener {-- fun flatten(circuit: Circuit, catalog: (String) -> ChipSpec?): Flattened {+ fun flatten(+ circuit: Circuit,+ catalog: (String) -> ChipSpec?,+ ): Flattened { val composite = circuit.nodes.any { it is Gate && catalog(it.chipId)?.behavior is Behavior.Composite } if (!composite) return Flattened(circuit, emptyMap(), emptyMap()) return Builder(circuit, catalog).build()@@ -45,7 +47,10 @@ internal object Flattener { val chain: Set<String>, ) - private class Builder(private val top: Circuit, private val catalog: (String) -> ChipSpec?) {+ private class Builder(+ private val top: Circuit,+ private val catalog: (String) -> ChipSpec?,+ ) { private val insts = mutableListOf<Inst>() private val flatId = HashMap<Pair<Int, NodeId>, NodeId>() private val children = HashMap<Pair<Int, NodeId>, Inst>()@@ -56,12 +61,13 @@ internal object Flattener { fun build(): Flattened { val root = Inst(0, top, null, null, null, null, emptySet()).also { insts += it } collect(root)- val wires = insts.flatMap { inst ->- inst.circuit.wires.mapNotNull { w ->- val to = flatId[inst.key to w.to.node] ?: return@mapNotNull null- resolve(inst, w.from, HashSet())?.let { Wire(it, PinRef(to, PinSide.IN, w.to.index)) }+ val wires =+ insts.flatMap { inst ->+ inst.circuit.wires.mapNotNull { w ->+ val to = flatId[inst.key to w.to.node] ?: return@mapNotNull null+ resolve(inst, w.from, HashSet())?.let { Wire(it, PinRef(to, PinSide.IN, w.to.index)) }+ } }- } val aliases = HashMap<PinRef, PinRef>() for (n in top.nodes) { val ports = children[0 to n.id]?.ports ?: continue@@ -85,10 +91,16 @@ internal object Flattener { ports == null -> place(inst, n, if (nested) NodeId(next++) else n.id) n.chipId in inst.chain || inst.chain.size >= MAX_DEPTH -> Unit else -> {- val child = Inst(- insts.size, ports.circuit, inst, n, ports,- inst.owner ?: n.id, inst.chain + n.chipId,- )+ val child =+ Inst(+ insts.size,+ ports.circuit,+ inst,+ n,+ ports,+ inst.owner ?: n.id,+ inst.chain + n.chipId,+ ) insts += child children[inst.key to n.id] = child collect(child)@@ -99,17 +111,26 @@ internal object Flattener { } } - private fun place(inst: Inst, n: Node, id: NodeId) {+ private fun place(+ inst: Inst,+ n: Node,+ id: NodeId,+ ) { flatId[inst.key to n.id] = id- nodes += when (n) {- is Gate -> n.copy(id = id)- else -> n- }+ nodes +=+ when (n) {+ is Gate -> n.copy(id = id)+ else -> n+ } inst.owner?.let { owner[id] = it } } /** The flat output pin that ultimately drives [ref], an output pin in [inst]'s circuit. */- private fun resolve(inst: Inst, ref: PinRef, seen: MutableSet<Triple<Int, NodeId, Int>>): PinRef? {+ private fun resolve(+ inst: Inst,+ ref: PinRef,+ seen: MutableSet<Triple<Int, NodeId, Int>>,+ ): PinRef? { if (!seen.add(Triple(inst.key, ref.node, ref.index))) return null val flat = flatId[inst.key to ref.node] val child = children[inst.key to ref.node]@@ -123,15 +144,26 @@ internal object Flattener { } /** The pin inside [child] wired to its output port [k]. */- private fun driverOfOutput(child: Inst, k: Int): PinRef? {+ private fun driverOfOutput(+ child: Inst,+ k: Int,+ ): PinRef? { val port = child.ports?.outputNodes?.getOrNull(k) ?: return null return child.circuit.wireInto(PinRef(port, PinSide.IN, 0))?.from } /** The pin in [parent] wired to the chip input that [inst]'s input node [node] stands for. */- private fun driverOfInput(inst: Inst, parent: Inst, node: NodeId): PinRef? {+ private fun driverOfInput(+ inst: Inst,+ parent: Inst,+ node: NodeId,+ ): PinRef? { val gate = inst.gate ?: return null- val k = inst.ports?.inputNodes?.indexOf(node)?.takeIf { it >= 0 } ?: return null+ val k =+ inst.ports+ ?.inputNodes+ ?.indexOf(node)+ ?.takeIf { it >= 0 } ?: return null return parent.circuit.wireInto(PinRef(gate.id, PinSide.IN, k))?.from } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.ktindex 3260afa9c7..9c34e5f253 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scheduler.kt@@ -2,12 +2,15 @@ package com.vayunmathur.games.logicgate.domain.sim /** Orders a dependency graph into strongly connected groups, sources first (Tarjan). */ internal object Scheduler {- /** * Groups nodes `0 until n` (except [excluded]) so every group only depends on groups before * it. Each entry is `(members in index order, isCyclic)`. */- fun groups(n: Int, edges: List<Pair<Int, Int>>, excluded: Set<Int>): List<Pair<IntArray, Boolean>> {+ fun groups(+ n: Int,+ edges: List<Pair<Int, Int>>,+ excluded: Set<Int>,+ ): List<Pair<IntArray, Boolean>> { val adj = Array(n) { mutableListOf<Int>() } val selfLoop = BooleanArray(n) for ((a, b) in edges) {@@ -22,7 +25,10 @@ internal object Scheduler { } } - private class Tarjan(n: Int, val adj: Array<MutableList<Int>>) {+ private class Tarjan(+ n: Int,+ val adj: Array<MutableList<Int>>,+ ) { val index = IntArray(n) { -1 } val low = IntArray(n) val onStack = BooleanArray(n)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.ktindex 6ab5e96252..a754dda87d 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Scoring.kt@@ -5,15 +5,21 @@ import com.vayunmathur.games.logicgate.domain.model.Gate /** Circuit cost and star rating. */ object Scoring {-- fun cost(circuit: Circuit, nandCost: (String) -> Int?): Int =- circuit.nodes.sumOf { (it as? Gate)?.let { g -> nandCost(g.chipId) } ?: 0 }+ fun cost(+ circuit: Circuit,+ nandCost: (String) -> Int?,+ ): Int = circuit.nodes.sumOf { (it as? Gate)?.let { g -> nandCost(g.chipId) } ?: 0 } /** ★ solved, ★★ within 1.5× par, ★★★ at or under par; 0 when unsolved. */- fun stars(solved: Boolean, cost: Int, par: Int): Int = when {- !solved -> 0- cost <= par -> 3- cost * 2 <= par * 3 -> 2- else -> 1- }+ fun stars(+ solved: Boolean,+ cost: Int,+ par: Int,+ ): Int =+ when {+ !solved -> 0+ cost <= par -> 3+ cost * 2 <= par * 3 -> 2+ else -> 1+ } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.ktindex 42d10255e5..24f143d058 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt@@ -50,10 +50,11 @@ class Simulator( init { val lookup = Chips.lookup(io) val empty = NodePins(emptyList(), emptyList())- val pins = nodes.mapIndexed { i, n ->- val spec = specs[i]- if (n is Gate) NodePins(spec?.inputs.orEmpty(), spec?.outputs.orEmpty()) else lookup.pins(n) ?: empty- }+ val pins =+ nodes.mapIndexed { i, n ->+ val spec = specs[i]+ if (n is Gate) NodePins(spec?.inputs.orEmpty(), spec?.outputs.orEmpty()) else lookup.pins(n) ?: empty+ } inPins = Array(nodes.size) { pins[it].inputs } outPins = Array(nodes.size) { pins[it].outputs } outBase = IntArray(nodes.size)@@ -83,7 +84,10 @@ class Simulator( reset() } - private fun edges(index: Map<NodeId, Int>, circuit: Circuit): List<Pair<Int, Int>> =+ private fun edges(+ index: Map<NodeId, Int>,+ circuit: Circuit,+ ): List<Pair<Int, Int>> = circuit.wires.mapNotNull { w -> val a = index[w.from.node] ?: return@mapNotNull null val b = index[w.to.node] ?: return@mapNotNull null@@ -126,10 +130,11 @@ class Simulator( } /** Level output values from the last [settle]. */- fun outputs(): IntArray = IntArray(outputNodes.size) { o ->- val node = outputNodes[o]- if (node < 0) 0 else read(node, 0)- }+ fun outputs(): IntArray =+ IntArray(outputNodes.size) { o ->+ val node = outputNodes[o]+ if (node < 0) 0 else read(node, 0)+ } /** Latches every sequential chip from the settled values. */ fun clock() {@@ -149,7 +154,10 @@ class Simulator( } /** Overwrites the state of every [chipId] chip, e.g. to load a program into RAM. */- fun preload(chipId: String, data: IntArray) {+ fun preload(+ chipId: String,+ data: IntArray,+ ) { for (i in nodes.indices) { if (specs[i]?.id == chipId) states[i] = data.copyOf() }@@ -170,7 +178,10 @@ class Simulator( return map } - private fun read(node: Int, pin: Int): Int {+ private fun read(+ node: Int,+ pin: Int,+ ): Int { val src = inSrc[node][pin] return if (src < 0) 0 else values[src] and inPins[node][pin].mask }@@ -183,15 +194,17 @@ class Simulator( private fun evaluate(i: Int): Boolean { val node = nodes[i]- val out: IntArray = when (node) {- is LevelInput -> intArrayOf(levelInputs.getOrElse(node.index) { 0 })- is LevelOutput -> return false- is Gate -> when (val b = specs[i]?.behavior ?: return false) {- is Behavior.Comb -> b.eval(gather(i))- is Behavior.Seq -> b.outputs(states[i] ?: b.init, gather(i))- is Behavior.Composite -> return false+ val out: IntArray =+ when (node) {+ is LevelInput -> intArrayOf(levelInputs.getOrElse(node.index) { 0 })+ is LevelOutput -> return false+ is Gate ->+ when (val b = specs[i]?.behavior ?: return false) {+ is Behavior.Comb -> b.eval(gather(i))+ is Behavior.Seq -> b.outputs(states[i] ?: b.init, gather(i))+ is Behavior.Composite -> return false+ } }- } var changed = false val base = outBase[i] val pins = outPins[i]@@ -206,7 +219,10 @@ class Simulator( } /** Outputs of one tick, read after settling and before the clock edge. */- class Step(val outputs: IntArray, val oscillating: Set<NodeId>)+ class Step(+ val outputs: IntArray,+ val oscillating: Set<NodeId>,+ ) /** Simulator limits. */ companion object {
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.ktindex 544b529d35..14d948ca0a 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/TestSpec.kt@@ -4,23 +4,39 @@ package com.vayunmathur.games.logicgate.domain.sim * One row of a test: the level inputs to drive, the outputs expected (null = don't care), and a * plain-language [title] such as `1 OR 1 = 1`. */-data class Case(val inputs: List<Int>, val expected: List<Int?>, val title: String)+data class Case(+ val inputs: List<Int>,+ val expected: List<Int?>,+ val title: String,+) /** A program run on the finished CPU: 16 bytes of RAM, a tick budget, and the answer in `acc`. */-data class ProgramTest(val name: String, val ram: List<Int>, val maxTicks: Int, val expectAcc: Int)+data class ProgramTest(+ val name: String,+ val ram: List<Int>,+ val maxTicks: Int,+ val expectAcc: Int,+) /** How a level is checked. */ sealed interface TestSpec { /** Each case is settled from reset on its own. */- data class Comb(val cases: List<Case>) : TestSpec+ data class Comb(+ val cases: List<Case>,+ ) : TestSpec /** Ticks run in order on one simulator, from reset. */- data class Seq(val ticks: List<Case>) : TestSpec+ data class Seq(+ val ticks: List<Case>,+ ) : TestSpec /** * Each program runs from reset until `halt`. With [harness] the circuit is a CPU whose * `instr`/`data` inputs are fed from a RAM model driven by its `pc`/`addr`/`dout`/`we` * outputs; without it the circuit must contain its own RAM16, which gets the program. */- data class Programs(val programs: List<ProgramTest>, val harness: Boolean) : TestSpec+ data class Programs(+ val programs: List<ProgramTest>,+ val harness: Boolean,+ ) : TestSpec }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.ktindex 8e5d7f1d2d..3beb0e9f90 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt@@ -17,7 +17,7 @@ data class CaseResult( ) /** Why a level could not even be run. */-enum class VerifyProblem { NO_RAM }+enum class VerifyProblem { NO_RAM, } /** Every row's outcome plus anything that stopped the circuit from settling. */ data class VerifyResult(@@ -33,11 +33,13 @@ data class VerifyResult( } /** Live wire values for one moment of a run, for the canvas. */-data class Probe(val values: Map<PinRef, Int>, val oscillating: Set<NodeId>)+data class Probe(+ val values: Map<PinRef, Int>,+ val oscillating: Set<NodeId>,+) /** Runs a level's tests against a player's circuit. */ object Verifier {- fun verify( io: LevelIo, tests: TestSpec,@@ -74,72 +76,94 @@ object Verifier { catalog: (String) -> ChipSpec? = Chips::get, ): Probe { val sim = Simulator(circuit, io, catalog)- val osc: Set<NodeId> = when (tests) {- is TestSpec.Comb -> {- sim.setInputs(tests.cases[caseIndex].inputs.toIntArray())- sim.settle()- }- is TestSpec.Seq -> {- for (t in 0 until caseIndex) sim.step(tests.ticks[t].inputs.toIntArray())- sim.setInputs(tests.ticks[caseIndex].inputs.toIntArray())- sim.settle()+ val osc: Set<NodeId> =+ when (tests) {+ is TestSpec.Comb -> {+ sim.setInputs(tests.cases[caseIndex].inputs.toIntArray())+ sim.settle()+ }+ is TestSpec.Seq -> {+ for (t in 0 until caseIndex) sim.step(tests.ticks[t].inputs.toIntArray())+ sim.setInputs(tests.ticks[caseIndex].inputs.toIntArray())+ sim.settle()+ }+ is TestSpec.Programs -> run(sim, io, tests.programs[caseIndex], tests.harness).oscillating }- is TestSpec.Programs -> run(sim, io, tests.programs[caseIndex], tests.harness).oscillating- } return Probe(sim.pinValues(), osc) } - private fun matches(expected: List<Int?>, actual: IntArray): Boolean =- expected.indices.all { k -> expected[k] == null || expected[k] == actual.getOrNull(k) }+ private fun matches(+ expected: List<Int?>,+ actual: IntArray,+ ): Boolean = expected.indices.all { k -> expected[k] == null || expected[k] == actual.getOrNull(k) } - private fun verifyComb(sim: Simulator, tests: TestSpec.Comb): VerifyResult {+ private fun verifyComb(+ sim: Simulator,+ tests: TestSpec.Comb,+ ): VerifyResult { val osc = LinkedHashSet<NodeId>()- val results = tests.cases.map { c ->- sim.reset()- sim.setInputs(c.inputs.toIntArray())- val o = sim.settle()- osc += o- val out = sim.outputs()- CaseResult(c.title, c.inputs, c.expected, out.toList(), o.isEmpty() && matches(c.expected, out))- }+ val results =+ tests.cases.map { c ->+ sim.reset()+ sim.setInputs(c.inputs.toIntArray())+ val o = sim.settle()+ osc += o+ val out = sim.outputs()+ CaseResult(c.title, c.inputs, c.expected, out.toList(), o.isEmpty() && matches(c.expected, out))+ } return VerifyResult(results, osc) } - private fun verifySeq(sim: Simulat
Diff truncated.