Skip to content

Commit

Permalink
Writing a PGN parser.
Browse files Browse the repository at this point in the history
  • Loading branch information
skytreader committed Aug 9, 2017
1 parent d3f3c58 commit a2a1d02
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 2 deletions.
Expand Up @@ -47,6 +47,11 @@ public class NotationParser{
Pattern.compile(CASTLING_REGEX),
Pattern.compile(CHECK_REGEX)
};

private class Movement{
public Point origin;
public Point destination;
}

/**
Returns true if the given string is valid chess algebraic notation.
Expand All @@ -62,11 +67,11 @@ public static boolean isValid(String s){
return isValid;
}

public static Point parse(String s){
public static Point parse(String s) throws InvalidStateException{
if(isValid(s)){
return null;
} else{
throw InvalidStateException("Invalid algebraic notation: " + s);
throw new InvalidStateException("Invalid algebraic notation: " + s);
}
}

Expand Down
30 changes: 30 additions & 0 deletions src/main/java/net/skytreader/kode/chesstemplar/utils/PGN.java
@@ -0,0 +1,30 @@
package net.skytreader.kode.chesstemplar.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;

import java.util.HashMap;
import java.util.regex.Pattern;

public class PGN{
private HashMap<String, String> metadata;
private String gamefeed;

protected static final Pattern METADATA_PATTERN = Pattern.compile("\\[.+\\]");
protected static final Pattern METADATA_CAPTURE_PATTERN = Pattern.compile("\\[(.+)\\s+[\"\'](.+)[\"\']\\]");

public PGN(String filename) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
try{
String line = br.readLine().trim();

while(line != null && PGN.METADATA_PATTERN.matcher(line).matches()){
line = br.readLine().trim();
}
} finally{
br.close();
}
}
}
41 changes: 41 additions & 0 deletions src/test/java/net/skytreader/kode/chesstemplar/utils/PGNTest.java
@@ -0,0 +1,41 @@
package net.skytreader.kode.chesstemplar.utils;

import org.junit.Assert;
import org.junit.Test;

import java.util.regex.Matcher;

public class PGNTest{

@Test
public void testMetadataPattern(){
String[] metadata = {
"[Event \"Local Event\"]",
"[Site \"Local Site\"]",
"[Date \"2017.08.01\"]",
"[Round \"1\"]",
"[White \"chad\"]",
"[Black \"PyChess.py\"]",
"[Result \"0-1\"]",
"[ECO \"B23\"]",
"[TimeControl \"300+0\"]",
"[Time \"21:49:00\"]",
"[WhiteClock \"0:00:43.901\"]",
"[BlackClock \"0:04:54.370\"]",
"[PlyCount \"50\"]"
};

for(int i = 0; i < metadata.length; i++){
Assert.assertTrue(PGN.METADATA_PATTERN.matcher(metadata[i]).matches());
}
}

@Test
public void testMetadataCapturePattern(){
String test = "[Event \"Local Event\"]";
Matcher m = PGN.METADATA_CAPTURE_PATTERN.matcher(test);
Assert.assertTrue(m.matches());
Assert.assertEquals("Event", m.group(1));
Assert.assertEquals("Local Event", m.group(2));
}
}

0 comments on commit a2a1d02

Please sign in to comment.