0

I am trying to run the following game of chess from the console:

package chess
import java.io.Console

object Game {

  def readCorrectMove(c: Console): String = {
    val move: String = c.readLine()
    if(!(move.length == 4 &&
      1 <= move(0).toInt && move(0).toInt <= 8 &&
      'a' <= move(0) && move(0) <= 'h' &&
      1 <= move(0).toInt && move(0).toInt <= 8 &&
      'a' <= move(0) && move(0) <= 'h')) {
      println("Wrong move!")
      readCorrectMove(c: Console)
    } else {
      move
    }
  }

  def main(args: Array[String]) {

    val c: Console = System.console()
    val board = new Board()

    c.format(board.toString)

    while(true) {
      val wm = readCorrectMove(c)
      c.format(board.toString)
//      if(board.checkMate()) {
//        println("White wins!!!")
//        return
//      }
      val bm = readCorrectMove(c)
      c.format(board.toString)
//      if(board.checkMate()) {
//        println("Black wins!!!")
//      }
    }

  }

}

I would like the program to wait for a move from the user, then to output the resulting board.

I'm not sure how to do that though.

If I run the code, I get a NullPointerException on this line:

    c.format(board.toString)

This probably means that I'm not using Console correctly.

So how can I create an interactive console that takes input from the user, in a Scala class?

bsky
  • 19,326
  • 49
  • 155
  • 270
  • please post code that can be run, i.e. has imports and no external dependencies. Also, which command are you using to run it? – Kim Stebel Aug 20 '16 at 15:40
  • I added the imports, but I can't remove external dependencies because there wouldn't be much code left. I just want to know whether using `System.console()` is the correct thing to do for getting repeated input from the user or if I should use something else. – bsky Aug 20 '16 at 16:37
  • `System.console` is the right way to go, but it seems to return `null`, which is why I asked how you run the code. – Kim Stebel Aug 20 '16 at 16:41
  • I am running the code from Intellij, without any parameters. – bsky Aug 20 '16 at 17:25
  • Try running it from the command line. – Kim Stebel Aug 20 '16 at 18:11
  • See http://stackoverflow.com/questions/14833973/how-to-get-system-console-in-java-while-using-ides-like-eclipse-or-netbeans – Alexey Romanov Aug 20 '16 at 21:40

0 Answers0