Skip to content

Instantly share code, notes, and snippets.

@uwi
Last active August 29, 2015 13:57
Show Gist options
  • Save uwi/9625841 to your computer and use it in GitHub Desktop.
Save uwi/9625841 to your computer and use it in GitHub Desktop.
2048のAIのSelenium2と連携させているところ
package twothu;
import java.util.Arrays;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
public class Reactor2 {
WebDriver driver;
WebElement body;
public Reactor2()
{
driver = new FirefoxDriver();
driver.get("http://gabrielecirulli.github.io/2048/");
body = driver.findElement(By.tagName("body"));
// driver.manage().timeouts().implicitlyWait()
}
List<int[]> newElements()
{
List<WebElement> elements = driver.findElements(By.className("tile-new"));
List<int[]> ret = Lists.newArrayList();
for(WebElement e : elements){
tr(e.getAttribute("class"));
int r = -1, c = -1, val = -1;
for(String item : Splitter.on(' ').split(e.getAttribute("class"))){
if(item.equals("tile-new"))continue;
if(item.startsWith("tile-position")){
r = item.charAt(16)-'1';
c = item.charAt(14)-'1';
tr(r, c);
}else if(item.startsWith("tile-")){
val = Ints.tryParse(item.substring(5));
}
}
ret.add(new int[]{r, c, val});
}
return ret;
}
void quit()
{
driver.quit();
}
public static void main(String[] args) throws Exception {
Reactor2 re = new Reactor2();
State s = new State();
AI ai = new DFSSnake();
Keys[] dir = {Keys.ARROW_DOWN, Keys.RIGHT, Keys.UP, Keys.LEFT};
while(true){
// 2048以降やり続けるボタン
WebElement keepPlaying = re.driver.findElement(By.className("keep-playing-button"));
if(keepPlaying.isDisplayed()){
keepPlaying.click();
Thread.sleep(500L);
}
// 新しいセルを読む
List<int[]> ne = re.newElements();
for(int[] cell : ne){
s.map[cell[0]][cell[1]] = Integer.numberOfTrailingZeros(cell[2]);
}
// 考える
Action act = ai.guess(s);
if(act == null || !s.canact(act)){
break;
}
// 動かす
s.act(act);
re.body.sendKeys(dir[act.dir]);
tr(act);
tr(s);
// 待つ
Thread.sleep(70L);
}
// re.quit();
}
static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment