Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package wld.objs
- import java.awt.Color
- import java.awt.Graphics
- import java.awt.Rectangle
- import java.util.*
- import javax.swing.JFrame
- import javax.swing.JPanel
- import kotlin.collections.ArrayList
- const val STEP = 2
- const val BOT_SIZE = 2
- const val WIDTH = 800
- const val HEIGHT = 600
- const val SLEEP_TIME:Long = 15
- const val BOT_POPULATION = 50000
- const val DNA_LEN = 1500
- fun main() {
- val thread = Thread(Runnable {
- println("start new world session")
- val world = World()
- while (!world.isWorldNotTerminated){
- world.update()
- world.render()
- Thread.sleep(SLEEP_TIME)
- }
- })
- thread.start()
- }
- class View(private val objects:ArrayList<Bot>):JPanel(){
- override fun paintComponent(g: Graphics?) {
- for (obj in objects){
- obj.draw(g)
- }
- }
- }
- class Bot {
- private val selfColor = Color.getHSBColor(Random().nextFloat(),Random().nextFloat(),Random().nextFloat())
- private var xPos:Int = 0
- private var yPos:Int = 0
- private var dna = mutableListOf<Int>()
- private var curDnaIndex = 0
- init {
- for (i in 0 until DNA_LEN){
- dna.add((Math.random()*4).toInt())
- }
- //println("dna chain: $dna")
- xPos = WIDTH/2
- yPos = HEIGHT/2
- //println("new bot coors are {x:$xPos y:$yPos}")
- }
- fun draw(g: Graphics?) {
- g!!.color = selfColor
- g.fillRect(xPos,yPos, BOT_SIZE, BOT_SIZE)
- }
- fun update() {
- if (curDnaIndex >= DNA_LEN){
- curDnaIndex = 0
- //println("dna chain finished and reloaded")
- }
- when(dna[curDnaIndex++]){
- 0 -> xPos += STEP
- 1 -> xPos -= STEP
- 2 -> yPos += STEP
- 3 -> yPos -= STEP
- }
- when(xPos){
- WIDTH -> xPos = 0
- -BOT_SIZE -> xPos = WIDTH - BOT_SIZE
- }
- when(yPos){
- HEIGHT -> yPos = 0
- -BOT_SIZE -> yPos = HEIGHT - BOT_SIZE
- }
- }
- }
- class World {
- var isWorldNotTerminated: Boolean = false
- private val frame = JFrame("title")
- private val objects = ArrayList<Bot>()
- private val view = View(objects)
- init {
- for (i in 0 until BOT_POPULATION){
- objects.add(Bot())
- }
- frame.bounds = Rectangle(0,0, WIDTH, HEIGHT)
- frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
- frame.isResizable = false
- frame.contentPane.add(view)
- frame.background = Color.BLACK
- frame.isVisible = true
- }
- fun update() {
- for (obj in objects){
- obj.update()
- }
- }
- fun render() {
- frame.repaint()
- view.repaint()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement