-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame.Java
98 lines (84 loc) · 2.49 KB
/
Game.Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private GameThread gameThread;
private float circleX, circleY;
private Paint paint;
public GameView(Context context) {
super(context);
getHolder().addCallback(this);
circleX = 100;
circleY = 100;
paint = new Paint();
paint.setColor(Color.RED);
gameThread = new GameThread(getHolder(), this);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
gameThread.setRunning(true);
gameThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameThread.setRunning(false);
while (retry) {
try {
gameThread.join();
retry = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
circleX = event.getX();
circleY = event.getY();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.drawCircle(circleX, circleY, 50, paint);
}
}
import android.graphics.Canvas;
import android.view.SurfaceHolder;
public class GameThread extends Thread {
private SurfaceHolder surfaceHolder;
private GameView gameView;
private boolean running;
public GameThread(SurfaceHolder surfaceHolder, GameView gameView) {
this.surfaceHolder = surfaceHolder;
this.gameView = gameView;
}
public void setRunning(boolean running) {
this.running = running;
}
@Override
public void run() {
while (running) {
Canvas canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
gameView.onDraw(canvas);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}