简体   繁体   English

如何确定记忆游戏中哪个方块被按下?

[英]How can I determine which square in my memory game was pressed?

I want to develop an simple memory game on Android. 我想在Android上开发一个简单的记忆游戏。

The memory game have squares like the picture below. 记忆游戏的方块如下图所示。 How should I determine which of the square is pressed? 我应该如何确定按下哪个正方形? Should I use image buttons? 我应该使用图像按钮吗? Personally I don't think it is an good idea to make the game with image buttons. 我个人认为使用图像按钮制作游戏不是一个好主意。 Could you suggest me an solution on how I should determine which of the square is pressed? 您能为我提供一个解决方案,该如何确定应该按下哪个正方形?

在此处输入图片说明

I think ImageView s for each square is the best way to go, no need for buttons. 我认为每个正方形的ImageView都是最好的选择,不需要按钮。

Note: View s would be sufficient, you can implement onClick(View) for any view. 注意: View就足够了,您可以为任何视图实现onClick(View)

UPDATE: Since you have a Graphics (as opposed to View s) for your squares, you may indeed use the coordinates to determine which square is touched, but I don't think this is the easiest, nor the best approach. 更新:由于您的正方形具有一个Graphics(而不是View ),因此您确实可以使用坐标来确定要触摸哪个正方形,但是我认为这不是最简单也不是最好的方法。

Why don't you want a GridLayout or a TableLayout containing ImageView s? 为什么不想要包含ImageViewGridLayoutTableLayout

If you have a view where you draw the squares then put a onClick() listener in that view and inside the onClick() do like this: (this is taken from a Sudoku game I made) 如果您有一个绘制正方形的视图,然后在该视图中的onClick()内放置一个onClick()侦听器,则应像这样:(取自我制作的Sudoku游戏)

@Override
public boolean onTouch(View v, MotionEvent event)
{
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // keep where the user first touch the screen
            touchedX = (int) event.getX() / wid33; // the square width
            touchedY = (int) event.getY() / hei33; // the square height
            break;

        case MotionEvent.ACTION_UP:
            // see if the touched square is the same
            int X = (int) event.getX() / wid33;
            int Y = (int) event.getY() / hei33;
            if (X == touchedX && Y == touchedY)
            {
             // the square is the same, do what you have to do
            }
            break;

        case MotionEvent.ACTION_CANCEL:
            touchedX = -1;
            touchedY = -1;
            break;

        default:
            return super.onTouchEvent(event);
    }
    return true;
}

Consider using Canvas or even OpenGL ES to render your game. 考虑使用Canvas甚至OpenGL ES渲染游戏。 This approach gives you more flexibility and better performance. 这种方法为您提供了更大的灵活性和更好的性能。

To check witch square was touched handle touch event you can use OnTouchListener . 要检查巫婆广场是否被触摸过,可以使用OnTouchListener触摸事件。

This or this answer might be helpful to start your code. 这个这个答案可能对启动代码很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM