[Solved] 2048 get board with python selenium


I don’t know Python but this is Java so hopefully you can translate it.

I put the board into a two-dimensional array of int in the form board[1][2] = 16 where the class on that tile would be tile tile-16 tile-position-1-2 tile-new. I know that’s not what you asked for but you didn’t give enough detail on how you are storing various positions…

List<WebElement> tiles = driver.findElements(By.cssSelector("div.tile"));
int[][] board = new int[5][5]; // need 5 instead of 4 because we are going to use indices 1-4 and not 0-3
for (WebElement tile : tiles)
{
    String className = tile.getAttribute("className");
    String regex = "tile tile-(\\d*) tile-position-(\\d)-(\\d) tile-new";
    Matcher matcher = Pattern.compile(regex).matcher(className);
    matcher.matches();
    int x = Integer.parseInt(matcher.group(2));
    int y = Integer.parseInt(matcher.group(3));
    int value = Integer.parseInt(matcher.group(1));
    board[x][y] = value;
}

The code grabs the DIV with class tile because all tiles that have any value are defined here. (The HTML of the board is kinda weird IMO but I’m not a web designer… so maybe it’s just me). It then loops through all tiles and gets the className where all the positional and value data is stored. It uses a Regex to pase the className and then assigns values to the correct position in the array board.

If you dump the values of board you will get something like

0000
0020
0000
0020

Hopefully that helps.

6

solved 2048 get board with python selenium