Snake Game Food Updation Working Randomly in ViewModel Coroutine

I’m trynna build a basic snake game for android. Everything is working just fine except for the food updation. It is working randomly, sometimes when you eat it, new food appears, sometimes literally nothing happens, and sometimes, when you pass from right next to the food, it gets considered as eating it, and sometimes the food just doesn’t appear on the screen until a few seconds pass by.

The whole project is uploaded on: https://github.com/tauqirnizami/SnakeGame

ViewModel file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var foodCoordinates: Pair<Int, Int> = Pair(14, 13)
var score = 0L
var direction = 0
var giantFoodCoordinates: Pair<Int, Int>? = null
var giantFoodCounter: Int = 0
class SnakeViewModel() : ViewModel() {
/*Pair(length/y-coordinate, width/x-coordinate)*/
var coordinates = mutableStateListOf(Pair(16, 17), Pair(17, 17), Pair(18, 17))
private set
private var delayInMillis: Long = 500L
private var gameGoing by mutableStateOf(true)
private fun delayChange() {/*TODO*/
delayInMillis = if (score == 0L) 500 else if (score <= 500) 500 / score else 0
}
init {
viewModelScope.launch(Dispatchers.Default) {
delay(1000L)
while (gameGoing) {
delay(delayInMillis)
delayChange()
coordinatesUpdation()
}
}
}
private suspend fun coordinatesUpdation() {
// Compute the new head position based on the direction
val head = coordinates.first()
val newHead = when (direction) {
0 -> Pair(if (head.first > 1) head.first - 1 else gridLength, head.second) // UP
1 -> Pair(if (head.first < gridLength) head.first + 1 else 1, head.second) // DOWN
2 -> Pair(head.first, if (head.second > 1) head.second - 1 else gridWidth) // LEFT
else -> Pair(head.first, if (head.second < gridWidth) head.second + 1 else 1) // RIGHT
}
// Update the coordinates with the new head and shift the body
coordinates.add(0, newHead)
coordinates.removeLast()
//Eating Food
if (newHead == foodCoordinates) {
foodCoordinates = food(giantFoodCoordinates)
score++
giantFoodCounter++
val tail = coordinates.last()
coordinates.add(tail)
}
if (coordinates.drop(1).any { it == newHead }) {
gameGoing = false
}
if (giantFoodCounter % 8 == 0 && giantFoodCounter!=0) {
giantFoodCoordinates = food(foodCoordinates)
viewModelScope.launch(Dispatchers.Default) {
delay((if (score < 30) 15 else if (score < 100) 10 else if (score < 300) 6 else 4) * 1000L)
giantFoodCoordinates = null
giantFoodCounter = 0
}
}
if (newHead == giantFoodCoordinates) {
giantFoodCounter = 0
score += 5
var tail = coordinates.last()
coordinates.add(tail)
tail = coordinates.last()
coordinates.add(tail)
tail = coordinates.last()
coordinates.add(tail)
tail = coordinates.last()
coordinates.add(tail)
tail = coordinates.last()
coordinates.add(tail)
}
}
private fun food(otherFood: Pair<Int, Int>?): Pair<Int, Int> {
var a: Pair<Int, Int>
do {
a = Pair((1..gridLength).random(), (1..gridWidth).random())
} while (coordinates.any { it == a } || otherFood == a)
return a
}
}
</code>
<code>var foodCoordinates: Pair<Int, Int> = Pair(14, 13) var score = 0L var direction = 0 var giantFoodCoordinates: Pair<Int, Int>? = null var giantFoodCounter: Int = 0 class SnakeViewModel() : ViewModel() { /*Pair(length/y-coordinate, width/x-coordinate)*/ var coordinates = mutableStateListOf(Pair(16, 17), Pair(17, 17), Pair(18, 17)) private set private var delayInMillis: Long = 500L private var gameGoing by mutableStateOf(true) private fun delayChange() {/*TODO*/ delayInMillis = if (score == 0L) 500 else if (score <= 500) 500 / score else 0 } init { viewModelScope.launch(Dispatchers.Default) { delay(1000L) while (gameGoing) { delay(delayInMillis) delayChange() coordinatesUpdation() } } } private suspend fun coordinatesUpdation() { // Compute the new head position based on the direction val head = coordinates.first() val newHead = when (direction) { 0 -> Pair(if (head.first > 1) head.first - 1 else gridLength, head.second) // UP 1 -> Pair(if (head.first < gridLength) head.first + 1 else 1, head.second) // DOWN 2 -> Pair(head.first, if (head.second > 1) head.second - 1 else gridWidth) // LEFT else -> Pair(head.first, if (head.second < gridWidth) head.second + 1 else 1) // RIGHT } // Update the coordinates with the new head and shift the body coordinates.add(0, newHead) coordinates.removeLast() //Eating Food if (newHead == foodCoordinates) { foodCoordinates = food(giantFoodCoordinates) score++ giantFoodCounter++ val tail = coordinates.last() coordinates.add(tail) } if (coordinates.drop(1).any { it == newHead }) { gameGoing = false } if (giantFoodCounter % 8 == 0 && giantFoodCounter!=0) { giantFoodCoordinates = food(foodCoordinates) viewModelScope.launch(Dispatchers.Default) { delay((if (score < 30) 15 else if (score < 100) 10 else if (score < 300) 6 else 4) * 1000L) giantFoodCoordinates = null giantFoodCounter = 0 } } if (newHead == giantFoodCoordinates) { giantFoodCounter = 0 score += 5 var tail = coordinates.last() coordinates.add(tail) tail = coordinates.last() coordinates.add(tail) tail = coordinates.last() coordinates.add(tail) tail = coordinates.last() coordinates.add(tail) tail = coordinates.last() coordinates.add(tail) } } private fun food(otherFood: Pair<Int, Int>?): Pair<Int, Int> { var a: Pair<Int, Int> do { a = Pair((1..gridLength).random(), (1..gridWidth).random()) } while (coordinates.any { it == a } || otherFood == a) return a } } </code>
var foodCoordinates: Pair<Int, Int> = Pair(14, 13)
var score = 0L
var direction = 0
var giantFoodCoordinates: Pair<Int, Int>? = null
var giantFoodCounter: Int = 0

class SnakeViewModel() : ViewModel() {
    /*Pair(length/y-coordinate, width/x-coordinate)*/
    var coordinates = mutableStateListOf(Pair(16, 17), Pair(17, 17), Pair(18, 17))
        private set

    private var delayInMillis: Long = 500L

    private var gameGoing by mutableStateOf(true)


    private fun delayChange() {/*TODO*/
        delayInMillis = if (score == 0L) 500 else if (score <= 500) 500 / score else 0
    }


    init {
        viewModelScope.launch(Dispatchers.Default) {
            delay(1000L)
            while (gameGoing) {
                delay(delayInMillis)
                delayChange()
                coordinatesUpdation()
            }
        }
    }

    private suspend fun coordinatesUpdation() {

        // Compute the new head position based on the direction
        val head = coordinates.first()
        val newHead = when (direction) {
            0 -> Pair(if (head.first > 1) head.first - 1 else gridLength, head.second) // UP
            1 -> Pair(if (head.first < gridLength) head.first + 1 else 1, head.second) // DOWN
            2 -> Pair(head.first, if (head.second > 1) head.second - 1 else gridWidth) // LEFT
            else -> Pair(head.first, if (head.second < gridWidth) head.second + 1 else 1) // RIGHT
        }

        // Update the coordinates with the new head and shift the body
        coordinates.add(0, newHead)
        coordinates.removeLast()

        //Eating Food
        if (newHead == foodCoordinates) {
            foodCoordinates = food(giantFoodCoordinates)
            score++
            giantFoodCounter++
            val tail = coordinates.last()
            coordinates.add(tail)
        }

        if (coordinates.drop(1).any { it == newHead }) {
            gameGoing = false
        }

        if (giantFoodCounter % 8 == 0 && giantFoodCounter!=0) {
            giantFoodCoordinates = food(foodCoordinates)
            viewModelScope.launch(Dispatchers.Default) {
                delay((if (score < 30) 15 else if (score < 100) 10 else if (score < 300) 6 else 4) * 1000L)
                giantFoodCoordinates = null
                giantFoodCounter = 0
            }
        }

        if (newHead == giantFoodCoordinates) {
            giantFoodCounter = 0
            score += 5
            var tail = coordinates.last()
            coordinates.add(tail)

            tail = coordinates.last()
            coordinates.add(tail)

            tail = coordinates.last()
            coordinates.add(tail)

            tail = coordinates.last()
            coordinates.add(tail)

            tail = coordinates.last()
            coordinates.add(tail)
        }
    }

    private fun food(otherFood: Pair<Int, Int>?): Pair<Int, Int> {
        var a: Pair<Int, Int>
        do {
            a = Pair((1..gridLength).random(), (1..gridWidth).random())
        } while (coordinates.any { it == a } || otherFood == a)
        return a
    }
}

and the composable file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>val gridWidth: Int = 20
val gridLength: Int = 35
@Composable
fun DisplayGrid(
modifier: Modifier,
snakeViewModel: SnakeViewModel
) {
val colors = generateColorGrid(coordinates = snakeViewModel.coordinates)
ColorGrid(colors, gridWidth, modifier = modifier, cellSize = 18.dp)
}
@Composable
fun Screen(
modifier: Modifier = Modifier,
snakeViewModel: SnakeViewModel = SnakeViewModel()
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
) {
DisplayGrid(modifier, snakeViewModel = snakeViewModel)
Row(
modifier = Modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
//Buttns and score display
}
}
}
fun generateColorGrid(coordinates: List<Pair<Int, Int>>): List<Color> {
val coloursList: MutableList<Color> = mutableListOf()
for (i in 1..gridLength) {
for (j in 1..gridWidth) {
if (coordinates.any { it == Pair(i, j) }) {
coloursList.add(Color.White)
} else if (Pair(j, i) == foodCoordinates) {
coloursList.add(Color.LightGray)
} else if (Pair(j, i) == giantFoodCoordinates) {
coloursList.add(Color.DarkGray)
} else {
coloursList.add(Color.Yellow)
}
}
}
return coloursList
}
@Composable
fun ColorGrid(colors: List<Color>, width: Int, cellSize: Dp, modifier: Modifier = Modifier) {
LazyVerticalGrid(
columns = GridCells.Fixed(width),
modifier = modifier
) {
items(colors) { color ->
Box(
modifier = Modifier
.size(cellSize) // Sets the size of each cell
.background(color)
)
}
}
}
</code>
<code>val gridWidth: Int = 20 val gridLength: Int = 35 @Composable fun DisplayGrid( modifier: Modifier, snakeViewModel: SnakeViewModel ) { val colors = generateColorGrid(coordinates = snakeViewModel.coordinates) ColorGrid(colors, gridWidth, modifier = modifier, cellSize = 18.dp) } @Composable fun Screen( modifier: Modifier = Modifier, snakeViewModel: SnakeViewModel = SnakeViewModel() ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier ) { DisplayGrid(modifier, snakeViewModel = snakeViewModel) Row( modifier = Modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { //Buttns and score display } } } fun generateColorGrid(coordinates: List<Pair<Int, Int>>): List<Color> { val coloursList: MutableList<Color> = mutableListOf() for (i in 1..gridLength) { for (j in 1..gridWidth) { if (coordinates.any { it == Pair(i, j) }) { coloursList.add(Color.White) } else if (Pair(j, i) == foodCoordinates) { coloursList.add(Color.LightGray) } else if (Pair(j, i) == giantFoodCoordinates) { coloursList.add(Color.DarkGray) } else { coloursList.add(Color.Yellow) } } } return coloursList } @Composable fun ColorGrid(colors: List<Color>, width: Int, cellSize: Dp, modifier: Modifier = Modifier) { LazyVerticalGrid( columns = GridCells.Fixed(width), modifier = modifier ) { items(colors) { color -> Box( modifier = Modifier .size(cellSize) // Sets the size of each cell .background(color) ) } } } </code>
val gridWidth: Int = 20
val gridLength: Int = 35

        @Composable
        fun DisplayGrid(
            modifier: Modifier,
            snakeViewModel: SnakeViewModel
        ) {
            val colors = generateColorGrid(coordinates = snakeViewModel.coordinates)
            ColorGrid(colors, gridWidth, modifier = modifier, cellSize = 18.dp)
        }
@Composable
fun Screen(
    modifier: Modifier = Modifier,
    snakeViewModel: SnakeViewModel = SnakeViewModel()
) {
    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = modifier
    ) {

        DisplayGrid(modifier, snakeViewModel = snakeViewModel)

        Row(
            modifier = Modifier,
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Center
        ) {
            //Buttns and score display
        }
    }
}

fun generateColorGrid(coordinates: List<Pair<Int, Int>>): List<Color> {
    val coloursList: MutableList<Color> = mutableListOf()
    for (i in 1..gridLength) {
        for (j in 1..gridWidth) {
            if (coordinates.any { it == Pair(i, j) }) {
                coloursList.add(Color.White)
            } else if (Pair(j, i) == foodCoordinates) {
                coloursList.add(Color.LightGray)
            } else if (Pair(j, i) == giantFoodCoordinates) {
                coloursList.add(Color.DarkGray)
            } else {
                coloursList.add(Color.Yellow)
            }
        }
    }
    return coloursList
}

@Composable
fun ColorGrid(colors: List<Color>, width: Int, cellSize: Dp, modifier: Modifier = Modifier) {
    LazyVerticalGrid(
        columns = GridCells.Fixed(width),
        modifier = modifier
    ) {
        items(colors) { color ->
            Box(
                modifier = Modifier
                    .size(cellSize)  // Sets the size of each cell
                    .background(color)
            )
        }
    }
}

I know my code looks crazy, but I wrote it that way just to prevent as much lag as possible and to make it as optimized as possible. bcz the screen would already be updating many times per second, I thought of doing as much optimization as I could.

I thought this might be due to the coordinatesUpdation() funciton requiring too much time to execute properly, hence I tried to put all the if else blocks from the coordinatesUpdation() function into a separate funciton and run this new funciton in a separate coroutine, but this caused even more harm as now we were reading and updating the ‘coordinates’ variable at the same time!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật