Libgdx tic tac toe游戏

时间:2016-04-06 05:45:05

标签: java input libgdx

public class CrossAndCircles extends ApplicationAdapter{

    OrthographicCamera camera;
    SpriteBatch batch;
    ShapeRenderer renderer;
    Array<Rectangle> array;
    Vector3 touchPos;
    int turn, cellSize, touchCount;
    float tempX, tempY;



    @Override
    public void create () {
        batch = new SpriteBatch();
        renderer = new ShapeRenderer();
        camera = new OrthographicCamera();
        camera.setToOrtho(false, 480, 480);


        touchCount = 0;

        cellSize = 480/3-5;
        array = new Array<Rectangle>();

        //cell's coordinates
        Rectangle oneOne = new Rectangle(0, 0 ,cellSize, cellSize);
        Rectangle oneTwo = new Rectangle(0, cellSize+5, cellSize, cellSize);
        Rectangle oneThree = new Rectangle(0, 480-cellSize, cellSize, cellSize);
        Rectangle twoOne = new Rectangle(cellSize+5, 0 , cellSize, cellSize);
        Rectangle twoTwo = new Rectangle(cellSize+5, cellSize+5, cellSize, cellSize);
        Rectangle twoThree = new Rectangle(cellSize+10, 480-cellSize, cellSize, cellSize);
        Rectangle threeOne = new Rectangle(480-cellSize, 0 , cellSize, cellSize);
        Rectangle threeTwo = new Rectangle (480-cellSize, cellSize+5, cellSize, cellSize);
        Rectangle threeThree = new Rectangle(480-cellSize, 480-cellSize, cellSize, cellSize);
        array.add(oneOne); array.add(oneTwo); array.add(oneThree); array.add(twoOne);
        array.add(twoTwo); array.add(twoThree); array.add(threeOne); array.add(threeTwo); array.add(threeThree);
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        camera.update();
        //our field
        batch.setProjectionMatrix(camera.combined);
        renderer.begin(ShapeType.Filled);
        renderer.setColor(Color.BLACK);
        renderer.rect(480/3-5, 0, 10, 480);
        renderer.rect(480/3*2-5, 0, 10, 480);
        renderer.rect(0, 480 / 3 - 10, 480, 10);
        renderer.rect(0, 480 / 3 * 2 - 10, 480, 10);
        renderer.end();

        //if user touch a rectangle draw a circle or a cross
        if(Gdx.input.isTouched()){
            for (Rectangle rect:array) {
                if (rect.contains(Gdx.input.getX(), Gdx.input.getY())) {
                    tempX = rect.x;
                    tempY = rect.y;
                    break;
                    }}
            touchCount++;
        }

        if (touchCount>0 && touchCount<=9){
            renderer.begin(ShapeType.Filled);
            renderer.rect(tempX+20,tempY+20,0, 0, 10, cellSize, 1, 1, -45);
            renderer.end();}

    }

    public void dispose(){super.dispose(); renderer.dispose();}

}

帮助我完成我的Tic tac toe游戏。我仍然只添加了一根棍子,但它只出现了两次,当我点击上面的单元格时,它会显示为较低的。我不知道为什么第一根棍子没有被保存,它只是改变了它的位置。我的逻辑出了什么问题?

1 个答案:

答案 0 :(得分:1)

触摸和屏幕坐标有差异, 参考: https://github.com/libgdx/libgdx/wiki/Coordinate-systems