renaming and moving samples around
[wxWidgets.git] / demos / life / life.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: life.cpp
3 // Purpose: The game of life, created by J. H. Conway
4 // Author: Guillermo Rodriguez Garcia, <guille@iies.es>
5 // Modified by:
6 // Created: Jan/2000
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000, Guillermo Rodriguez Garcia
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ==========================================================================
13 // declarations
14 // ==========================================================================
15
16 // minimum and maximum table size, in each dimension
17 #define LIFE_MIN 20
18 #define LIFE_MAX 200
19
20 // some shortcuts
21 #define ADD_TOOL(a, b, c, d) \
22 toolBar->AddTool(a, b, wxNullBitmap, FALSE, -1, -1, (wxObject *)0, c, d)
23
24 #define GET_FRAME() \
25 ((LifeFrame *) wxGetApp().GetTopWindow())
26
27 // --------------------------------------------------------------------------
28 // headers
29 // --------------------------------------------------------------------------
30
31 #ifdef __GNUG__
32 #pragma implementation "life.cpp"
33 #pragma interface "life.cpp"
34 #endif
35
36 // for compilers that support precompilation, includes "wx/wx.h".
37 #include "wx/wxprec.h"
38
39 #ifdef __BORLANDC__
40 #pragma hdrstop
41 #endif
42
43 // for all others, include the necessary headers
44 #ifndef WX_PRECOMP
45 #include "wx/wx.h"
46 #endif
47
48 #include "wx/statline.h"
49 #include "wx/spinctrl.h"
50
51 // --------------------------------------------------------------------------
52 // resources
53 // --------------------------------------------------------------------------
54
55 #if defined(__WXGTK__) || defined(__WXMOTIF__)
56 // the application icon
57 #include "mondrian.xpm"
58
59 // bitmap buttons for the toolbar
60 #include "bitmaps/reset.xpm"
61 #include "bitmaps/play.xpm"
62 #include "bitmaps/stop.xpm"
63 #endif
64
65 // --------------------------------------------------------------------------
66 // classes
67 // --------------------------------------------------------------------------
68
69 class Life;
70 class LifeShape;
71 class LifeCanvas;
72 class LifeTimer;
73 class LifeFrame;
74 class LifeApp;
75 class LifeNewGameDialog;
76 class LifeSamplesDialog;
77
78 // --------------------------------------------------------------------------
79 // non-GUI classes
80 // --------------------------------------------------------------------------
81
82 // Life
83 class Life
84 {
85 public:
86 // ctors and dtors
87 Life(int width, int height);
88 ~Life();
89 void Create(int width, int height);
90 void Destroy();
91
92 // accessors
93 inline int GetWidth() const { return m_width; };
94 inline int GetHeight() const { return m_height; };
95 inline bool IsAlive(int x, int y) const;
96 inline bool HasChanged(int x, int y) const;
97
98 // flags
99 void SetBorderWrap(bool on);
100
101 // game logic
102 void Clear();
103 void SetCell(int x, int y, bool alive = TRUE);
104 void SetShape(LifeShape &shape);
105 bool NextTic();
106
107 private:
108 enum CellFlags {
109 CELL_DEAD = 0x0000, // is dead
110 CELL_ALIVE = 0x0001, // is alive
111 CELL_MARK = 0x0002, // will change / has changed
112 };
113 typedef int Cell;
114
115 int GetNeighbors(int x, int y) const;
116 inline void SetCell(int x, int y, Cell status);
117
118 int m_width;
119 int m_height;
120 Cell *m_cells;
121 bool m_wrap;
122 };
123
124 // LifeShape
125 class LifeShape
126 {
127 public:
128 LifeShape::LifeShape(wxString name,
129 wxString desc,
130 int width, int height, char *data,
131 int fieldWidth = 20, int fieldHeight = 20,
132 bool wrap = TRUE)
133 {
134 m_name = name;
135 m_desc = desc;
136 m_width = width;
137 m_height = height;
138 m_data = data;
139 m_fieldWidth = fieldWidth;
140 m_fieldHeight = fieldHeight;
141 m_wrap = wrap;
142 }
143
144 wxString m_name;
145 wxString m_desc;
146 int m_width;
147 int m_height;
148 char *m_data;
149 int m_fieldWidth;
150 int m_fieldHeight;
151 bool m_wrap;
152 };
153
154 // --------------------------------------------------------------------------
155 // GUI classes
156 // --------------------------------------------------------------------------
157
158 // Life canvas
159 class LifeCanvas : public wxScrolledWindow
160 {
161 public:
162 // ctor and dtor
163 LifeCanvas(wxWindow* parent, Life* life, bool interactive = TRUE);
164 ~LifeCanvas();
165
166 // member functions
167 void Reset();
168 void DrawEverything(bool force = FALSE);
169 void DrawCell(int i, int j);
170 void DrawCell(int i, int j, wxDC &dc);
171 inline int CellToCoord(int i) const { return (i * m_cellsize); };
172 inline int CoordToCell(int x) const { return ((x >= 0)? (x / m_cellsize) : -1); };
173
174 // event handlers
175 void OnPaint(wxPaintEvent& event);
176 void OnMouse(wxMouseEvent& event);
177 void OnSize(wxSizeEvent& event);
178
179 private:
180 // any class wishing to process wxWindows events must use this macro
181 DECLARE_EVENT_TABLE()
182
183 enum MouseStatus {
184 MOUSE_NOACTION,
185 MOUSE_DRAWING,
186 MOUSE_ERASING
187 };
188
189 Life *m_life;
190 wxBitmap *m_bmp;
191 int m_height;
192 int m_width;
193 int m_cellsize;
194 wxCoord m_xoffset;
195 wxCoord m_yoffset;
196 MouseStatus m_status;
197 bool m_interactive;
198 };
199
200 // Life timer
201 class LifeTimer : public wxTimer
202 {
203 public:
204 void Notify();
205 };
206
207 // Life main frame
208 class LifeFrame : public wxFrame
209 {
210 public:
211 // ctor and dtor
212 LifeFrame();
213 ~LifeFrame();
214
215 // member functions
216 void UpdateInfoText();
217
218 // event handlers
219 void OnMenu(wxCommandEvent& event);
220 void OnNewGame(wxCommandEvent& event);
221 void OnSamples(wxCommandEvent& event);
222 void OnStart();
223 void OnStop();
224 void OnTimer();
225 void OnSlider(wxScrollEvent& event);
226
227 private:
228 // any class wishing to process wxWindows events must use this macro
229 DECLARE_EVENT_TABLE()
230
231 Life *m_life;
232 LifeTimer *m_timer;
233 LifeCanvas *m_canvas;
234 wxStaticText *m_text;
235 bool m_running;
236 long m_interval;
237 long m_tics;
238 };
239
240 // Life new game dialog
241 class LifeNewGameDialog : public wxDialog
242 {
243 public:
244 // ctor
245 LifeNewGameDialog(wxWindow *parent, int *w, int *h);
246
247 // event handlers
248 void OnOK(wxCommandEvent& event);
249
250 private:
251 // any class wishing to process wxWindows events must use this macro
252 DECLARE_EVENT_TABLE();
253
254 int *m_w;
255 int *m_h;
256 wxSpinCtrl *m_spinctrlw;
257 wxSpinCtrl *m_spinctrlh;
258 };
259
260 // Life sample configurations dialog
261 class LifeSamplesDialog : public wxDialog
262 {
263 public:
264 // ctor and dtor
265 LifeSamplesDialog(wxWindow *parent);
266 ~LifeSamplesDialog();
267
268 // members
269 int GetValue();
270
271 // event handlers
272 void OnListBox(wxCommandEvent &event);
273
274 private:
275 // any class wishing to process wxWindows events must use this macro
276 DECLARE_EVENT_TABLE();
277
278 int m_value;
279 wxListBox *m_list;
280 wxTextCtrl *m_text;
281 LifeCanvas *m_canvas;
282 Life *m_life;
283 };
284
285 // Life app
286 class LifeApp : public wxApp
287 {
288 public:
289 virtual bool OnInit();
290 };
291
292 // --------------------------------------------------------------------------
293 // constants
294 // --------------------------------------------------------------------------
295
296 // IDs for the controls and the menu commands
297 enum
298 {
299 // menu items and toolbar buttons
300 ID_NEWGAME = 1001,
301 ID_SAMPLES,
302 ID_ABOUT,
303 ID_EXIT,
304 ID_CLEAR,
305 ID_START,
306 ID_STEP,
307 ID_STOP,
308 ID_WRAP,
309
310 // speed selection slider
311 ID_SLIDER,
312
313 // listbox in samples dialog
314 ID_LISTBOX
315 };
316
317
318 // built-in sample games
319 #include "samples.inc"
320
321 // --------------------------------------------------------------------------
322 // event tables and other macros for wxWindows
323 // --------------------------------------------------------------------------
324
325 // Event tables
326 BEGIN_EVENT_TABLE(LifeFrame, wxFrame)
327 EVT_MENU (ID_NEWGAME, LifeFrame::OnNewGame)
328 EVT_MENU (ID_SAMPLES, LifeFrame::OnSamples)
329 EVT_MENU (ID_ABOUT, LifeFrame::OnMenu)
330 EVT_MENU (ID_EXIT, LifeFrame::OnMenu)
331 EVT_MENU (ID_CLEAR, LifeFrame::OnMenu)
332 EVT_MENU (ID_START, LifeFrame::OnMenu)
333 EVT_MENU (ID_STEP, LifeFrame::OnMenu)
334 EVT_MENU (ID_STOP, LifeFrame::OnMenu)
335 EVT_MENU (ID_WRAP, LifeFrame::OnMenu)
336 EVT_COMMAND_SCROLL (ID_SLIDER, LifeFrame::OnSlider)
337 END_EVENT_TABLE()
338
339 BEGIN_EVENT_TABLE(LifeCanvas, wxScrolledWindow)
340 EVT_PAINT ( LifeCanvas::OnPaint)
341 EVT_SIZE ( LifeCanvas::OnSize)
342 EVT_MOUSE_EVENTS ( LifeCanvas::OnMouse)
343 END_EVENT_TABLE()
344
345 BEGIN_EVENT_TABLE(LifeNewGameDialog, wxDialog)
346 EVT_BUTTON (wxID_OK, LifeNewGameDialog::OnOK)
347 END_EVENT_TABLE()
348
349 BEGIN_EVENT_TABLE(LifeSamplesDialog, wxDialog)
350 EVT_LISTBOX (ID_LISTBOX, LifeSamplesDialog::OnListBox)
351 END_EVENT_TABLE()
352
353
354 // Create a new application object
355 IMPLEMENT_APP(LifeApp)
356
357 // ==========================================================================
358 // implementation
359 // ==========================================================================
360
361 // --------------------------------------------------------------------------
362 // LifeApp
363 // --------------------------------------------------------------------------
364
365 // `Main program' equivalent: the program execution "starts" here
366 bool LifeApp::OnInit()
367 {
368 // create the main application window
369 LifeFrame *frame = new LifeFrame();
370
371 // show it and tell the application that it's our main window
372 frame->Show(TRUE);
373 SetTopWindow(frame);
374
375 // enter the main message loop and run the app
376 return TRUE;
377 }
378
379 // --------------------------------------------------------------------------
380 // LifeFrame
381 // --------------------------------------------------------------------------
382
383 // frame constructor
384 LifeFrame::LifeFrame() : wxFrame((wxFrame *)0, -1, _("Life!"), wxPoint(50, 50))
385 {
386 // frame icon
387 SetIcon(wxICON(mondrian));
388
389 // menu bar
390 wxMenu *menuFile = new wxMenu("", wxMENU_TEAROFF);
391 wxMenu *menuGame = new wxMenu("", wxMENU_TEAROFF);
392
393 menuFile->Append(ID_NEWGAME, _("New game..."), _("Start a new game"));
394 menuFile->Append(ID_SAMPLES, _("Sample game..."), _("Select a sample configuration"));
395 menuFile->AppendSeparator();
396 menuFile->Append(ID_ABOUT, _("&About...\tCtrl-A"), _("Show about dialog"));
397 menuFile->AppendSeparator();
398 menuFile->Append(ID_EXIT, _("E&xit\tAlt-X"), _("Quit this program"));
399
400 menuGame->Append(ID_CLEAR, _("&Clear\tCtrl-C"), _("Clear game field"));
401 menuGame->Append(ID_START, _("&Start\tCtrl-S"), _("Start"));
402 menuGame->Append(ID_STEP, _("&Next\tCtrl-N"), _("Single step"));
403 menuGame->Append(ID_STOP, _("S&top\tCtrl-T"), _("Stop"));
404 menuGame->Enable(ID_STOP, FALSE);
405 menuGame->AppendSeparator();
406 menuGame->Append(ID_WRAP, _("&Wraparound\tCtrl-W"), _("Wrap around borders"), TRUE);
407 menuGame->Check (ID_WRAP, TRUE);
408
409
410 wxMenuBar *menuBar = new wxMenuBar();
411 menuBar->Append(menuFile, _("&File"));
412 menuBar->Append(menuGame, _("&Game"));
413 SetMenuBar(menuBar);
414
415 // tool bar
416 wxBitmap tbBitmaps[3];
417
418 tbBitmaps[0] = wxBITMAP(reset);
419 tbBitmaps[1] = wxBITMAP(play);
420 tbBitmaps[2] = wxBITMAP(stop);
421
422 wxToolBar *toolBar = CreateToolBar();
423 toolBar->SetMargins(5, 5);
424 toolBar->SetToolBitmapSize(wxSize(16, 16));
425 ADD_TOOL(ID_CLEAR, tbBitmaps[0], _("Clear"), _("Clear game board"));
426 ADD_TOOL(ID_START, tbBitmaps[1], _("Start"), _("Start"));
427 ADD_TOOL(ID_STOP , tbBitmaps[2], _("Stop"), _("Stop"));
428 toolBar->EnableTool(ID_STOP, FALSE);
429 toolBar->Realize();
430
431 // status bar
432 CreateStatusBar(2);
433 SetStatusText(_("Welcome to Life!"));
434
435 // panel
436 wxPanel *panel = new wxPanel(this, -1);
437
438 // game
439 m_life = new Life(20, 20);
440 m_canvas = new LifeCanvas(panel, m_life);
441 m_timer = new LifeTimer();
442 m_interval = 500;
443 m_tics = 0;
444 m_text = new wxStaticText(panel, -1, "");
445 UpdateInfoText();
446
447 // slider
448 wxSlider *slider = new wxSlider(panel, ID_SLIDER, 5, 1, 10,
449 wxDefaultPosition, wxSize(200, -1), wxSL_HORIZONTAL | wxSL_AUTOTICKS);
450
451 // component layout
452 wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
453 sizer->Add(new wxStaticLine(panel, -1), 0, wxGROW | wxCENTRE);
454 sizer->Add(m_canvas, 1, wxGROW | wxCENTRE | wxALL, 5);
455 sizer->Add(new wxStaticLine(panel, -1), 0, wxGROW | wxCENTRE);
456 sizer->Add(m_text, 0, wxCENTRE | wxTOP, 5);
457 sizer->Add(slider, 0, wxCENTRE | wxALL, 5);
458 panel->SetSizer(sizer);
459 panel->SetAutoLayout(TRUE);
460 sizer->Fit(this);
461 sizer->SetSizeHints(this);
462 }
463
464 LifeFrame::~LifeFrame()
465 {
466 delete m_timer;
467 delete m_life;
468 }
469
470 void LifeFrame::UpdateInfoText()
471 {
472 wxString msg;
473
474 msg.Printf(_("Generation: %u, Interval: %u ms"), m_tics, m_interval);
475 m_text->SetLabel(msg);
476 }
477
478 // event handlers
479 void LifeFrame::OnMenu(wxCommandEvent& event)
480 {
481 switch (event.GetId())
482 {
483 case ID_START : OnStart(); break;
484 case ID_STEP : OnTimer(); break;
485 case ID_STOP : OnStop(); break;
486 case ID_WRAP :
487 {
488 bool checked = GetMenuBar()->GetMenu(1)->IsChecked(ID_WRAP);
489 m_life->SetBorderWrap(checked);
490 break;
491 }
492 case ID_CLEAR :
493 {
494 OnStop();
495 m_life->Clear();
496 m_canvas->DrawEverything(TRUE);
497 m_canvas->Refresh(FALSE);
498 m_tics = 0;
499 UpdateInfoText();
500 break;
501 }
502 case ID_ABOUT :
503 {
504 wxMessageBox(
505 _("This is the about dialog of the Life! sample.\n"
506 "(c) 2000 Guillermo Rodriguez Garcia"),
507 _("About Life!"),
508 wxOK | wxICON_INFORMATION,
509 this);
510 break;
511 }
512 case ID_EXIT :
513 {
514 // TRUE is to force the frame to close
515 Close(TRUE);
516 break;
517 }
518 }
519 }
520
521 void LifeFrame::OnNewGame(wxCommandEvent& WXUNUSED(event))
522 {
523 int w = m_life->GetWidth();
524 int h = m_life->GetHeight();
525
526 // stop if it was running
527 OnStop();
528
529 // dialog box
530 LifeNewGameDialog dialog(this, &w, &h);
531
532 // new game?
533 if (dialog.ShowModal() == wxID_OK)
534 {
535 // check dimensions
536 if (w >= LIFE_MIN && w <= LIFE_MAX &&
537 h >= LIFE_MIN && h <= LIFE_MAX)
538 {
539 // resize game field
540 m_life->Destroy();
541 m_life->Create(w, h);
542
543 // tell the canvas
544 m_canvas->Reset();
545 m_canvas->Refresh();
546 m_tics = 0;
547 UpdateInfoText();
548 }
549 else
550 {
551 wxString msg;
552 msg.Printf(_("Both dimensions must be within %u and %u.\n"),
553 LIFE_MIN, LIFE_MAX);
554 wxMessageBox(msg, _("Error!"), wxOK | wxICON_EXCLAMATION, this);
555 }
556 }
557 }
558
559 void LifeFrame::OnSamples(wxCommandEvent& WXUNUSED(event))
560 {
561 // stop if it was running
562 OnStop();
563
564 // dialog box
565 LifeSamplesDialog dialog(this);
566
567 // new game?
568 if (dialog.ShowModal() == wxID_OK)
569 {
570 int result = dialog.GetValue();
571
572 if (result == -1)
573 return;
574
575 int gw = g_shapes[result].m_fieldWidth;
576 int gh = g_shapes[result].m_fieldHeight;
577 int wrap = g_shapes[result].m_wrap;
578
579 // set wraparound (don't ask the user)
580 m_life->SetBorderWrap(wrap);
581 GetMenuBar()->GetMenu(1)->Check(ID_WRAP, wrap);
582
583 // need to resize the game field?
584 if (gw > m_life->GetWidth() || gh > m_life->GetHeight())
585 {
586 wxString s;
587 s.Printf(_("Your game field is too small for this configuration.\n"
588 "It is recommended to resize it to %u x %u. Proceed?\n"),
589 gw, gh);
590
591 if (wxMessageBox(s, _("Question"), wxYES_NO | wxICON_QUESTION, this) == wxYES)
592 {
593 m_life->Destroy();
594 m_life->Create(gw, gh);
595 }
596 }
597
598 // put the shape
599 m_life->SetShape(g_shapes[result]);
600
601 // tell the canvas about the change
602 m_canvas->Reset();
603 m_canvas->Refresh();
604 m_tics = 0;
605 UpdateInfoText();
606 }
607 }
608
609 void LifeFrame::OnStart()
610 {
611 if (!m_running)
612 {
613 GetToolBar()->EnableTool(ID_START, FALSE);
614 GetToolBar()->EnableTool(ID_STOP, TRUE);
615 GetMenuBar()->GetMenu(1)->Enable(ID_START, FALSE);
616 GetMenuBar()->GetMenu(1)->Enable(ID_STEP, FALSE);
617 GetMenuBar()->GetMenu(1)->Enable(ID_STOP, TRUE);
618
619 m_timer->Start(m_interval);
620 m_running = TRUE;
621 }
622 }
623
624 void LifeFrame::OnStop()
625 {
626 if (m_running)
627 {
628 GetToolBar()->EnableTool(ID_START, TRUE);
629 GetToolBar()->EnableTool(ID_STOP, FALSE);
630 GetMenuBar()->GetMenu(1)->Enable(ID_START, TRUE);
631 GetMenuBar()->GetMenu(1)->Enable(ID_STEP, TRUE);
632 GetMenuBar()->GetMenu(1)->Enable(ID_STOP, FALSE);
633
634 m_timer->Stop();
635 m_running = FALSE;
636 }
637 }
638
639 void LifeFrame::OnTimer()
640 {
641 if (m_life->NextTic())
642 m_tics++;
643 else
644 OnStop();
645
646 UpdateInfoText();
647 m_canvas->DrawEverything();
648 m_canvas->Refresh(FALSE);
649 }
650
651 void LifeFrame::OnSlider(wxScrollEvent& event)
652 {
653 m_interval = event.GetPosition() * 100;
654
655 // restart timer if running, to set the new interval
656 if (m_running)
657 {
658 m_timer->Stop();
659 m_timer->Start(m_interval);
660 }
661
662 UpdateInfoText();
663 }
664
665 // --------------------------------------------------------------------------
666 // LifeTimer
667 // --------------------------------------------------------------------------
668
669 void LifeTimer::Notify()
670 {
671 GET_FRAME()->OnTimer();
672 };
673
674 // --------------------------------------------------------------------------
675 // LifeCanvas
676 // --------------------------------------------------------------------------
677
678 // canvas constructor
679 LifeCanvas::LifeCanvas(wxWindow *parent, Life *life, bool interactive)
680 : wxScrolledWindow(parent, -1, wxPoint(0, 0), wxSize(100, 100))
681 {
682 m_life = life;
683 m_interactive = interactive;
684 m_cellsize = 8;
685 m_bmp = NULL;
686 Reset();
687 }
688
689 LifeCanvas::~LifeCanvas()
690 {
691 delete m_bmp;
692 }
693
694 void LifeCanvas::Reset()
695 {
696 if (m_bmp)
697 delete m_bmp;
698
699 m_status = MOUSE_NOACTION;
700 m_width = CellToCoord(m_life->GetWidth()) + 1;
701 m_height = CellToCoord(m_life->GetHeight()) + 1;
702 m_bmp = new wxBitmap(m_width, m_height);
703 wxCoord w = GetClientSize().GetX();
704 wxCoord h = GetClientSize().GetY();
705 m_xoffset = (w > m_width)? ((w - m_width) / 2) : 0;
706 m_yoffset = (h > m_height)? ((h - m_height) / 2) : 0;
707
708 // redraw everything
709 DrawEverything(TRUE);
710 SetScrollbars(10, 10, (m_width + 9) / 10, (m_height + 9) / 10);
711 }
712
713 void LifeCanvas::DrawEverything(bool force)
714 {
715 wxMemoryDC dc;
716
717 dc.SelectObject(*m_bmp);
718 dc.BeginDrawing();
719
720 // draw cells
721 for (int j = 0; j < m_life->GetHeight(); j++)
722 for (int i = 0; i < m_life->GetWidth(); i++)
723 if (force || m_life->HasChanged(i, j))
724 DrawCell(i, j, dc);
725
726 // bounding rectangle (always drawn - better than clipping region)
727 dc.SetPen(*wxBLACK_PEN);
728 dc.SetBrush(*wxTRANSPARENT_BRUSH);
729 dc.DrawRectangle(0, 0, m_width, m_height);
730
731 dc.EndDrawing();
732 dc.SelectObject(wxNullBitmap);
733 }
734
735 void LifeCanvas::DrawCell(int i, int j)
736 {
737 wxMemoryDC dc;
738
739 dc.SelectObject(*m_bmp);
740 dc.BeginDrawing();
741
742 dc.SetClippingRegion(1, 1, m_width - 2, m_height - 2);
743 DrawCell(i, j, dc);
744
745 dc.EndDrawing();
746 dc.SelectObject(wxNullBitmap);
747 }
748
749 void LifeCanvas::DrawCell(int i, int j, wxDC &dc)
750 {
751 if (m_life->IsAlive(i, j))
752 {
753 dc.SetPen(*wxBLACK_PEN);
754 dc.SetBrush(*wxBLACK_BRUSH);
755 dc.DrawRectangle(CellToCoord(i),
756 CellToCoord(j),
757 m_cellsize,
758 m_cellsize);
759 }
760 else
761 {
762 dc.SetPen(*wxLIGHT_GREY_PEN);
763 dc.SetBrush(*wxTRANSPARENT_BRUSH);
764 dc.DrawRectangle(CellToCoord(i),
765 CellToCoord(j),
766 m_cellsize,
767 m_cellsize);
768 dc.SetPen(*wxWHITE_PEN);
769 dc.SetBrush(*wxWHITE_BRUSH);
770 dc.DrawRectangle(CellToCoord(i) + 1,
771 CellToCoord(j) + 1,
772 m_cellsize - 1,
773 m_cellsize - 1);
774 }
775 }
776
777 // event handlers
778 void LifeCanvas::OnPaint(wxPaintEvent& event)
779 {
780 wxPaintDC dc(this);
781 wxMemoryDC memdc;
782
783 wxRegionIterator upd(GetUpdateRegion());
784 wxCoord x, y, w, h, xx, yy;
785
786 dc.BeginDrawing();
787 memdc.SelectObject(*m_bmp);
788
789 while(upd)
790 {
791 x = upd.GetX();
792 y = upd.GetY();
793 w = upd.GetW();
794 h = upd.GetH();
795 CalcUnscrolledPosition(x, y, &xx, &yy);
796
797 dc.Blit(x, y, w, h, &memdc, xx - m_xoffset, yy - m_yoffset);
798 upd++;
799 }
800
801 memdc.SelectObject(wxNullBitmap);
802 dc.EndDrawing();
803 }
804
805 void LifeCanvas::OnMouse(wxMouseEvent& event)
806 {
807 if (!m_interactive)
808 return;
809
810 int x, y, xx, yy, i, j;
811
812 // which cell are we pointing at?
813 x = event.GetX();
814 y = event.GetY();
815 CalcUnscrolledPosition(x, y, &xx, &yy);
816 i = CoordToCell( xx - m_xoffset );
817 j = CoordToCell( yy - m_yoffset );
818
819 // adjust x, y to point to the upper left corner of the cell
820 CalcScrolledPosition( CellToCoord(i) + m_xoffset,
821 CellToCoord(j) + m_yoffset,
822 &x, &y );
823
824 // set cursor shape and statusbar text
825 if (i < 0 || i >= m_life->GetWidth() ||
826 j < 0 || j >= m_life->GetHeight())
827 {
828 GET_FRAME()->SetStatusText(wxEmptyString, 1);
829 SetCursor(*wxSTANDARD_CURSOR);
830 }
831 else
832 {
833 wxString msg;
834 msg.Printf(_("Cell: (%u, %u)"), i, j);
835 GET_FRAME()->SetStatusText(msg, 1);
836 SetCursor(*wxCROSS_CURSOR);
837 }
838
839 // button pressed?
840 if (!event.LeftIsDown())
841 {
842 m_status = MOUSE_NOACTION;
843 }
844 else if (i >= 0 && i < m_life->GetWidth() &&
845 j >= 0 && j < m_life->GetHeight())
846 {
847 bool alive = m_life->IsAlive(i, j);
848
849 // if just pressed, update status
850 if (m_status == MOUSE_NOACTION)
851 m_status = (alive? MOUSE_ERASING : MOUSE_DRAWING);
852
853 // toggle cell and refresh if needed
854 if (((m_status == MOUSE_ERASING) && alive) ||
855 ((m_status == MOUSE_DRAWING) && !alive))
856 {
857 wxRect rect(x, y, m_cellsize + 1, m_cellsize + 1);
858 m_life->SetCell(i, j, !alive);
859 DrawCell(i, j);
860 Refresh(FALSE, &rect);
861 }
862 }
863 }
864
865 void LifeCanvas::OnSize(wxSizeEvent& event)
866 {
867 wxCoord w = event.GetSize().GetX();
868 wxCoord h = event.GetSize().GetY();
869 m_xoffset = (w > m_width)? ((w - m_width) / 2) : 0;
870 m_yoffset = (h > m_height)? ((h - m_height) / 2) : 0;
871
872 // allow default processing
873 event.Skip();
874 }
875
876 // --------------------------------------------------------------------------
877 // LifeNewGameDialog
878 // --------------------------------------------------------------------------
879
880 LifeNewGameDialog::LifeNewGameDialog(wxWindow *parent, int *w, int *h)
881 : wxDialog(parent, -1,
882 _("New game"),
883 wxDefaultPosition,
884 wxDefaultSize,
885 wxDEFAULT_DIALOG_STYLE | wxDIALOG_MODAL)
886 {
887 m_w = w;
888 m_h = h;
889
890 // spin ctrls
891 m_spinctrlw = new wxSpinCtrl( this, -1 );
892 m_spinctrlw->SetValue(*m_w);
893 m_spinctrlw->SetRange(LIFE_MIN, LIFE_MAX);
894
895 m_spinctrlh = new wxSpinCtrl( this, -1 );
896 m_spinctrlh->SetValue(*m_h);
897 m_spinctrlh->SetRange(LIFE_MIN, LIFE_MAX);
898
899 // component layout
900 wxBoxSizer *inputsizer1 = new wxBoxSizer( wxHORIZONTAL );
901 inputsizer1->Add( new wxStaticText(this, -1, _("Width")), 1, wxCENTRE | wxLEFT, 20);
902 inputsizer1->Add( m_spinctrlw, 2, wxCENTRE | wxLEFT | wxRIGHT, 20 );
903
904 wxBoxSizer *inputsizer2 = new wxBoxSizer( wxHORIZONTAL );
905 inputsizer2->Add( new wxStaticText(this, -1, _("Height")), 1, wxCENTRE | wxLEFT, 20);
906 inputsizer2->Add( m_spinctrlh, 2, wxCENTRE | wxLEFT | wxRIGHT, 20 );
907
908 wxBoxSizer *topsizer = new wxBoxSizer( wxVERTICAL );
909 topsizer->Add( CreateTextSizer(_("Enter board dimensions")), 0, wxALL, 10 );
910 topsizer->Add( new wxStaticLine(this, -1), 0, wxGROW | wxLEFT | wxRIGHT | wxBOTTOM, 10);
911 topsizer->Add( inputsizer1, 1, wxGROW | wxLEFT | wxRIGHT, 5 );
912 topsizer->Add( inputsizer2, 1, wxGROW | wxLEFT | wxRIGHT, 5 );
913 topsizer->Add( new wxStaticLine(this, -1), 0, wxGROW | wxLEFT | wxRIGHT | wxTOP, 10);
914 topsizer->Add( CreateButtonSizer(wxOK | wxCANCEL), 0, wxCENTRE | wxALL, 10);
915
916 // activate
917 SetSizer(topsizer);
918 SetAutoLayout(TRUE);
919 topsizer->SetSizeHints(this);
920 topsizer->Fit(this);
921 Centre(wxBOTH);
922 }
923
924 void LifeNewGameDialog::OnOK(wxCommandEvent& WXUNUSED(event))
925 {
926 *m_w = m_spinctrlw->GetValue();
927 *m_h = m_spinctrlh->GetValue();
928
929 EndModal(wxID_OK);
930 }
931
932 // --------------------------------------------------------------------------
933 // LifeSamplesDialog
934 // --------------------------------------------------------------------------
935
936 LifeSamplesDialog::LifeSamplesDialog(wxWindow *parent)
937 : wxDialog(parent, -1,
938 _("Sample games"),
939 wxDefaultPosition,
940 wxDefaultSize,
941 wxDEFAULT_DIALOG_STYLE | wxDIALOG_MODAL)
942 {
943 m_value = 0;
944
945 // create and populate the list of available samples
946 m_list = new wxListBox( this, ID_LISTBOX,
947 wxDefaultPosition,
948 wxDefaultSize,
949 0, NULL,
950 wxLB_SINGLE | wxLB_NEEDED_SB | wxLB_HSCROLL );
951
952 for (unsigned i = 0; i < (sizeof(g_shapes) / sizeof(LifeShape)); i++)
953 m_list->Append(g_shapes[i].m_name);
954
955 // descriptions
956 wxStaticBox *statbox = new wxStaticBox( this, -1, _("Description"));
957 m_life = new Life( 16, 16 );
958 m_life->SetShape(g_shapes[0]);
959 m_canvas = new LifeCanvas( this, m_life, FALSE );
960 m_text = new wxTextCtrl( this, -1,
961 g_shapes[0].m_desc,
962 wxDefaultPosition,
963 wxSize(300, 60),
964 wxTE_MULTILINE | wxTE_READONLY);
965
966 // layout components
967 wxStaticBoxSizer *sizer1 = new wxStaticBoxSizer( statbox, wxVERTICAL );
968 sizer1->Add( m_canvas, 2, wxGROW | wxCENTRE | wxALL, 5);
969 sizer1->Add( m_text, 1, wxGROW | wxCENTRE | wxALL, 5 );
970
971 wxBoxSizer *sizer2 = new wxBoxSizer( wxHORIZONTAL );
972 sizer2->Add( m_list, 0, wxGROW | wxCENTRE | wxALL, 5 );
973 sizer2->Add( sizer1, 1, wxGROW | wxCENTRE | wxALL, 5 );
974
975 wxBoxSizer *sizer3 = new wxBoxSizer( wxVERTICAL );
976 sizer3->Add( CreateTextSizer(_("Select one configuration")), 0, wxALL, 10 );
977 sizer3->Add( new wxStaticLine(this, -1), 0, wxGROW | wxLEFT | wxRIGHT, 10 );
978 sizer3->Add( sizer2, 1, wxGROW | wxCENTRE | wxALL, 5 );
979 sizer3->Add( new wxStaticLine(this, -1), 0, wxGROW | wxLEFT | wxRIGHT, 10 );
980 sizer3->Add( CreateButtonSizer(wxOK | wxCANCEL), 0, wxCENTRE | wxALL, 10 );
981
982 // activate
983 SetSizer(sizer3);
984 SetAutoLayout(TRUE);
985 sizer3->SetSizeHints(this);
986 sizer3->Fit(this);
987 Centre(wxBOTH);
988 }
989
990 LifeSamplesDialog::~LifeSamplesDialog()
991 {
992 m_canvas->Destroy();
993 delete m_life;
994 }
995
996 int LifeSamplesDialog::GetValue()
997 {
998 return m_value;
999 }
1000
1001 void LifeSamplesDialog::OnListBox(wxCommandEvent& event)
1002 {
1003 if (event.GetSelection() != -1)
1004 {
1005 m_value = m_list->GetSelection();
1006 m_text->SetValue(g_shapes[ event.GetSelection() ].m_desc);
1007 m_life->SetShape(g_shapes[ event.GetSelection() ]);
1008
1009 m_canvas->DrawEverything(TRUE); // force redraw everything
1010 m_canvas->Refresh(FALSE); // do not erase background
1011 }
1012 }
1013
1014 // --------------------------------------------------------------------------
1015 // Life
1016 // --------------------------------------------------------------------------
1017
1018 Life::Life(int width, int height)
1019 {
1020 m_wrap = TRUE;
1021 m_cells = NULL;
1022 Create(width, height);
1023 }
1024
1025 Life::~Life()
1026 {
1027 Destroy();
1028 }
1029
1030 void Life::Create(int width, int height)
1031 {
1032 wxASSERT(width > 0 && height > 0);
1033
1034 m_width = width;
1035 m_height = height;
1036 m_cells = new Cell[m_width * m_height];
1037 Clear();
1038 }
1039
1040 void Life::Destroy()
1041 {
1042 delete[] m_cells;
1043 }
1044
1045 void Life::Clear()
1046 {
1047 for (int i = 0; i < m_width * m_height; i++)
1048 m_cells[i] = CELL_DEAD;
1049 }
1050
1051 bool Life::IsAlive(int x, int y) const
1052 {
1053 wxASSERT(x >= 0 && y >= 0 && x < m_width && y < m_height);
1054
1055 return (m_cells[y * m_width + x] & CELL_ALIVE);
1056 }
1057
1058 bool Life::HasChanged(int x, int y) const
1059 {
1060 wxASSERT(x >= 0 && y >= 0 && x < m_width && y < m_height);
1061
1062 return (m_cells[y * m_width + x] & CELL_MARK) != 0;
1063 }
1064
1065 void Life::SetBorderWrap(bool on)
1066 {
1067 m_wrap = on;
1068 }
1069
1070 void Life::SetCell(int x, int y, bool alive)
1071 {
1072 wxASSERT(x >= 0 && y >= 0 && x < m_width && y < m_height);
1073
1074 m_cells[y * m_width + x] = (alive? CELL_ALIVE : CELL_DEAD);
1075 }
1076
1077 void Life::SetShape(LifeShape& shape)
1078 {
1079 wxASSERT((m_width >= shape.m_width) && (m_height >= shape.m_height));
1080
1081 int x0 = (m_width - shape.m_width) / 2;
1082 int y0 = (m_height - shape.m_height) / 2;
1083 char *p = shape.m_data;
1084
1085 Clear();
1086 for (int j = y0; j < y0 + shape.m_height; j++)
1087 for (int i = x0; i < x0 + shape.m_width; i++)
1088 SetCell(i, j, *(p++) == '*');
1089 }
1090
1091 bool Life::NextTic()
1092 {
1093 long changed = 0;
1094 int i, j;
1095
1096 /* 1st pass. Find and mark deaths and births for this generation.
1097 *
1098 * Rules:
1099 * An organism with <= 1 neighbors will die due to isolation.
1100 * An organism with >= 4 neighbors will die due to starvation.
1101 * New organisms are born in cells with exactly 3 neighbors.
1102 */
1103 for (j = 0; j < m_height; j++)
1104 for (i = 0; i < m_width; i++)
1105 {
1106 int neighbors = GetNeighbors(i, j);
1107 bool alive = IsAlive(i, j);
1108
1109 /* Set CELL_MARK if this cell must change, clear it
1110 * otherwise. We cannot toggle the CELL_ALIVE bit yet
1111 * because all deaths and births are simultaneous (it
1112 * would affect neighbouring cells).
1113 */
1114 if ((!alive && neighbors == 3) ||
1115 (alive && (neighbors <= 1 || neighbors >= 4)))
1116 m_cells[j * m_width + i] |= CELL_MARK;
1117 else
1118 m_cells[j * m_width + i] &= ~CELL_MARK;
1119 }
1120
1121 /* 2nd pass. Stabilize.
1122 */
1123 for (j = 0; j < m_height; j++)
1124 for (i = 0; i < m_width; i++)
1125 {
1126 /* Toggle CELL_ALIVE for those cells marked in the
1127 * previous pass. Do not clear the CELL_MARK bit yet;
1128 * it is useful to know which cells have changed and
1129 * thus must be updated in the screen.
1130 */
1131 if (m_cells[j * m_width + i] & CELL_MARK)
1132 {
1133 m_cells[j * m_width + i] ^= CELL_ALIVE;
1134 changed++;
1135 }
1136 }
1137
1138 return (changed != 0);
1139 }
1140
1141 int Life::GetNeighbors(int x, int y) const
1142 {
1143 wxASSERT(x >= 0 && y >= 0 && x < m_width && y < m_height);
1144
1145 int neighbors = 0;
1146
1147 int i0 = (x)? (x - 1) : 0;
1148 int j0 = (y)? (y - 1) : 0;
1149 int i1 = (x < (m_width - 1))? (x + 1) : (m_width - 1);
1150 int j1 = (y < (m_height - 1))? (y + 1) : (m_height - 1);
1151
1152 if (m_wrap && ( !x || !y || x == (m_width - 1) || y == (m_height - 1)))
1153 {
1154 // this is an outer cell and wraparound is on
1155 for (int j = y - 1; j <= y + 1; j++)
1156 for (int i = x - 1; i <= x + 1; i++)
1157 if (IsAlive( ((i < 0)? (i + m_width ) : (i % m_width)),
1158 ((j < 0)? (j + m_height) : (j % m_height)) ))
1159 neighbors++;
1160 }
1161 else
1162 {
1163 // this is an inner cell, or wraparound is off
1164 for (int j = j0; j <= j1; j++)
1165 for (int i = i0; i <= i1; i++)
1166 if (IsAlive(i, j))
1167 neighbors++;
1168 }
1169
1170 // do not count ourselves
1171 if (IsAlive(x, y)) neighbors--;
1172
1173 return neighbors;
1174 }
1175
1176 void Life::SetCell(int x, int y, Cell status)
1177 {
1178 wxASSERT(x >= 0 && y >= 0 && x < m_width && y < m_height);
1179
1180 m_cells[y * m_width + x] = status;
1181 }
1182