]>
git.saurik.com Git - wxWidgets.git/blob - samples/life/life.cpp
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: The game of life, created by J. H. Conway
4 // Author: Guillermo Rodriguez Garcia, <guille@iies.es>
8 // Copyright: (c) 2000, Guillermo Rodriguez Garcia
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ==========================================================================
14 // ==========================================================================
16 // minimum and maximum table size, in each dimension
21 #define ADD_TOOL(a, b, c, d) \
22 toolBar->AddTool(a, b, wxNullBitmap, FALSE, -1, -1, (wxObject *)0, c, d)
25 ((wxFrame *) wxGetApp().GetTopWindow())
27 // --------------------------------------------------------------------------
29 // --------------------------------------------------------------------------
32 #pragma implementation "life.cpp"
33 #pragma interface "life.cpp"
36 // for compilers that support precompilation, includes "wx/wx.h".
37 #include "wx/wxprec.h"
43 // for all others, include the necessary headers
48 #include "wx/statline.h"
49 #include "wx/spinctrl.h"
51 // --------------------------------------------------------------------------
53 // --------------------------------------------------------------------------
55 #if defined(__WXGTK__) || defined(__WXMOTIF__)
56 // the application icon
57 #include "mondrian.xpm"
59 // bitmap buttons for the toolbar
60 #include "bitmaps/reset.xpm"
61 #include "bitmaps/play.xpm"
62 #include "bitmaps/stop.xpm"
65 // --------------------------------------------------------------------------
67 // --------------------------------------------------------------------------
81 Life(int width
, int height
);
83 void Create(int width
, int height
);
87 inline int GetWidth() const { return m_width
; };
88 inline int GetHeight() const { return m_height
; };
89 inline bool IsAlive(int x
, int y
) const;
90 inline bool HasChanged(int x
, int y
) const;
91 inline void SetCell(int x
, int y
, bool alive
= TRUE
);
99 CELL_DEAD
= 0x0000, // is dead
100 CELL_ALIVE
= 0x0001, // is alive
101 CELL_MARK
= 0x0002, // will change / has changed
105 int GetNeighbors(int x
, int y
) const;
106 inline void SetCell(int x
, int y
, Cell status
);
114 class LifeCanvas
: public wxScrolledWindow
118 LifeCanvas(wxWindow
* parent
, Life
* life
);
123 void DrawEverything(bool force
= FALSE
);
124 void DrawCell(int i
, int j
);
125 void DrawCell(int i
, int j
, wxDC
&dc
);
126 inline int CellToCoord(int i
) const { return (i
* m_cellsize
); };
127 inline int CoordToCell(int x
) const { return ((x
>= 0)? (x
/ m_cellsize
) : -1); };
130 void OnPaint(wxPaintEvent
& event
);
131 void OnMouse(wxMouseEvent
& event
);
132 void OnSize(wxSizeEvent
& event
);
135 // any class wishing to process wxWindows events must use this macro
136 DECLARE_EVENT_TABLE()
152 MouseStatus m_status
;
156 class LifeTimer
: public wxTimer
159 LifeTimer(LifeFrame
*parent
);
167 class LifeFrame
: public wxFrame
175 void UpdateInfoText();
178 void OnMenu(wxCommandEvent
& event
);
179 void OnSlider(wxScrollEvent
& event
);
186 // any class wishing to process wxWindows events must use this macro
187 DECLARE_EVENT_TABLE()
191 LifeCanvas
*m_canvas
;
192 wxStaticText
*m_text
;
198 // Life new game dialog
199 class LifeNewGameDialog
: public wxDialog
203 LifeNewGameDialog(wxWindow
*parent
, int *w
, int *h
);
206 void OnOK(wxCommandEvent
& event
);
207 void OnCancel(wxCommandEvent
& event
);
210 // any class wishing to process wxWindows events must use this macro
211 DECLARE_EVENT_TABLE();
215 wxSpinCtrl
*m_spinctrlw
;
216 wxSpinCtrl
*m_spinctrlh
;
220 class LifeApp
: public wxApp
223 virtual bool OnInit();
227 // --------------------------------------------------------------------------
229 // --------------------------------------------------------------------------
231 // IDs for the controls and the menu commands
234 // menu items and toolbar buttons
246 // --------------------------------------------------------------------------
247 // event tables and other macros for wxWindows
248 // --------------------------------------------------------------------------
252 BEGIN_EVENT_TABLE(LifeFrame
, wxFrame
)
253 EVT_MENU_RANGE (ID_NEWGAME
, ID_ABOUT
, LifeFrame::OnMenu
)
254 EVT_COMMAND_SCROLL (ID_SLIDER
, LifeFrame::OnSlider
)
257 BEGIN_EVENT_TABLE(LifeCanvas
, wxScrolledWindow
)
258 EVT_PAINT ( LifeCanvas::OnPaint
)
259 EVT_SIZE ( LifeCanvas::OnSize
)
260 EVT_MOUSE_EVENTS ( LifeCanvas::OnMouse
)
263 BEGIN_EVENT_TABLE(LifeNewGameDialog
, wxDialog
)
264 EVT_BUTTON (wxID_OK
, LifeNewGameDialog::OnOK
)
265 EVT_BUTTON (wxID_CANCEL
, LifeNewGameDialog::OnCancel
)
269 // Create a new application object
270 IMPLEMENT_APP(LifeApp
)
272 // ==========================================================================
274 // ==========================================================================
276 // --------------------------------------------------------------------------
278 // --------------------------------------------------------------------------
280 // `Main program' equivalent: the program execution "starts" here
281 bool LifeApp::OnInit()
283 // create the main application window
284 LifeFrame
*frame
= new LifeFrame();
286 // show it and tell the application that it's our main window
290 // enter the main message loop and run the app
294 // --------------------------------------------------------------------------
296 // --------------------------------------------------------------------------
299 LifeFrame::LifeFrame() : wxFrame((wxFrame
*)0, -1, _("Life!"), wxPoint(50, 50))
302 SetIcon(wxICON(mondrian
));
305 wxMenu
*menuFile
= new wxMenu("", wxMENU_TEAROFF
);
307 menuFile
->Append(ID_NEWGAME
, _("&New game...\tCtrl-N"), _("Start a new game"));
308 menuFile
->Append(ID_CLEAR
, _("&Clear\tCtrl-C"), _("Clear game board"));
309 menuFile
->Append(ID_START
, _("&Start\tCtrl-S"), _("Start"));
310 menuFile
->Append(ID_STOP
, _("S&top\tCtrl-T"), _("Stop"));
311 menuFile
->AppendSeparator();
312 menuFile
->Append(ID_ABOUT
, _("&About...\tCtrl-A"), _("Show about dialog"));
313 menuFile
->AppendSeparator();
314 menuFile
->Append(ID_EXIT
, _("E&xit\tAlt-X"), _("Quit this program"));
315 menuFile
->Enable(ID_STOP
, FALSE
);
317 wxMenuBar
*menuBar
= new wxMenuBar();
318 menuBar
->Append(menuFile
, _("&File"));
322 wxBitmap tbBitmaps
[3];
323 tbBitmaps
[0] = wxBITMAP(reset
);
324 tbBitmaps
[1] = wxBITMAP(play
);
325 tbBitmaps
[2] = wxBITMAP(stop
);
327 wxToolBar
*toolBar
= CreateToolBar();
328 toolBar
->SetMargins(5, 5);
329 toolBar
->SetToolBitmapSize(wxSize(16, 16));
330 ADD_TOOL(ID_CLEAR
, tbBitmaps
[0], _("Clear"), _("Clear game board"));
331 ADD_TOOL(ID_START
, tbBitmaps
[1], _("Start"), _("Start"));
332 ADD_TOOL(ID_STOP
, tbBitmaps
[2], _("Stop"), _("Stop"));
333 toolBar
->EnableTool(ID_STOP
, FALSE
);
338 SetStatusText(_("Welcome to Life!"));
341 wxPanel
*panel
= new wxPanel(this, -1);
344 m_life
= new Life(20, 20);
345 m_canvas
= new LifeCanvas(panel
, m_life
);
346 m_timer
= new LifeTimer(this);
349 m_text
= new wxStaticText(panel
, -1, "");
353 wxSlider
*slider
= new wxSlider(panel
, ID_SLIDER
, 5, 1, 10,
354 wxDefaultPosition
, wxDefaultSize
, wxSL_HORIZONTAL
| wxSL_AUTOTICKS
);
357 wxBoxSizer
*sizer
= new wxBoxSizer(wxVERTICAL
);
358 sizer
->Add(m_canvas
, 1, wxGROW
| wxCENTRE
| wxALL
, 5);
359 sizer
->Add(new wxStaticLine(panel
, -1), 0, wxGROW
| wxCENTRE
);
360 sizer
->Add(m_text
, 0, wxCENTRE
| wxNORTH
, 5);
361 sizer
->Add(slider
, 0, wxCENTRE
| wxALL
, 5);
362 panel
->SetSizer(sizer
);
363 panel
->SetAutoLayout(TRUE
);
365 sizer
->SetSizeHints(this);
368 LifeFrame::~LifeFrame()
374 void LifeFrame::UpdateInfoText()
378 msg
.Printf(_("Generation: %u, Interval: %u ms"), m_tics
, m_interval
);
379 m_text
->SetLabel(msg
);
383 void LifeFrame::OnMenu(wxCommandEvent
& event
)
385 switch (event
.GetId())
387 case ID_START
: OnStart(); break;
388 case ID_STOP
: OnStop(); break;
389 case ID_NEWGAME
: OnNewGame(); break;
394 m_canvas
->DrawEverything(TRUE
);
395 m_canvas
->Refresh(FALSE
);
403 _("This is the about dialog of the Life! sample.\n"
404 "(c) 2000 Guillermo Rodriguez Garcia"),
406 wxOK
| wxICON_INFORMATION
,
412 // TRUE is to force the frame to close
419 void LifeFrame::OnSlider(wxScrollEvent
& event
)
421 m_interval
= event
.GetPosition() * 100;
423 // restart timer if running, to set the new interval
427 m_timer
->Start(m_interval
);
433 void LifeFrame::OnNewGame()
435 int w
= m_life
->GetWidth();
436 int h
= m_life
->GetHeight();
439 // stop if it was running
443 LifeNewGameDialog
dialog(this, &w
, &h
);
444 result
= dialog
.ShowModal();
447 if (result
== wxID_OK
)
450 if (w
>= LIFE_MIN
&& w
<= LIFE_MAX
&&
451 h
>= LIFE_MIN
&& h
<= LIFE_MAX
)
454 m_life
->Create(w
, h
);
462 msg
.Printf(_("Both dimensions must be within %u and %u.\n"),
464 wxMessageBox(msg
, _("Error!"), wxOK
| wxICON_EXCLAMATION
, this);
469 void LifeFrame::OnStart()
471 GetToolBar()->EnableTool(ID_START
, FALSE
);
472 GetToolBar()->EnableTool(ID_STOP
, TRUE
);
473 GetMenuBar()->GetMenu(0)->Enable(ID_START
, FALSE
);
474 GetMenuBar()->GetMenu(0)->Enable(ID_STOP
, TRUE
);
476 m_timer
->Start(m_interval
);
480 void LifeFrame::OnStop()
482 GetToolBar()->EnableTool(ID_START
, TRUE
);
483 GetToolBar()->EnableTool(ID_STOP
, FALSE
);
484 GetMenuBar()->GetMenu(0)->Enable(ID_START
, TRUE
);
485 GetMenuBar()->GetMenu(0)->Enable(ID_STOP
, FALSE
);
491 void LifeFrame::OnTimer()
497 m_canvas
->DrawEverything();
498 m_canvas
->Refresh(FALSE
);
501 // --------------------------------------------------------------------------
503 // --------------------------------------------------------------------------
505 LifeTimer::LifeTimer(LifeFrame
*parent
) : wxTimer()
510 void LifeTimer::Notify()
515 // --------------------------------------------------------------------------
517 // --------------------------------------------------------------------------
519 // canvas constructor
520 LifeCanvas::LifeCanvas(wxWindow
*parent
, Life
*life
)
521 : wxScrolledWindow(parent
, -1, wxPoint(0, 0), wxSize(100, 100))
528 LifeCanvas::~LifeCanvas()
533 void LifeCanvas::Reset()
538 m_status
= MOUSE_NOACTION
;
539 m_width
= CellToCoord(m_life
->GetWidth()) + 1;
540 m_height
= CellToCoord(m_life
->GetHeight()) + 1;
541 m_bmp
= new wxBitmap(m_width
, m_height
);
542 wxCoord w
= GetSize().GetX();
543 wxCoord h
= GetSize().GetY();
544 m_xoffset
= (w
> m_width
)? ((w
- m_width
) / 2) : 0;
545 m_yoffset
= (h
> m_height
)? ((h
- m_height
) / 2) : 0;
547 // redraw all, incl. background
548 DrawEverything(TRUE
);
549 SetScrollbars(10, 10, (m_width
+ 9) / 10, (m_height
+ 9) / 10);
553 void LifeCanvas::DrawEverything(bool force
)
557 dc
.SelectObject(*m_bmp
);
561 for (int j
= 0; j
< m_life
->GetHeight(); j
++)
562 for (int i
= 0; i
< m_life
->GetWidth(); i
++)
563 if (force
|| m_life
->HasChanged(i
, j
))
566 // bounding rectangle (always drawn)
567 dc
.SetPen(*wxBLACK_PEN
);
568 dc
.SetBrush(*wxTRANSPARENT_BRUSH
);
569 dc
.DrawRectangle(0, 0, m_width
, m_height
);
572 dc
.SelectObject(wxNullBitmap
);
575 // draw a single cell
576 void LifeCanvas::DrawCell(int i
, int j
)
580 dc
.SelectObject(*m_bmp
);
586 dc
.SelectObject(wxNullBitmap
);
589 void LifeCanvas::DrawCell(int i
, int j
, wxDC
&dc
)
591 if (m_life
->IsAlive(i
, j
))
593 dc
.SetPen(*wxBLACK_PEN
);
594 dc
.SetBrush(*wxBLACK_BRUSH
);
595 dc
.DrawRectangle(CellToCoord(i
),
602 dc
.SetPen(*wxLIGHT_GREY_PEN
);
603 dc
.SetBrush(*wxTRANSPARENT_BRUSH
);
604 dc
.DrawRectangle(CellToCoord(i
),
608 dc
.SetPen(*wxWHITE_PEN
);
609 dc
.SetBrush(*wxWHITE_BRUSH
);
610 dc
.DrawRectangle(CellToCoord(i
) + 1,
618 void LifeCanvas::OnPaint(wxPaintEvent
& event
)
623 wxRegionIterator
upd(GetUpdateRegion());
624 int x
, y
, w
, h
, xx
, yy
;
627 memdc
.SelectObject(*m_bmp
);
635 CalcUnscrolledPosition(x
, y
, &xx
, &yy
);
637 dc
.Blit(x
, y
, w
, h
, &memdc
, xx
- m_xoffset
, yy
- m_yoffset
);
641 memdc
.SelectObject(wxNullBitmap
);
645 void LifeCanvas::OnMouse(wxMouseEvent
& event
)
647 int x
, y
, xx
, yy
, i
, j
;
649 // which cell are we pointing at?
652 CalcUnscrolledPosition(x
, y
, &xx
, &yy
);
653 i
= CoordToCell( xx
- m_xoffset
);
654 j
= CoordToCell( yy
- m_yoffset
);
656 // adjust x, y to point to the upper left corner of the cell
657 CalcScrolledPosition( CellToCoord(i
) + m_xoffset
,
658 CellToCoord(j
) + m_yoffset
,
661 // set cursor shape and statusbar text
662 if (i
< 0 || i
>= m_life
->GetWidth() ||
663 j
< 0 || j
>= m_life
->GetHeight())
665 GET_FRAME()->SetStatusText(wxEmptyString
, 1);
666 SetCursor(*wxSTANDARD_CURSOR
);
671 msg
.Printf(_("Cell: (%u, %u)"), i
, j
);
672 GET_FRAME()->SetStatusText(msg
, 1);
673 SetCursor(*wxCROSS_CURSOR
);
677 if (!event
.LeftIsDown())
679 m_status
= MOUSE_NOACTION
;
681 else if (i
>= 0 && i
< m_life
->GetWidth() &&
682 j
>= 0 && j
< m_life
->GetHeight())
684 bool alive
= m_life
->IsAlive(i
, j
);
686 // if just pressed, update status
687 if (m_status
== MOUSE_NOACTION
)
688 m_status
= (alive
? MOUSE_ERASING
: MOUSE_DRAWING
);
690 // toggle cell and refresh if needed
691 if (((m_status
== MOUSE_ERASING
) && alive
) ||
692 ((m_status
== MOUSE_DRAWING
) && !alive
))
694 wxRect
rect(x
, y
, m_cellsize
+ 1, m_cellsize
+ 1);
695 m_life
->SetCell(i
, j
, !alive
);
697 Refresh(FALSE
, &rect
);
702 void LifeCanvas::OnSize(wxSizeEvent
& event
)
704 wxCoord w
= event
.GetSize().GetX();
705 wxCoord h
= event
.GetSize().GetY();
706 m_xoffset
= (w
> m_width
)? ((w
- m_width
) / 2) : 0;
707 m_yoffset
= (h
> m_height
)? ((h
- m_height
) / 2) : 0;
709 // allow default processing
713 // --------------------------------------------------------------------------
715 // --------------------------------------------------------------------------
717 LifeNewGameDialog::LifeNewGameDialog(wxWindow
*parent
, int *w
, int *h
)
718 : wxDialog(parent
, -1, _("New game"),
719 wxDefaultPosition
, wxDefaultSize
,
720 wxDEFAULT_DIALOG_STYLE
| wxDIALOG_MODAL
)
725 wxBoxSizer
*topsizer
= new wxBoxSizer( wxVERTICAL
);
728 topsizer
->Add( CreateTextSizer(_("Enter board dimensions")), 0, wxALL
, 10 );
729 topsizer
->Add( new wxStaticLine(this, -1), 0, wxGROW
| wxLEFT
| wxRIGHT
| wxBOTTOM
, 10);
731 // prompts and text controls
733 strw
.Printf(_("%u"), *m_w
);
734 strh
.Printf(_("%u"), *m_h
);
735 m_spinctrlw
= new wxSpinCtrl( this, -1, strw
);
736 m_spinctrlh
= new wxSpinCtrl( this, -1, strh
);
738 wxBoxSizer
*inputsizer1
= new wxBoxSizer( wxHORIZONTAL
);
739 inputsizer1
->Add( new wxStaticText(this, -1, _("Width")), 1, wxCENTER
| wxLEFT
, 20);
740 inputsizer1
->Add( m_spinctrlw
, 2, wxCENTER
| wxLEFT
| wxRIGHT
, 20 );
741 wxBoxSizer
*inputsizer2
= new wxBoxSizer( wxHORIZONTAL
);
742 inputsizer2
->Add( new wxStaticText(this, -1, _("Height")), 1, wxCENTER
| wxLEFT
, 20);
743 inputsizer2
->Add( m_spinctrlh
, 2, wxCENTER
| wxLEFT
| wxRIGHT
, 20 );
745 topsizer
->Add( inputsizer1
, 1, wxGROW
| wxLEFT
| wxRIGHT
, 5 );
746 topsizer
->Add( inputsizer2
, 1, wxGROW
| wxLEFT
| wxRIGHT
, 5 );
747 topsizer
->Add( new wxStaticLine(this, -1), 0, wxGROW
| wxLEFT
| wxRIGHT
| wxTOP
, 10);
750 topsizer
->Add( CreateButtonSizer(wxOK
| wxCANCEL
), 0, wxCENTRE
| wxALL
, 10);
755 topsizer
->SetSizeHints(this);
760 void LifeNewGameDialog::OnOK(wxCommandEvent
& WXUNUSED(event
))
762 *m_w
= m_spinctrlw
->GetValue();
763 *m_h
= m_spinctrlh
->GetValue();
768 void LifeNewGameDialog::OnCancel(wxCommandEvent
& WXUNUSED(event
))
773 EndModal(wxID_CANCEL
);
776 // --------------------------------------------------------------------------
778 // --------------------------------------------------------------------------
780 Life::Life(int width
, int height
)
782 Create(width
, height
);
790 void Life::Create(int width
, int height
)
792 wxASSERT(width
> 0 || height
> 0);
796 m_cells
= new Cell
[m_width
* m_height
];
807 for (int i
= 0; i
< m_width
* m_height
; i
++)
808 m_cells
[i
] = CELL_DEAD
;
811 bool Life::IsAlive(int x
, int y
) const
813 wxASSERT(x
< m_width
|| y
< m_height
);
815 return (m_cells
[y
* m_width
+ x
] & CELL_ALIVE
);
818 bool Life::HasChanged(int x
, int y
) const
820 wxASSERT(x
< m_width
|| y
< m_height
);
822 return (m_cells
[y
* m_width
+ x
] & CELL_MARK
);
825 void Life::SetCell(int x
, int y
, bool alive
)
827 wxASSERT(x
< m_width
|| y
< m_height
);
829 // set the CELL_MARK flag to notify that this cell has changed
830 m_cells
[y
* m_width
+ x
] = (alive
? CELL_ALIVE
: CELL_DEAD
);
835 /* 1st pass. Find and mark deaths and births for this generation.
838 * An organism with <= 1 neighbors will die due to isolation.
839 * An organism with >= 4 neighbors will die due to starvation.
840 * New organisms are born in cells with exactly 3 neighbors.
842 for (int j
= 0; j
< m_height
; j
++)
843 for (int i
= 0; i
< m_width
; i
++)
845 int neighbors
= GetNeighbors(i
, j
);
846 bool alive
= IsAlive(i
, j
);
848 /* Set CELL_MARK if this cell must change, clear it
849 * otherwise. We cannot toggle the CELL_ALIVE bit yet
850 * because all deaths and births are simultaneous (it
851 * would affect neighbouring cells).
853 if ((!alive
&& neighbors
== 3) ||
854 (alive
&& (neighbors
<= 1 || neighbors
>= 4)))
855 m_cells
[j
* m_width
+ i
] |= CELL_MARK
;
857 m_cells
[j
* m_width
+ i
] &= ~CELL_MARK
;
860 /* 2nd pass. Stabilize.
862 for (int j
= 0; j
< m_height
; j
++)
863 for (int i
= 0; i
< m_width
; i
++)
865 /* Toggle CELL_ALIVE for those cells marked in the
866 * previous pass. Do not clear the CELL_MARK bit yet;
867 * it is useful to know which cells have changed and
868 * thus must be updated in the screen.
870 if (m_cells
[j
* m_width
+ i
] & CELL_MARK
)
871 m_cells
[j
* m_width
+ i
] ^= CELL_ALIVE
;
875 int Life::GetNeighbors(int x
, int y
) const
877 wxASSERT(x
< m_width
|| y
< m_height
);
879 // count number of neighbors (wrap around board limits)
881 for (int j
= y
- 1; j
<= y
+ 1; j
++)
882 for (int i
= x
- 1; i
<= x
+ 1; i
++)
884 if (IsAlive( ((i
< 0)? (i
+ m_width
) : (i
% m_width
)),
885 ((j
< 0)? (j
+ m_height
) : (j
% m_height
)) ))
889 // do not count ourselves
890 if (IsAlive(x
, y
)) neighbors
--;
895 void Life::SetCell(int x
, int y
, Cell status
)
897 wxASSERT(x
< m_width
|| y
< m_height
);
899 m_cells
[y
* m_width
+ x
] = status
;