summaryrefslogtreecommitdiff
path: root/app/src/main/java/space/jakob/mines/GameView.kt
diff options
context:
space:
mode:
Diffstat (limited to 'app/src/main/java/space/jakob/mines/GameView.kt')
-rw-r--r--app/src/main/java/space/jakob/mines/GameView.kt41
1 files changed, 27 insertions, 14 deletions
diff --git a/app/src/main/java/space/jakob/mines/GameView.kt b/app/src/main/java/space/jakob/mines/GameView.kt
index 80218ce..36fe2ec 100644
--- a/app/src/main/java/space/jakob/mines/GameView.kt
+++ b/app/src/main/java/space/jakob/mines/GameView.kt
@@ -37,15 +37,34 @@ class GameView(context: Context, attrs: AttributeSet) : View(context, attrs) {
var grid: Grid? = null
- var cameraX = 0.5f
- var cameraY = 0.0f
- var sightX = 5.0f
- var sightY = 5.0f
+ var cameraX = 0.0
+ var cameraY = 0.0
+ var sightX = 5.0
+ var sightY = 5.0
+ val maxCameraX: Double
+ get() = grid?.let {
+ it.width - sightX
+ } ?: 0.0
+ val maxCameraY: Double
+ get() = grid?.let {
+ it.height - sightY
+ } ?: 0.0
+
+ // The size, in pixels, of an individual tile based on the current scale
+ // factor.
val scaledWidth: Int
- get() = width / (sightX - cameraX).toInt()
+ get() = width / sightX.toInt()
val scaledHeight: Int
- get() = height / (sightY - cameraY).toInt()
+ get() = height / sightY.toInt()
+
+ /**
+ * Returns the grid coordinates for the tile at the given screen coordinates.
+ */
+ fun toGridCoordinates(x: Int, y: Int) = Pair(
+ (x + (scaledWidth * (cameraX % 1)).toInt()) / scaledWidth + cameraX.toInt(),
+ (y + (scaledHeight * (cameraY % 1)).toInt()) / scaledHeight + cameraY.toInt()
+ )
private fun atlasRect(entry: AtlasEntry): Rect {
val x = (entry.ordinal % atlasWidth) * tileWidth
@@ -89,8 +108,8 @@ class GameView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private fun drawGrid(canvas: Canvas, grid: Grid) {
val startX = cameraX.toInt() // Truncates the fractional component.
val startY = cameraY.toInt()
- val howManyX = (sightX - cameraX).toInt() + 1
- val howManyY = (sightY - cameraY).toInt() + 1
+ val howManyX = (sightX.toInt() + 1).coerceAtMost(grid.width - startX - 1)
+ val howManyY = (sightY.toInt() + 1).coerceAtMost(grid.height - startY - 1)
for (i in 0..howManyX) {
for (j in 0..howManyY) {
@@ -109,14 +128,8 @@ class GameView(context: Context, attrs: AttributeSet) : View(context, attrs) {
}
}
- fun toGridCoordinates(x: Int, y: Int) = Pair(
- (x + (scaledWidth * (cameraX % 1)).toInt()) / scaledWidth + cameraX.toInt(),
- (y + (scaledHeight * (cameraY % 1)).toInt()) / scaledHeight + cameraY.toInt()
- )
-
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
-
grid?.let {
drawGrid(canvas, it)
}