package com.nishtahir.openpong
import java.awt.*
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.SwingUtilities
import javax.swing.Timer
/**
* Created by nish on 10/15/16.
*/
class OpenPongApp : JFrame() {
init {
title = "Open pong II"
defaultCloseOperation = EXIT_ON_CLOSE
size = Dimension(600, 800)
isVisible = true
val panel = MainPanel()
add(panel)
}
}
//inline fun <T> Timer.run(crossinline body: () -> T) {
// scheduleAtFixedRate(object : TimerTask () {
// override fun run() {
// body.invoke()
// }
// }, 0, 1 * 1000)
//}
class MainPanel(val ball : Ball = Ball()) : JPanel(), ActionListener {
override fun actionPerformed(e: ActionEvent?) {
repaint()
}
init {
isDoubleBuffered = true
background = Color.BLACK
// val timer = Timer(1000, this)
// timer.start()
val timer = Timer(100, ActionListener { e ->
ball.update()
repaint()
})
timer.start()
}
override fun paint(g: Graphics?) {
super.paint(g)
ball.asRect(g!!)
// println("Called")
// println("Ball - ${ball.toString()}")
Toolkit.getDefaultToolkit().sync();
}
}
class Ball(var dx: Int = 1, var dy: Int = 1) : Entity(x = 300.0, y = 400.0, width = 5, height = 5) {
fun asRect(g: Graphics) {
with (g) {
color = Color.WHITE
drawRect(x.toInt(), y.toInt(), width, height)
}
}
override fun toString(): String = "$x, $y"
fun update() {
x += dx
y += dy
}
}
class Paddle(var dx: Int = 1, var dy: Int = 1) : Entity(x = 150.0, y = 30.0 , width = 300, height = 50) {
fun asRect(g: Graphics) {
with (g) {
color = Color.WHITE
drawRect(x.toInt(), y.toInt(), width, height)
}
}
fun update() {
x += dx
}
}
open class Entity(var x: Double = 0.0, var y: Double = 0.0, var width: Int = 0, var height: Int = 0)
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
OpenPongApp()
}
}