I'm trying to make my view move in a loop around 4 corners. I did it by having a keyList. Originally my view is constrained to top and left border.
After each click, I update the keylist by removing first index of keyList and move it to the last.
I have this code currently. The view moves fine for the first 4 corners (1 loop) but the app crashed after.
var keyList = arrayListOf(1,2,3,0,1,2,3,0)
val puckMinX = border.minX().toFloat()
val puckMaxX = (border.maxX() - puck.width).toFloat()
val puckMinY= border.minY().toFloat()
val puckMaxY = (border.maxY() - puck.height).toFloat()
fun clickTextView(view: ImageView) {
if (keyList[0] == 0) {
puck.x = puckMinX
puck.y = puckMinY
var holder =keyList[0]
keyList.remove(holder)
keyList+holder}
else if (keyList[0] == 1) {
puck.x = puckMaxX
puck.y = puckMinY
var holder =keyList[0]
keyList
keyList.remove(holder)
keyList+holder}
else if (keyList[0] == 2) {
puck.x = puckMaxX
puck.y = puckMaxY
var holder =keyList[0]
keyList.remove(holder)
keyList+holder}
else if (keyList[0] == 3) {
puck.x = puckMinX
puck.y = puckMaxY
var holder =keyList[0]
keyList.remove(holder)
keyList+holder}
}
//applying lambda to each textview
puck.setOnClickListener { clickTextView(puck) }
Could someone tell me what I did wrong? Or also is there a better way to make my view move in a loop? Any help is appreciated!
EDIT: I found the problem. My list is only removing the first index but not adding the item that's removed back to the list. How do I update my keylist?
You can use add which adds element to end of the list
keyList.add(holder)
Edit
Note that you wont be able to print like println(keyList.add(holder)) because add will return true since it will successfully update the list. So you will have to do
keyList.add(holder)
println(keyList)
I'm trying to make an animation when my silver's user is updated. The problem is that the animation doesn't stop on the right number.
I'm working with firestore so I retreive the silver value from a Snapchat listener.
Since the ValueAnimator doesn't work proprely with big number I don't want animation for number biger than 2 000 000 000.
var oldSilver :Long = 0
var silver_long :Long = 923364963
if (silver_long>2000000000){
silver_textView.setText(DecimalFormat("#,###").format(silver_long))
} else {
startCountAnimationSilver(oldSilver.toInt(),silver_long.toInt(),2000)
}
private fun startCountAnimationSilver(old:Int,new:Int,duration:Int) {
Toast.makeText(applicationContext,"old = $old new = $new",Toast.LENGTH_LONG).show()
val animator = ValueAnimator.ofInt(old, new)
animator.addUpdateListener { animation -> silver_textView.text = DecimalFormat("#,###").format(animation.animatedValue) }
animator.duration = duration.toLong()
animator.start()
}
The Toast in startCountAnimationSilver was just to make sure that i've got the rights parameters.
For exemple if I try right now, the toast shows : old = 0 new = 923364963
But the silver_textView shows : 923 364 992
I am creating a pixel art editor for Android, and as for all pixel art editors, a paint bucket (fill tool) is a must need.
To do this, I did some research on flood fill algorithms online.
I stumbled across the following video which explained how to implement an iterative flood fill algorithm in your code. The code used in the video was JavaScript, but I was easily able to convert the code from the video to Kotlin:
https://www.youtube.com/watch?v=5Bochyn8MMI&t=72s&ab_channel=crayoncode
Here is an excerpt of the JavaScript code from the video:
Converted code:
Tools.FILL_TOOL -> {
val seedColor = instance.rectangles[rectTapped]?.color ?: Color.WHITE
val queue = LinkedList<XYPosition>()
queue.offer(MathExtensions.convertIndexToXYPosition(rectangleData.indexOf(rectTapped), instance.spanCount.toInt()))
val selectedColor = getSelectedColor()
while (queue.isNotEmpty() && seedColor != selectedColor) { // While the queue is not empty the code below will run
val current = queue.poll()
val color = instance.rectangles.toList()[convertXYDataToIndex(instance, current)].second?.color ?: Color.WHITE
if (color != seedColor) {
continue
}
instance.extraCanvas.apply {
instance.rectangles[rectangleData[convertXYDataToIndex(instance, current)]] = defaultRectPaint // Colors in pixel with defaultRectPaint
drawRect(rectangleData[convertXYDataToIndex(instance, current)], defaultRectPaint)
for (index in expandToNeighborsWithMap(instance, current)) {
val candidate = MathExtensions.convertIndexToXYPosition(index, instance.spanCount.toInt())
queue.offer(candidate)
}
}
}
}
Now, I want to address two major issues I'm having with the code of mine:
Performance
Flooding glitch (fixed by suggestion from person in the comments)
Performance
A flood fill needs to be very fast and shouldn't take less than a second, the problem is, say I have a canvas of size 50 x 50, and I decide to fill in the whole canvas, it can take up to 8 seconds or more.
Here is some data I've compiled for the time it's taken to fill in a whole canvas given the spanCount value:
spanCount
approx time taken in seconds to fill whole canvas
10
<1 seconds
20
~2 seconds
40
~6 seconds
60
~15 seconds
100
~115 seconds
The conclusion from the data is that the flood fill algorithm is unusually slow.
To find out why, I decided to test out which parts of the code are taking the most time to compile. I came to the conclusion that the expandToNeighbors function is taking the most time out of all the other tasks:
Here is an excerpt of the expandToNeighbors function:
fun expandToNeighbors(instance: MyCanvasView, from: XYPosition): List<Int> {
var asIndex1 = from.x
var asIndex2 = from.x
var asIndex3 = from.y
var asIndex4 = from.y
if (from.x > 1) {
asIndex1 = xyPositionData!!.indexOf(XYPosition(from.x - 1, from.y))
}
if (from.x < instance.spanCount) {
asIndex2 = xyPositionData!!.indexOf(XYPosition(from.x + 1, from.y))
}
if (from.y > 1) {
asIndex3 = xyPositionData!!.indexOf(XYPosition(from.x, from.y - 1))
}
if (from.y < instance.spanCount) {
asIndex4 = xyPositionData!!.indexOf(XYPosition(from.x, from.y + 1))
}
return listOf(asIndex1, asIndex2, asIndex3, asIndex4)
}
To understand the use of the expandToNeighbors function, I would recommend watching the video that I linked above.
(The if statements are there to make sure you won't get an IndexOutOfBoundsException if you try and expand from the edge of the canvas.)
This function will return the index of the north, south, west, and east pixels from the xyPositionData list which contains XYPosition objects.
(The black pixel is the from parameter.)
The xyPositionData list is initialized once in the convertXYDataToIndex function, here:
var xyPositionData: List<XYPosition>? = null
var rectangleData: List<RectF>? = null
fun convertXYDataToIndex(instance: MyCanvasView, from: XYPosition): Int {
if (rectangleData == null) {
rectangleData = instance.rectangles.keys.toList()
}
if (xyPositionData == null) {
xyPositionData = MathExtensions.convertListOfSizeNToListOfXYPosition(
rectangleData!!.size,
instance.spanCount.toInt()
)
}
return xyPositionData!!.indexOf(from)
}
So, the code works fine (kind of) but the expandToNeighbors function is very slow, and it is the main reason why the flood fill algorithm is taking a long time.
My colleague suggested that indexOf may be slowing everything down, and that I should probably switch to a Map-based implementation with a key being XYPosition and a value being Int representing the index, so I replaced it with the following:
fun expandToNeighborsWithMap(instance: MyCanvasView, from: XYPosition): List<Int> {
var asIndex1 = from.x
var asIndex2 = from.x
var asIndex3 = from.y
var asIndex4 = from.y
if (from.x > 1) {
asIndex1 = rectangleDataMap!![XYPosition(from.x - 1, from.y)]!!
}
if (from.x < instance.spanCount) {
asIndex2 = rectangleDataMap!![XYPosition(from.x + 1, from.y)]!!
}
if (from.y > 1) {
asIndex3 = rectangleDataMap!![XYPosition(from.x, from.y - 1)]!!
}
if (from.y < instance.spanCount) {
asIndex4 = rectangleDataMap!![XYPosition(from.x, from.y + 1)]!!
}
return listOf(asIndex1, asIndex2, asIndex3, asIndex4)
}
It functions the same way, only this time it uses a Map which is initialized here:
var xyPositionData: List<XYPosition>? = null
var rectangleData: List<RectF>? = null
var rectangleDataMap: Map<XYPosition, Int>? = null
fun convertXYDataToIndex(instance: MyCanvasView, from: XYPosition): Int {
if (rectangleData == null) {
rectangleData = instance.rectangles.keys.toList()
}
if (xyPositionData == null) {
xyPositionData = MathExtensions.convertListOfSizeNToListOfXYPosition(
rectangleData!!.size,
instance.spanCount.toInt()
)
}
if (rectangleDataMap == null) {
rectangleDataMap = MathExtensions.convertListToMap(
rectangleData!!.size,
instance.spanCount.toInt()
)
}
return xyPositionData!!.indexOf(from)
}
Converting the code to use a map increased the speed by around 20%, although the algorithm is still slow.
After trying to make the algorithm work faster, I'm out of ideas and I'm unsure why the expandToNeighbors function is taking a long time.
Implementation-wise it is quite messy unfortunately because of the whole list index to XYPosition conversions, but at least it works - the only problem is the performance.
So I have two one major problem.
I've actually pushed the fill tool to GitHub as a KIOL (Known Issue or Limitation), so the user can use the fill tool if they want, but they need to be aware of the limitations/issues. This is so anyone can have a look at my code and reproduce the bugs.
Link to repository:
https://github.com/realtomjoney/PyxlMoose
Edit
I understand that this question is extremely difficult to answer and will require a lot of thinking. I would recommend cloning PyxlMoose and reproduce the errors, then work from there. Relying on the code snippets isn't enough.
Formula for converting XY position to an index
Somebody in the comments suggested a formula for converting an XYPosition to an index value, I came up with the following method which works:
fun convertXYPositionToIndex(xyPosition: XYPosition, spanCount: Int): Int {
val positionX = xyPosition.x
val positionY = xyPosition.y
return (spanCount - positionY) + (spanCount * (positionX - 1))
}
The only problem is - it increases the speed by around 50% but it's still taking around 10-15 seconds to fill in an area of 80 by 80 pixels, so it has helped to a large degree although it's still very slow.
I think the performance issue is because of expandToNeighbors method generates 4 points all the time. It becomes crucial on the border, where you'd better generate 3 (or even 2 on corner) points, so extra point is current position again. So first border point doubles following points count, second one doubles it again (now it's x4) and so on.
If I'm right, you saw not the slow method work, but it was called too often.
How I fixed it:
Getting rid of the toList() calls.
Creating an convertXYPositionToIndex() function.
Here is my new code:
Tools.FILL_TOOL -> {
val seedColor = instance.rectangles[rectTapped]?.color ?: Color.WHITE
val queue = LinkedList<XYPosition>()
val spanCount = instance.spanCount.toInt()
queue.offer(MathExtensions.convertIndexToXYPosition(rectangleData.indexOf(rectTapped), spanCount))
val selectedColor = getSelectedColor()
while (queue.isNotEmpty() && seedColor != selectedColor) {
val current = queue.poll()
val color = instance.rectangles[rectangleData[convertXYDataToIndex(spanCount, current)]]?.color ?: Color.WHITE
if (color != seedColor) {
continue
}
instance.rectangles[rectangleData[convertXYDataToIndex(spanCount, current)]] = defaultRectPaint // Colors in pixel with defaultRectPaint
instance.extraCanvas.drawRect(rectangleData[MathExtensions.convertXYPositionToIndex(current, spanCount)], defaultRectPaint)
for (index in expandToNeighborsWithMap(spanCount, current)) {
val candidate = MathExtensions.convertIndexToXYPosition(index, spanCount)
queue.offer(candidate)
}
}
val timeTakenForThis = (System.currentTimeMillis()-startTime)
totalTime += timeTakenForThis
}
Expand to neighbors func:
fun expandToNeighborsWithMap(spanCount: Int, from: XYPosition): List<Int> {
val toReturn = mutableListOf<Int>()
if (from.x > 1) {
toReturn.add(MathExtensions.convertXYPositionToIndex(XYPosition(from.x - 1, from.y), spanCount))
}
if (from.x < spanCount) {
toReturn.add(MathExtensions.convertXYPositionToIndex(XYPosition(from.x + 1, from.y), spanCount))
}
if (from.y > 1) {
toReturn.add(MathExtensions.convertXYPositionToIndex(XYPosition(from.x, from.y - 1), spanCount))
}
if (from.y < spanCount) {
toReturn.add(MathExtensions.convertXYPositionToIndex(XYPosition(from.x, from.y + 1), spanCount))
}
return toReturn
}
It takes less than a second for canvas sizes of 100 by 100 and 200 by 200, so I'd say it's in the usable stage now.
I would say this is one of the simplest Android flood fill algorithms out there to understand, so if anyone is making an app similar to mine and they want a flood fill tool they can copy my code.
A guy in the comments called EvilTalk helped me with this.
I made a simple tic tac toe game in Kotlin android studio and I'm Trying to make a line after a won game.
for example if X won all three of X will be crossed with line X̶X̶X̶. My representation of that is Indigent, but I think you got the point.
Progress so far:
made two arrays which hold info about each player:
var Player1 = ArrayList<Int>()
var Player2 = ArrayList<Int>()
var ActivePlayer = 1
var setPlayer = 1
gave id to buttons:
fun buttonClick(view: View) {
val buSelected:Button = view as Button
var cellId = 0
when(buSelected.id) {
R.id.button1 -> cellId = 1
R.id.button2 -> cellId = 2
R.id.button3 -> cellId = 3
R.id.button4 -> cellId = 4
R.id.button5 -> cellId = 5
R.id.button6 -> cellId = 6
R.id.button7 -> cellId = 7
R.id.button8 -> cellId = 8
R.id.button9 -> cellId = 9
}
PlayGame(cellId,buSelected)
}
and this is how I check winner:
fun CheckWinner()
{
var winner = -1
//row1
if (Player1.contains(1) && Player1.contains(2) && Player1.contains(3))
{
winner = 1
}
if (Player2.contains(1) && Player2.contains(2) && Player2.contains(3))
{
winner = 2
}
There is more code to it but its too much to add into this post.
User Interface
I recommend create your own custom view instead of using Buttons. You can for example create FrameLayout and put inside TextView and then either show/hide some simple View with line or draw this line with the help of Canvas. That custom view will be 1 of 9 squares. Then just put them in some grid (manually or using RecyclerView or GridView).
Logic
Create two lists that will contain X and O for each player. Lists of ints with square positions will be enough. Fill those lists with positions (from 1 to 9) when one of two users select a square and before add new item (position) to list, check if this item isn't already in the list (this player, player1) and isn't in the other list (other player, player2). If both of two lists don't contain this item - add it. Then, after adding a new position to list, check if it forms a line. For example, 1, 3, 9 or 2, 5, 7. If so, that player won and you can cross those positions.
Code could look like this:
enum Player {
player1,
player2
}
List<int> player1List = List();
List<int> player2List = List();
void addNewPosition(Player player, int position) {
List<int> currentPlayerList;
List<int> otherPlayerList;
switch(player) {
case Player.player1:
currentPlayerList = player1List;
otherPlayerList = player2List;
break;
case Player.player2:
currentPlayerList = player2List;
otherPlayerList = player1List;
break;
}
if (currentPlayerList.contains(position)) {
// this player already selected this position, do nothing
return;
}
if (otherPlayerList.contains(position)) {
// another player already selected this position, do nothing
return;
}
currentPlayerList.add(position); // add selected position to current player list
// now check if current players position forms a line
if (currentPlayerList.contains(1) && currentPlayerList.contains(2) && currentPlayerList.contains(3)) {
// this player won
}
... check other possible solutions that could result in a win. Better to follow some pattern instead of checking each of them
}
I have two list, one with all possible devices and another with just few devices. I need pass final list with this condition:
if full list == one of the items in smaller list, make this item "active" too true, else leave it false.
I have no problem when working with full list >500 devices and small list >50, but when I have for example 2000 devices everything start to be too slow (on Google Pixel 2XL I need to wait about 6 seconds to job finish).
Question: how can I increase this loop speed?
What I have done so far:
devicesList.forEach { device ->
device.selected = false
items.forEach { it ->
if(it.id == device.id){
device.selected = true
}
}
But this is too slow for larger data
You can speed it up a bit by not using forEach, which uses an interator and instead use a for loop. You can also break once you locate your id, assuming they are unique
for (i in 0 until devicesList.size) {
val device = devicesList[i]
for (j in 0 until items.size) {
val item = items[j]
if (item.id == device.id) {
device.selected = true
break
}
}
}
Assuming your ids are unique, you could also make a duplicate of the items list and drop those that have been located, so each loop is shorter, like this
val copy = items.toMutableList()
for (i in 0 until devicesList.size) {
val device = devicesList[i]
for (j in 0 until copy.size) {
val item = copy[j]
if (item.id == device.id) {
device.selected = true
copy.remove(item)
break
}
}
}
You could also consider creating a map where the key is your id so you do not have to loop and instead you retrieve the item by id directly. You have to weight the cost of creating the map in the first place.
val map = items.associateBy { it.id }
for (i in 0 until devicesList.size) {
val device = devicesList[i]
device.selected = map[device.id] != null
}
Besides this, you should also move your logic to a background thread and wait for it to complete.
If all you need is make selected = true if a device's id exists in the list items, you can get all the ids of items like this:
val ids = items.map { it.id }
and then loop through devices:
devicesList.forEach { it.selected = it.id in ids }