Skip to content

Instantly share code, notes, and snippets.

@pljones
Forked from anonymous/BattleshipsClient.scala
Created January 19, 2016 12:20
Show Gist options
  • Save pljones/5cea959c690dcf49e1e1 to your computer and use it in GitHub Desktop.
Save pljones/5cea959c690dcf49e1e1 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Jan 18, 2016.
    17 changes: 17 additions & 0 deletions BattleshipsClient.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    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()

    }
    43 changes: 43 additions & 0 deletions BattleshipsServer.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    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)

    }