Skip to content

Instantly share code, notes, and snippets.

Created January 18, 2016 23:26
Show Gist options
  • Save anonymous/4777fbdcf194d55fc6d9 to your computer and use it in GitHub Desktop.
Save anonymous/4777fbdcf194d55fc6d9 to your computer and use it in GitHub Desktop.
import java.net._
import java.io._
import scala.io._
object BattleshipsClient extends App {
val s = new Socket(InetAddress.getByName("localhost"), 8000)
lazy val in = new BufferedSource(s.getInputStream()).getLines()
val out = new PrintStream(s.getOutputStream())
out.println("0,1")
out.flush()
println("Received: " + in.next())
s.close()
}
import java.net._
import java.io._
import scala.io._
object BattleshipsServer extends App {
val initState = List(
List(0, 1, 0),
List(0, 0, 1),
List(0, 0, 0)
)
val server = new ServerSocket(8000)
def respond(s: String, currentState: List[List[Int]]) = {
val x: Int = s.split(",")(0).toInt
val y: Int = s.split(",")(1).toInt
(currentState(x)(y), x, y)
}
def nextIteration(state: List[List[Int]]) {
val s = server.accept()
val in = new BufferedSource(s.getInputStream()).getLines()
val out = new PrintStream(s.getOutputStream())
val response: (Int, Int, Int) = respond(in.next(), state)
out.println(response._1)
val newState: List[List[Int]] = for (i <- (0 until state.length).toList) yield {
for (j <- (0 until state(0).length).toList) yield {
if (i == response._2 && j == response._3 && response._1 == 1) -1
else state(i)(j)
}
}
out.flush()
s.close()
nextIteration(newState)
}
nextIteration(initState)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment