source: advance-wars/src/com/medievaltech/advancewars/GameView.java@ 5d77d43

Last change on this file since 5d77d43 was 1a1e8c7, checked in by dportnoy <devnull@…>, 14 years ago

Added a basic draw function to Unit and made some other minor code changes.

  • Property mode set to 100644
File size: 17.6 KB
Line 
1package com.medievaltech.advancewars;
2
3import com.medievaltech.game.*;
4import com.medievaltech.gui.*;
5
6import android.content.Context;
7import android.graphics.*;
8import android.os.*;
9import android.view.*;
10import android.util.AttributeSet;
11import android.util.Log;
12import android.widget.TextView;
13
14/**
15 * View that draws, takes keystrokes, etc. for a simple LunarLander game.
16 *
17 * Has a mode which RUNNING, PAUSED, etc. Has a x, y, dx, dy, ... capturing the
18 * current ship physics. All x/y etc. are measured with (0,0) at the lower left.
19 * updatePhysics() advances the physics based on realtime. draw() renders the
20 * ship, and does an invalidate() to prompt another draw() as soon as possible
21 * by the system.
22 */
23class GameView extends SurfaceView implements SurfaceHolder.Callback {
24
25 class DrawingThread extends Thread {
26 public AppState mAppState;
27 public GameState mGameState;
28
29 /*
30 * UI constants (i.e. the speed & fuel bars)
31 */
32 public static final int UI_BAR = 100; // width of the bar(s)
33 public static final int UI_BAR_HEIGHT = 10; // height of the bar(s)
34
35 /*
36 * Member (state) fields
37 */
38
39 private int mCanvasHeight = 1;
40 private int mCanvasWidth = 1;
41 public int mPlayerWins = 0, mPlayerLosses = 0;
42
43 /** Message handler used by thread to interact with TextView */
44 private Handler mHandler;
45
46 /** Used to figure out elapsed time between frames */
47 private long mLastTime;
48
49 /** Paint to draw the lines on screen. */
50 private Paint mLinePaint, mTextPaint, mButtonPaint, mTilePaint1, mTilePaint2,
51 mUnitPaint;
52
53 private Map mMap;
54
55 /** Indicate whether the surface has been created & is ready to draw */
56 private boolean mRun = false;
57
58 /** Handle to the surface manager object we interact with */
59 private SurfaceHolder mSurfaceHolder;
60
61 private com.medievaltech.gui.Window wndMainMenu, wndBattleMap;
62
63 public DrawingThread(SurfaceHolder surfaceHolder, Context context, Handler handler) {
64 // get handles to some important objects
65 mSurfaceHolder = surfaceHolder;
66 mHandler = handler;
67 mContext = context;
68
69 mLinePaint = new Paint();
70 mLinePaint.setAntiAlias(true);
71 mLinePaint.setARGB(255, 0, 255, 0);
72
73 mTextPaint = new Paint();
74 mTextPaint.setAntiAlias(true);
75 mTextPaint.setARGB(255, 255, 255, 255);
76 mTextPaint.setTextSize(12);
77 mTextPaint.setTextAlign(Paint.Align.CENTER);
78
79 mButtonPaint = new Paint();
80 mButtonPaint.setAntiAlias(true);
81 mButtonPaint.setARGB(255, 0, 0, 0);
82 mButtonPaint.setTextSize(20);
83 mButtonPaint.setTextAlign(Paint.Align.CENTER);
84
85 mTilePaint1 = new Paint();
86 mTilePaint1.setAntiAlias(true);
87 mTilePaint1.setARGB(255, 0, 255, 0);
88
89 mTilePaint2 = new Paint();
90 mTilePaint2.setAntiAlias(true);
91 mTilePaint2.setARGB(255, 0, 0, 255);
92
93 mUnitPaint = new Paint();
94 mUnitPaint.setAntiAlias(true);
95 mUnitPaint.setARGB(255, 255, 0, 0);
96
97 wndMainMenu = new com.medievaltech.gui.Window(0, 0, 320, 450);;
98 wndMainMenu.addGUIObject("txtTitle", new Text("Main Menu", 100, 30, 120, 20, mTextPaint));
99 wndMainMenu.addGUIObject("btnNewGame", new Button("New Game", 100, 90, 120, 20, mLinePaint, mButtonPaint));
100 wndMainMenu.addGUIObject("btnLoadGame", new Button("Load Game", 100, 125, 120, 20, mLinePaint, mButtonPaint));
101 wndMainMenu.addGUIObject("btnMapEditor", new Button("Map Editor", 100, 160, 120, 20, mLinePaint, mButtonPaint));
102 wndMainMenu.addGUIObject("btnQuit", new Button("Quit", 100, 195, 120, 20, mLinePaint, mButtonPaint));
103
104 Tile grassTile = new Tile(mTilePaint1);
105 Tile oceanTile = new Tile(mTilePaint2);
106
107 mMap = new Map(grassTile, 6, 8);
108
109 boolean land = true;
110
111 for(int x=0; x<mMap.getWidth(); x++) {
112 for(int y=0; y<mMap.getHeight(); y++) {
113 if(land)
114 mMap.setTile(x, y, new Tile(grassTile));
115 else
116 mMap.setTile(x, y, new Tile(oceanTile));
117 land = !land;
118 }
119 land = !land;
120 }
121
122 mMap.getTile(2, 3).addUnit(new Soldier(mUnitPaint));
123 mMap.getTile(5, 7).addUnit(new Soldier(mUnitPaint));
124
125 mGameState = GameState.MAIN_MENU;
126 }
127
128 /**
129 * Starts the game, setting parameters for the current difficulty.
130 */
131 // I don't think this gets called now. maybe we should call it in the thread constructor
132 public void doStart() {
133 synchronized (mSurfaceHolder) {
134 mLastTime = System.currentTimeMillis() + 100;
135 setState(AppState.RUNNING);
136 Log.i("AdvanceWars", "Player's turn starting now");
137 mGameState = GameState.MAIN_MENU;
138 }
139 }
140
141 /**
142 * Pauses the physics update & animation.
143 */
144 public void pause() {
145 synchronized (mSurfaceHolder) {
146 if (mAppState == AppState.RUNNING) setState(AppState.PAUSE);
147 }
148 }
149
150 @Override
151 public void run() {
152 while (mRun) {
153 Canvas c = null;
154 try {
155 c = mSurfaceHolder.lockCanvas(null);
156 synchronized(mSurfaceHolder) {
157 if(mAppState == AppState.RUNNING)
158 updatePhysics();
159 doDraw(c);
160 }
161 } finally {
162 // do this in a finally so that if an exception is thrown
163 // during the above, we don't leave the Surface in an
164 // inconsistent state
165 if (c != null) {
166 mSurfaceHolder.unlockCanvasAndPost(c);
167 }
168 }
169 }
170 }
171
172 /**
173 * Used to signal the thread whether it should be running or not.
174 * Passing true allows the thread to run; passing false will shut it
175 * down if it's already running. Calling start() after this was most
176 * recently called with false will result in an immediate shutdown.
177 *
178 * @param b true to run, false to shut down
179 */
180 public void setRunning(boolean b) {
181 mRun = b;
182 }
183
184 /**
185 * Sets the game mode. That is, whether we are running, paused, in the
186 * failure state, in the victory state, etc.
187 *
188 * @see #setState(int, CharSequence)
189 * @param mode one of the STATE_* constants
190 */
191 public void setState(AppState state) {
192 synchronized (mSurfaceHolder) {
193 setState(state, null);
194 }
195 }
196
197 public void setGameState(GameState state) {
198 synchronized (mSurfaceHolder) {
199 mGameState = state;
200 }
201 }
202
203 /**
204 * Sets the game mode. That is, whether we are running, paused, in the
205 * failure state, in the victory state, etc.
206 *
207 * @param mode one of the STATE_* constants
208 * @param message string to add to screen or null
209 */
210 public void setState(AppState mode, CharSequence message) {
211 /*
212 * This method optionally can cause a text message to be displayed
213 * to the user when the mode changes. Since the View that actually
214 * renders that text is part of the main View hierarchy and not
215 * owned by this thread, we can't touch the state of that View.
216 * Instead we use a Message + Handler to relay commands to the main
217 * thread, which updates the user-text View.
218 */
219 synchronized (mSurfaceHolder) {
220 mAppState = mode;
221
222 if (mAppState == AppState.RUNNING) {
223 Message msg = mHandler.obtainMessage();
224 Bundle b = new Bundle();
225 b.putString("text", "");
226 b.putInt("viz", GameView.INVISIBLE);
227 msg.setData(b);
228 mHandler.sendMessage(msg);
229 } else {
230 CharSequence str = "";
231 str = "Mode probably changed";
232
233 if (message != null) {
234 str = message + "\n" + str;
235 }
236
237 Message msg = mHandler.obtainMessage();
238 Bundle b = new Bundle();
239 b.putString("text", str.toString());
240 b.putInt("viz", GameView.VISIBLE);
241 msg.setData(b);
242 //mHandler.sendMessage(msg);
243 }
244 }
245 }
246
247 /* Callback invoked when the surface dimensions change. */
248 public void setSurfaceSize(int width, int height) {
249 // synchronized to make sure these all change atomically
250 synchronized (mSurfaceHolder) {
251 mCanvasWidth = width;
252 mCanvasHeight = height;
253
254 Log.i("AdvanceWars", "width: "+mCanvasWidth+", height: "+mCanvasHeight);
255 }
256 }
257
258 /**
259 * Resumes from a pause.
260 */
261 public void unpause() {
262 // Move the real time clock up to now
263 synchronized (mSurfaceHolder) {
264 mLastTime = System.currentTimeMillis() + 100;
265 }
266 setState(AppState.RUNNING);
267 }
268
269 /**
270 * Handles a key-down event.
271 *
272 * @param keyCode the key that was pressed
273 * @param msg the original event object
274 * @return true
275 */
276 boolean doKeyDown(int keyCode, KeyEvent msg) {
277 synchronized (mSurfaceHolder) {
278 boolean okStart = false;
279 if (keyCode == KeyEvent.KEYCODE_DPAD_UP) okStart = true;
280 if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) okStart = true;
281 if (keyCode == KeyEvent.KEYCODE_S) okStart = true;
282
283 if (okStart
284 && (mAppState == AppState.READY || mAppState == AppState.LOSE || mAppState == AppState.WIN)) {
285 // ready-to-start -> start
286 doStart();
287 return true;
288 } else if (mAppState == AppState.PAUSE && okStart) {
289 // paused -> running
290 unpause();
291 return true;
292 } else if (mAppState == AppState.RUNNING) {
293 return true;
294 }
295
296 return false;
297 }
298 }
299
300 /**
301 * Handles a key-up event.
302 *
303 * @param keyCode the key that was pressed
304 * @param msg the original event object
305 * @return true if the key was handled and consumed, or else false
306 */
307 boolean doKeyUp(int keyCode, KeyEvent msg) {
308 boolean handled = false;
309
310 synchronized (mSurfaceHolder) {
311 if (mAppState == AppState.RUNNING) {
312 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
313 || keyCode == KeyEvent.KEYCODE_SPACE) {
314 handled = true;
315 } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
316 || keyCode == KeyEvent.KEYCODE_Q
317 || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
318 || keyCode == KeyEvent.KEYCODE_W) {
319 handled = true;
320 }
321 }
322 }
323
324 return handled;
325 }
326
327 /**
328 * Draws the ship, fuel/speed bars, and background to the provided
329 * Canvas.
330 */
331 private void doDraw(Canvas canvas) {
332 canvas.drawColor(Color.BLACK);
333
334 String text;
335 Paint.FontMetrics metrics = mTextPaint.getFontMetrics();
336
337 switch(mGameState) {
338 case MAIN_MENU:
339 wndMainMenu.draw(canvas);
340 break;
341 case BATTLE_MAP:
342 mTextPaint.setTextSize(12);
343
344 mMap.draw(canvas, 10, 25);
345
346 text = "Advance Wars grid test";
347 canvas.drawText(text, 0, 450-(metrics.ascent+metrics.descent)/2, mTextPaint);
348 break;
349 }
350 }
351
352 /**
353 * Figures the lander state (x, y, fuel, ...) based on the passage of
354 * realtime. Does not invalidate(). Called at the start of draw().
355 * Detects the end-of-game and sets the UI to the next state.
356 */
357 private void updatePhysics() {
358 long now = System.currentTimeMillis();
359
360 // Do nothing if mLastTime is in the future.
361 // This allows the game-start to delay the start of the physics
362 // by 100ms or whatever.
363 if (mLastTime > now) return;
364
365 // DO SHIT HERE
366
367 mLastTime = now+50;
368 }
369 }
370
371 /** Handle to the application context, used to e.g. fetch Drawables. */
372 private Context mContext;
373
374 /** Pointer to the text view to display "Paused.." etc. */
375 private TextView mStatusText;
376
377 /** The thread that actually draws the animation */
378 private DrawingThread thread;
379
380 public Game mGame;
381
382 public GameView(Context context, AttributeSet attrs) {
383 super(context, attrs);
384
385 // register our interest in hearing about changes to our surface
386 SurfaceHolder holder = getHolder();
387 holder.addCallback(this);
388
389 // create thread only; it's started in surfaceCreated()
390 thread = new DrawingThread(holder, context, new Handler() {
391 @Override
392 public void handleMessage(Message m) {
393 mStatusText.setVisibility(m.getData().getInt("viz"));
394 mStatusText.setText(m.getData().getString("text"));
395 }
396 });
397
398 setFocusable(true); // make sure we get key events
399 }
400
401 @Override public boolean onTouchEvent(MotionEvent event) {
402 Log.i("AdvanceWars", "Detected touch event");
403
404 if(event.getAction() == MotionEvent.ACTION_UP) {
405 Log.i("AdvanceWars", "Detected UP touch action");
406 switch(thread.mGameState) {
407 case MAIN_MENU:
408 Log.i("AdvanceWars", "Switching to battle map");
409 if(thread.wndMainMenu.getGUIObject("btnNewGame").isClicked(event.getX(), event.getY())) {
410 thread.mGameState = GameState.BATTLE_MAP;
411 }else if(thread.wndMainMenu.getGUIObject("btnLoadGame").isClicked(event.getX(), event.getY())) {
412 thread.mGameState = GameState.BATTLE_MAP;
413 }else if(thread.wndMainMenu.getGUIObject("btnQuit").isClicked(event.getX(), event.getY())) {
414 mGame.finish();
415 }
416 break;
417 case BATTLE_MAP:
418 Log.i("AdvanceWars", "Touch event detected on battle map");
419 thread.mGameState = GameState.MAIN_MENU;
420 break;
421 }
422 }else if(event.getAction() == MotionEvent.ACTION_DOWN) {
423
424 }
425
426 return true;
427 }
428
429 /**
430 * Fetches the animation thread corresponding to this LunarView.
431 *
432 * @return the animation thread
433 */
434 public DrawingThread getThread() {
435 return thread;
436 }
437
438 /**
439 * Standard override to get key-press events.
440 */
441 @Override
442 public boolean onKeyDown(int keyCode, KeyEvent msg) {
443 return thread.doKeyDown(keyCode, msg);
444 }
445
446 /**
447 * Standard override for key-up. We actually care about these, so we can
448 * turn off the engine or stop rotating.
449 */
450 @Override
451 public boolean onKeyUp(int keyCode, KeyEvent msg) {
452 return thread.doKeyUp(keyCode, msg);
453 }
454
455 /**
456 * Standard window-focus override. Notice focus lost so we can pause on
457 * focus lost. e.g. user switches to take a call.
458 */
459 @Override
460 public void onWindowFocusChanged(boolean hasWindowFocus) {
461 if (!hasWindowFocus) thread.pause();
462 }
463
464 /**
465 * Installs a pointer to the text view used for messages.
466 */
467 public void setTextView(TextView textView) {
468 mStatusText = textView;
469 }
470
471 /* Callback invoked when the surface dimensions change. */
472 public void surfaceChanged(SurfaceHolder holder, int format, int width,
473 int height) {
474 thread.setSurfaceSize(width, height);
475 }
476
477 /*
478 * Callback invoked when the Surface has been created and is ready to be
479 * used.
480 */
481 public void surfaceCreated(SurfaceHolder holder) {
482 // start the thread here so that we don't busy-wait in run()
483 // waiting for the surface to be created
484 thread.setRunning(true);
485
486 //if(thread.mAppState == AppState.PAUSE)
487 //thread.unpause();
488 //else
489 thread.start();
490 }
491
492 /*
493 * Callback invoked when the Surface has been destroyed and must no longer
494 * be touched. WARNING: after this method returns, the Surface/Canvas must
495 * never be touched again!
496 */
497 public void surfaceDestroyed(SurfaceHolder holder) {
498 // we have to tell thread to shut down & wait for it to finish, or else
499 // it might touch the Surface after we return and explode
500 boolean retry = true;
501 thread.setRunning(false);
502 while (retry) {
503 try {
504 thread.join();
505 retry = false;
506 } catch (InterruptedException e) {
507 }
508 }
509 }
510}
Note: See TracBrowser for help on using the repository browser.