id
int64
0
25.6k
text
stringlengths
0
4.59k
19,100
graphic objects are used for specific conceptsfor example filing cabinets for disks or waste bin for file disposal (these could be regarded as desk accessories)various application programs are displayed on the screenthese stand for tools that you might use on your desktop in order to interact with this displaythe wimp user is provided with mouse (or light pen or touch sensitive screen)which can be used to select icons and menus or to manipulate windows the software basis of any wimp style environment is the window manager it controls the multiplepossibly overlapping windows and icons displayed on the screen it also handles the transfer of information about events which occur in those windows to the appropriate application and generates the various menus and prompts used window is an area of the graphic screen in which page or piece of page of information may be displayedit may display textgraphics or combination of both these windows may be overlappingand associated with the same processor they may be associated with separate processes windows can generally be createdopenedclosedmoved and resized an icon is small graphic object that is usually symbolic of an operation or of larger entity such as an application program or file the opening of an icon causes either the associated application to execute or the associated window to be displayed at the heart of the users ability to interact with such wimp based programs is the event loop this loop listens for events such as the user clicking button or selecting menu item or entering text field when such an event occurs it triggers the associated behaviour (such as running function linked with button windowing frameworks for python python is cross platform programming language as such python programs can be written on one platform (such as linux boxand then run on that platform or another operating system platform (such as windows or mac osthis can however generate issues for libraries that need to be available across multiple operating system platforms the area of guis is particularly an issue as library written to exploit features available in the microsoft windows system may not be available (or may look differenton mac os or linux systems each operating system that python runs on may have one or more windowing systems written for it and these systems may or may not be available on other operating systems this makes the job of providing gui library for python that much more difficult
19,101
graphical user interfaces developers of python guis have taken one of two approaches to handle thisone approach is to write wrapper that abstracts the underlying gui facilities so that the developer works at level above specific windowing system' facilities the python library then maps (as best it canthe facilities to the underlying system that is currently being used the other approach is to provide closer wrapping to particular set of facilities on the underlying gui system and to only target systems that support those facilities some of the libraries available for python are listed below and have been categorised into platform-independent libraries and platform-specific librariesplatform-independent gui libraries tkinter this is the standard built-in python gui library it is built on top of the tcl/tk widget set that has been around for very many years for many different operating systems tcl stands for tool command language while tk is the graphical user interface toolkit for tcl wxpython wxwidgets is freehighly portable gui library its is written in cand it can provide native look and feel on operating systems such as windowsmac oslinux etc wxpython is set of python bindings for wxwidgets this is the library that we will be using in this pyqt or pyside both of these libraries wrap the qt toolkit facilities qt is cross platform software development system for the implementation of guis and applications platform-specific gui libraries pyobjc is mac os specific library that provides an objective- bridge to the apple mac cocoa gui libraries pythonwin provides set of wrappings around the microsoft windows foundation classes and can be used to create windows based guis
19,102
online resources there are numerous online references that support the development of guis and of python guis in particularincludingdevelopment library macos cocoa library bridge pythonwin
19,103
the wxpython gui library the wxpython library the wxpython library is cross platform gui library (or toolkitfor python it allows programmers to develop highly graphical user interfaces for their programs using common concepts such as menu barsmenusbuttonsfieldspanels and frames in wxpython all the elements of gui are contained within top level windows such as wx frame or wx dialog these windows contain graphical components known as widgets or controls these widgets/controls may be grouped together into panels (which may or may not have visible representationthus in wxpython we might construct gui fromframes which provide the basic structure for windowbordersa label and some basic functionality ( resizingdialogs which are like frames but provide fewer border controls widgets/controls that are graphical objects displayed in frame some other languages refer to them as ui components examples of widgets are buttonscheckboxesselection listslabels and text fields containers are component that are made up of one or more other components (or containersall the components within container (such as panelcan be treated as single entity thus gui is constructed hierarchically from set of widgetscontainers and one or more frames (or in the case of pop up dialog then dialogsthis is illustrated below for window containing several panels and widgets(cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,104
the wxpython gui library windows such as frames and dialogs have component hierarchy that is used (amongst other thingsto determine how and when elements of the window are drawn and redrawn the component hierarchy is rooted with the framewithin which components and containers can be added the above figure illustrates component hierarchy for framewith two container panels and few basic widgets/ui components held within the panels note that panel can contain another sub panel with different widgets in wxpython modules the wxpython library is comprised of many different modules these modules provide different features from the core wx module to the html oriented wx html and wx html modules these modules includewx which holds the core widgets and classes in the wx library wx adv that provides less commonly used or more advanced widgets and classes wx grid contains widgets and classes supporting the display and editing of tabular data wx richtext consists of widgets and classes used for displaying multiple text styles and images wx html comprises widgets and supporting classes for generic html renderer wx html provides further widget and supporting classes for native html rendererwith css and javascript support
19,105
windows as objects in wxpythonframes and dialogs as well as their contents are instances of appropriate classes (such as framedialogpanelbutton or statictextthus when you create windowyou create an object that knows how to display itself on the computer screen you must tell it what to display and then tell it to show its contents to the user you should bear the following points in mind during your reading of this they will help you understand what you are required to doyou create window by instantiating frame or dialog object you define what the window displays by creating widget that has an appropriate parent component this adds the widget to containersuch as type of panel or frame you can send messages to the window to change its stateperform an operationand display graphic object the windowor components within the windowcan send messages to other objects in response to user (or programactions everything displayed by window is an instance of class and is potentially subject to all of the above wx app handles the main event loop of the gui application simple example an example of creating very simple window using wxpython is given below the result of running this short program is shown here for both mac and windows pcthis program creates top level window (the wx frameand gives it title it also creates label ( wx statictext objectto be displayed within the frame
19,106
the wxpython gui library to use the wxpython library it is necessary to import the wx module import wx create the application object app wx app(now create frame (representing the windowframe wx frame(parent=nonetitle=simple hello world'and add text label to it text wx statictext(parent=framelabel'hello python'display the window (frameframe show(start the event loop app mainloop(the program also creates new instance of the application object called wx app(every wxpython gui program must have one application object it is the equivalent of the main(function in many non-gui applications as it will run the gui application for you it also provides default facilities for defining startup and shutdown operations and can be subclassed to create custom behaviour the wx statictext class is used to create single (or multipleline label in this case the label shows the string 'hello pythonthe statictext object is constructed with reference to its parent container this is the container within which the text will be displayed in this case the statictext is being displayed directly within the frame and thus the frame object is its containing parent object in contrast the frame which is top level windowdoes not have parent container also notice that the frame must be shown (displayedfor the user to see it this is because there might be multiple different windows that need to be shown (or hiddenin different situations for an application finally the program starts the applicationsmain event loopwithin this loop the program listens for any user input (such as requesting that the window is closed the wx app class the wx app class represents the application and is used tostart up the wxpython system and initialise the underlying gui toolkitset and get application-wide propertiesimplement the native windowing system main message or event loopand to dispatch events to window instances
19,107
every wxpython application must have single wx app instance the creation of all of the ui objects should be delayed until after the wx app object has been created in order to ensure that the gui platform and wxwidgets have been fully initialised it is common to subclass the wx app class and override methods such as onpreinit and onexit to provide custom behaviour this ensures that the required behaviour is run at appropriate times the methods that can be overridden for this purpose areonpreinitthis method can be overridden to define behaviour that should be run once the application object is createdbut before the oninit method has been called oninit this is expected to create the applications main windowdisplay that window etc onrunthis is the method used to start the execution of the main program onexitthis can be overridden to provide any behaviour that should be called just before the application exits as an exampleif we wish to set up gui application such that the main frame is initialised and shown after the wx app has been instantiated then the safest way is to override the oninit(method of the wx app class in suitable subclass the method should return true of falsewhere true is used to indicate that processing of the application should continue and false indicates that the application should terminate immediately (usually as the result of some unexpected issuean example wx app subclass is shown belowclass mainapp(wx app)def oninit(self)""initialise the main gui application""frame welcomeframe(frame show(indicate whether processing should continue or not return true this class can now be instantiated and the mainloop startedfor examplerun the gui application app mainapp(app mainloop(it is also possible to override the onexit(to clean up anything initialised in the oninit(method
19,108
the wxpython gui library window classes the window or widget container classes that are commonly used within wxpython application arewx dialog dialog is top level window used for popups where the user has limited ability to interact with the window in many cases the user can only input some data and/or accept or decline an option wx frame frame is top level window whose size and position can be set and can (usuallybe controlled by the user wx panel is container (non top level windowon which controls/widgets can be placed this is often used in conjunction with dialog or frame to manage the positioning of widgets within the gui the inheritance hierarchy for these classes is given below for referenceas an example of using frame and panelthe following application creates two panels and displays them within top level frame the background colour of the frame is the default greywhile the background colour for the first panel is blue and for the second panel it is red the resulting display is shown below
19,109
the program that generated this gui is given belowimport wx class sampleframe(wx frame)def __init__(self)super(__init__(parent=nonetitle='sample app'size=( )set up the first panel to be at position (the defaultand of size by with blue background self panel wx panel(selfself panel setsize( self panel setbackgroundcolour(wx colour( )set up the second panel to be at position and of size by with red background self panel wx panel(selfself panel setsize( self panel setbackgroundcolour(wx colour( )class mainapp(wx app)def oninit(self)""initialise the main gui application""frame sampleframe(frame show(return true run the gui application app mainapp(app mainloop(
19,110
the wxpython gui library the sampleframe is subclass of the wx frame classit thus inherits all of the functionality of top level frame (windowwithin the __init__(method of the sampleframe the super classes __init__(method is called this is used to set the size of the frame and to give the frame title note that the frame also indicates that it does not have parent window when the panel is created it is necessary to specify the window (or in this case framewithin which it will be displayed this is common pattern within wxpython also note that the setsize method of the panel class also allows the position to be specified and that the colour class is the wxpython colour class widget/control classes although there are very many widgets/controls available to the developerthe most commonly used includewx button/wx togglebutton/wx radiobutton these are widgets that provide button like behaviour within gui wx textctrl this widget allows text to be displayed and edited can be single line or multiple line widget depending upon configuration wx statictext used to display one or more lines of read-only text in many libraries this widgets is known as label wx staticline line used in dialogs to separate groups of widgets the line may be vertical or horizontal wx listbox this widget is used to allow user to select one option from list of options wx menubar/wx menu/wx menuitem the components that can be used to construct set of menus for user interface wx toolbar this widget is used to display bar of buttons and/or other widgets usually placed below the menubar in wx frame the inheritance hierarchy of these widgets is given below note that they all inherit from the class control (hence why they are often referred to as controls as well as widgets or gui components
19,111
whenever widget is created it is necessary to provide the container window class that will hold itsuch as frame or panelfor exampleenter_button wx button(panellabel='enter'in this code snippet wx button is being created that will have label 'enterand will be displayed within the given panel dialogs the generic wx dialog class can be used to build any custom dialog you require it can be used to create modal and modeless dialogsa modal dialog blocks program flow and user input on other windows until it is dismissed modeless dialog behaves more like frame in that program flow continuesand input in other windows is still possible the wx dialog class provides two versions of the show method to support modal and modeless dialogs the showmodal(method is used to display modal dialogwhile the show(is used to show modeless dialog as well as the generic wx dialog classthe wxpython library provides numerous prebuilt dialogs for common situations these pre built dialogs includewx colourdialog this class is used to generate colour chooser dialog wx dirdialog this class provides directory chooser dialog wx filedialog this class provides file chooser dialog wx fontdialog this class provides font chooser dialog wx messagedialog this class can be used to generate single or multi-line message or information dialog it can support yesno and cancel options it can be used for generic messages or for error messages wx multichoicedialog this dialog can be used to display lit of strings and allows the user to select one or more values for the list wx passwordentrydialog this class represents dialog that allows user to enter one-line password string from the user wx progressdialog if supported by the gui platformthen this class will provide the platforms native progress dialogotherwise it will use the pure python wx genericprogressdialog the wx genericprogressdialog shows short message and progress bar wx textentrydialog this class provides dialog that requests one-line text string from the user
19,112
the wxpython gui library most of the dialogs that return value follow the same pattern this pattern returns value from the showmodel(method that indicates if the user selected ok or cancel (using the return value wx id_ok or wx id_cancelthe selected/entered value can then be obtained from suitable get method such as getcolourdata(for the colourdialog or getpath(for the dirdialog arranging widgets within container widgets can be located within window using specific coordinates (such as pixels down and pixels acrosshoweverthis can be problem if you are considering cross platform applicationsthis is because how button is rendered (drawnon mac is different to windows and different again from the windowing systems on linux/unix etc this means that different amount of spacing must be given on different platforms in addition the fonts used with text boxes and labels differ between different platforms also requiring differences in the layout of widgets to overcome this wxpython provides sizers sizers work with container such as frame or panel to determine how the contained widgets should be laid out widgets are added to sizer which is then set onto container such as panel sizer is thus an object which works with container and the host windowing platform to determine the best way to display the objects in the window the developer does not need to worry about what happens if user resizes window or if the program is executed on different windowing platform sizers therefore help to produce portablepresentable user interfaces in fact one sizer can be placed within another sizer to create complex component layouts there are several sizers available includingwx boxsizer this sizer can be used to place several widgets into row or column organisation depending upon the orientation when the boxsizer is created the orientation can be specified using wx vertical or wxhorizontal wx gridsizer this sizer lays widgets out in two dimensional grid each cell within the grid has the same size when the gridsizer object is created it is possible to specify the number of rows and columns the grid has it is also possible to specify the spacing between the cells both horizontally and vertically wx flexgridsizer this sizer is slightly more flexible version of the gridsizer in this version not all columns and rows need to be the same size (although all cells in the same column are the same width and all cells in the same row are the same height
19,113
wx gridbagsizer is the most flexible sizer it allows widgets to be positioned relative to the grid and also allows widgets to span multiple rows and/or columns to use sizer it must first be instantiated when widgets are created they should be added to the sizer and then the sizer should be set on the container for examplethe following code uses gridsizer used with panel to layout out four widgets comprised of two buttonsa statictext label and textctrl input fieldcreate the panel panel wx panel(selfcreate the sizer to use with rows and column and spacing around each cell grid wx gridsizer( create the widgets text wx textctrl(panelsize=( - )enter_button wx button(panellabel='enter'label wx statictext(panel,label='welcome'message_button wx button(panellabel='show message'add the widgets to the grid sizer grid addmany([textenter_buttonlabelmessage_button]set the sizer on the panel panel setsizer(gridthe resulting display is shown below
19,114
the wxpython gui library drawing graphics in earlier we looked at the turtle graphics api for generating vector and raster graphics in python the wxpython library provides its own facilities for generating cross platform graphic displays using linessquarescirclestext etc this is provided via the device context device context (often shortened to just dcis an object on which graphics and text can be drawn it is intended to allow different output devices to all have common graphics api (also known as the gdi or graphics device interfacespecific device contexts can be instantiate depending on whether the program is to use window on computer screen or some other output medium (such as printerthere are several device context types available such as wx windowdcwx paintdc and wx clientdcthe wx windowdc is used if we want to paint on the whole window (windows onlythis includes window decorations the wx clientdc is used to draw on the client area of window the client area is the area of window without its decorations (title and borderthe wx paintdc is used to draw on the client area as well but is intended to support the window refresh paint event handling mechanism note that the wx paintdc should be used only from wx paintevent handler while the wx clientdc should never be used from wx paintevent handler whichever device context is usedthey all support similar set of methods that are used to generate graphicssuch asdrawcircle (xyradiusdraws circle with the given centre and radius drawellipse (xywidthheightdraws an ellipse contained in the rectangle specified either with the given top left corner and the given size or directly drawpoint (xydraws point using the color of the current pen drawrectangle (xywidthheightdraws rectangle with the given corner coordinate and size drawtext (textxydraws text string at the specified pointusing the current text fontand the current text foreground and background colours drawline (pt pt )/drawline ( this method draws line from the first point to the second it is also important to understand when the device context is refreshed/redrawn for exampleif you resize windowmaximise itminimise itmove itor modify its contents the window is redrawn this generates an eventa paintevent you can bind method to the paintevent (using wx evt_paintthat can be called each time the window is refreshed
19,115
this method can be used to draw whatever the contents of the window should be if you do not redraw the contents of the device context in such method than whatever you previously drew will display when the window is refreshed the following simple program illustrates the use of some of the draw methods listed above and how method can be bound to the paint event so that the display is refreshed appropriately when using device contextimport wx class drawingframe(wx frame)def __init__(selftitle)super(__init__(nonetitle=titlesize=( )self bind(wx evt_paintself on_paintdef on_paint(selfevent)"""set up the device context (dcfor painting""dc wx paintdc(selfdc drawline( dc drawrectangle( dc drawtext("hello world" dc drawcircle( radius= class graphicapp(wx app)def oninit(self)""initialise the gui display""frame drawingframe(title='pydraw'frame show(return true run the gui application app graphicapp(app mainloop(when this program is run the following display is generated
19,116
the wxpython gui library online resources there are numerous online references that support the development of guis and of python guis in particularincludingcross platform gui library exercises simple gui application in this exercise you will implement your own simple gui application the application should generate the display for simple ui an example of the user interface is given belownotice that we have added label to the input fields for name and ageyou can manage their display using nested panel in the next we will add event handling to this application so that the application can respond to button clicks etc
19,117
events in wxpython user interfaces event handling events are an integral part of any guithey represent user interactions with the interface such as clicking on buttonentering text into fieldselecting menu option etc the main event loop listens for an eventwhen one occurs it processes that event (which usually results in function or method being calledand then waits for the next event to happen this loop is initiated in wxpython via the call to the mainloop(method on the wx app object this raises the question 'what is an event?an event object is piece of information representing some interaction that occurred typically with the gui (although an event can be generated by anythingan event is processed by an event handler this is method or function that is called when the event occurs the event is passed to the handler as parameter an event binder is used to bind an event to an event handler event definitions it is useful to summarise the definitions around events as the terminology used can be confusing and is very similarevent represents information from the underlying gui framework that describes something that has happened and any associated data the specific data available will differ depending on what has occurred for exampleif window has been moved then the associated data will relate to the window' new location where as commandevent generated by selection action from listbox provides the item index for the selection (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,118
events in wxpython user interfaces event loop the main processing loop of the gui that waits for an event to occur when an event occurs the associated event handler is called event handlers these are methods (or functionsthat are called when an event occurs event binders associate type of event with an event handler there are different event binders for different types of event for examplethe event binder associated with the wx moveevent is named wx evt_move the relationship between the eventthe event handler via the event binder is illustrated belowthe top three boxes illustrate the concepts while the lower boxes provide concrete example of binding move_event to an on_move(method via the evt_move binder types of events there are numerous different types of event includingwx closeevent used to indicate that frame or dialog has been closed the event binder for this event is named wx evt_close wx commandevent used with widgets such as buttonslist boxesmenu itemsradio buttonsscrollbarssliders etc depending upon the type of widget that generated the event different information may be provided for examplefor button commandevent indicates that button has been clicked where as for listbox it indicates that an option has been selectedetc different event binders are used for different event situations for exampleto bind command event to event handler for button then the wx evt_button binder is usedwhile for listbox wx evt_listbox binder can be used wx focusevent this event is sent when window' focus changes (loses or gains focusyou can pick up window gaining focus using the wx evt_set_focus event binder the wx evt_kill_focus is used to bind an event handler that will be called when window loses focus
19,119
wx keyevent this event contains information relating to key press or release wx maximizeevent this event is generated when top level window is maximised wx menuevent this event is used for menu oriented actions such as the menu being opened or closedhowever it should be noted that this event is not used when menu item is selected (menuitems generate commandeventswx mouseevent this event class contains information about the events generated by the mousethis includes information on which mouse button was pressed (and releasedand whether the mouse was double clicked etc wx windowcreateevent this event is sent just after the actual window is created wx windowdestoryedevent this event is sent as early as possible during the window destruction process binding an event to an event handler an event is bound to an event handler using the bind(method of an event generating object (such as buttonfieldmenu item etc via named event binder for examplebutton bind(wx evt_buttonself event_handler_method implementing event handling there are four steps involved in implementing event handling for widget or windowthese are identify the event of interest many widgets will generate different events in different situationsit may therefore be necessary to determine which event you are interested in find the correct event binder namee wx evt_closewx evt_move or wx evt_button etc again you may find that the widget you are interested in supports numerous different event binders which may be used in different situations (even for the same event implement an event handler ( suitable method or functionthat will be called when the event occurs the event handler will be supplied with the event object bind the event to the event handler via the binder name using the bind(method of the widget or window
19,120
events in wxpython user interfaces to illustrate this we will use simple example we will write very simple event handling application this application will have frame containing panel the panel will contain label using the wx statictext class we will define an event handler called on_mouse_click(that will move the statictext label to the current mouse location when the left mouse button is pressed this means that we can move the label around the screen to do this we first need to determine the widget that will be used to generate the event in this case it is the panel that contains the text label having done this we can look at the panel class to see what events and event bindings it supports it turns out that the panel class only directly defines support for navigationkeyevents this is not actually what we wanthowever the panel class extends the window class the window class supports numerous event bindingsfrom those associated with setting the focus (wx evt_set_focus and wx evt_kill_focusto key presses (wx evt_key_down and wx evt_key_upas well as mouse events there are however numerous different mouse event bindings these allow leftmiddle and right mouse button clicks to be picked updown clicks to be identifiedsituations such as the mouse entering or leaving the window etc howeverthe binding we are interested in for mouseevent is the wx evt_left_down bindingthis picks up on the moueevent when the left mouse button is pressed (there is also the wx evt_left_up binding which can be used to pick up an event that occurs when the left mouse button is releasedwe now know that we need to bind the on_mouse_click(event handler to the mouseevent via the wx evt_left_down event binderfor exampleself panel bind(wx evt_left_downself on_mouse_clickall event handler methods takes two parametersself and the mouse event thus the signature of the on_mouse_click(method isdef on_mouse_click(selfmouse_event)the mouse event object has numerous methods defined that allow information about the mouse to be obtained such as the number of mouse clicks involved (getclickcount())which button was pressed (getbutton()and the current mouse position within the containing widget or window (getposition ()we can therefore use this last method to obtain the current mouse location and then use the setposition(xymethod on the statictext object to set its position the end result is the program shown below
19,121
import wx class welcomeframe(wx frame)""the main window frame of the application ""def __init__(self)super(__init__(parent=nonetitle='sample app'size=( )set up panel within the frame and text label self panel wx panel(selfself text wx statictext(self panellabel='hello'bind the on_mouse_click method to the mouse event via the left mouse click binder self panel bind(wx evt_left_downself on_mouse_clickdef on_mouse_click(selfmouse_event)""when the left mouse button is clicked this method is called it will obtain the current mouse coordinatesand reposition the text label to this position ""xy mouse_event getposition(print(xyself text setposition(wx point(xy)class mainapp(wx app)def oninit(self)""initialise the main gui application""frame welcomeframe(frame show(indicate that processing should continue return true run the gui application app mainapp(app mainloop(
19,122
events in wxpython user interfaces when this program is runthe window is displayed with the 'hellostatictext label in the top left hand corner of the frame (actually it is added to the panelhowever the panel fills the frame in this exampleif the user then clicks the left mouse button anywhere within the frame then the 'hellolabel jumps to that location this is shown below for the initial setup and then for two locations within the window an interactive wxpython gui an example of slightly larger gui applicationthat brings together many of the ideas presented in this is given below in this application we have text input field ( wx textctrlthat allows user to enter their name when they click on the enter button (wx buttonthe welcome label ( wx statictextis updated with their name the 'show messagebutton is used to display wx messagedialog which will also contain their name the initial display is shown below for both mac and windows pcnote that the default background colour for frame is different on windows pc than on mac and thus although the gui runs on both platformsthe look differs between the two
19,123
the code used to implement this gui application is given belowimport wx class helloframe(wx frame)def __init__(selftitle)super(__init__(nonetitle=titlesize=( )self name 'create the boxsizer to use for the frame vertical_box_sizer wx boxsizer(wx verticalself setsizer(vertical_box_sizercreate the panel to contain the widgets panel wx panel(selfadd the panel to the frames sizer vertical_box_sizer add(panelwx id_anywx expand wx all create the gridsizer to use with the panel grid wx gridsizer( set up the input field self text wx textctrl(panelsize=( - )
19,124
events in wxpython user interfaces now configure the enter button enter_button wx button(panellabel='enter'enter_button bind(wx evt_buttonself set_namenext set up the text label self label wx statictext(panellabel='welcome'style=wx align_leftnow configure the show message button message_button wx button(panellabel='show message'message_button bind(wx evt_buttonself show_messageadd the widgets to the grid sizer to handle layout grid addmany([self textenter_buttonself labelmessage_button]set the sizer on the panel panel setsizer(gridcentre the frame on the computer screen self centre(def show_message(selfevent)""event handler to display the message dialog using the current value of the name attribute ""dialog wx messagedialog(nonemessage='welcome to python self namecaption='hello'style=wx okdialog showmodal(def set_name(selfevent)""event handler for the enter button retrieves the text entered into the input field and sets the self name attribute this is then used to set the text label ""self name self text getlinetext( self label setlabeltext('welcome self name
19,125
class mainapp(wx app)def oninit(self)""initialise the gui display""frame helloframe(title='sample app'frame show(indicate whether processing should continue or not return true def onexit(self)""executes when the gui application shuts down""print('goodbye'need to indicate success or failure return true run the gui application app mainapp(app mainloop(if the user enters their name in the top textctrl fieldfor example 'phoebe'then when they click on the 'enterbutton the welcome label changes to 'welcome phoebe'if they now click on the 'show messagebutton then the wx messagedialog ( specific type of wx dialogwill display welcome message to phoebe
19,126
events in wxpython user interfaces online resources there are numerous online references that support the development of guis and of python guis in particularincludingcross platform gui library exercises simple gui application this exercise builds on the gui you created in the last the application should allow user to enter their name and age you will need to check that the value entered into the age field is numeric value (for example using isnumeric()if the value is not number then an error message dialog should be displayed
19,127
button should be provided labelled 'birthday'when clicked it should increment the age by one and display happy birthday message the age should be updated within the gui an example of the user interface you created in the last is given belowas an examplethe user might enter their name and age as shown belowwhen the user clicks on the 'birthdaybutton then the happy birthday message dialog is displayed
19,128
events in wxpython user interfaces gui interface to tic tac toe game the aim of this exercise is to implement simple tic tac toe game the game should allow two users to play interactive using the same mouse the first user will have play as the 'xplayer and the second user as the ' player when each user selects button you can set the label for the button to their symbol you will need two check after each move to see if someone has won (or if the game is drawyou will still need an internal representation of the grid so that you can determine whoif anyonehas won an example of how the gui for the tictactoe game might look is given belowyou can also add dialogs to obtain the players names and to notify them who won or whether there was draw
19,129
pydraw wxpython example application introduction this builds on the gui library presented in the last two to illustrate how larger application can be built it presents case study of drawing tool akin to tool such as visio etc the pydraw application the pydraw application allows user to draw diagrams using squarescircleslines and text at present there is no selectresizereposition or delete option available (although these could be added if requiredpydraw is implemented using the wxpython set of components as defined in version when user starts the pydraw applicationthey see the interface shown above (for both the microsoft windows and apple mac operating systemsdepending on (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,130
pydraw wxpython example application the operating system it has menu bar across the top (on mac this menu bar is at the top of the mac display) tool bar below the menu bar and scrollable drawing area below that the first button on the tool bar clears the drawing area the second and third buttons are only implemented so that they print out message into the python consolebut are intended to allow user to load and save drawings the tool bar buttons are duplicated on the menus defined for the applicationalong with drawing tool selection menuas shown below the structure of the application the user interface created for the pydraw application is made up of number of elements (see below)the pydrawmenubarthe pydrawtoolbar containing sequence of buttons across the top of the windowthe drawing paneland the window frame (implemented by the pydrawframe classthe following diagram shows the same information as that presented abovebut as containment hierarchythis means that the diagram illustrates how one object is contained within another the lower level objects are contained within the higher level objects
19,131
the structure of the application it is important to visualize this as the majority of wxpython interfaces are built up in this wayusing containers and sizers the inheritance structure between the classes used in the pydraw application is illustrated below this class hierarchy is typical of an application which incorporates user interface features with graphical elements modelview and controller architecture the application adopts the well established model-view-controller (or mvcdesign pattern for separating out the responsibilities between the view element ( the frame or panel)the control element (for handling user inputand the model element (which holds the data to be displayedthis separation of concerns is not new idea and allows the construction of gui applications that mirror the model-view-controller architecture the intention of the mvc architecture is the separation of the user displayfrom the control of user inputfrom the underlying information model as illustrated below
19,132
pydraw wxpython example application there are number of reasons why this separation is usefulreusability of application and/or user interface componentsability to develop the application and user interface separatelyability to inherit from different parts of the class hierarchy ability to define control style classes which provide common features separately from how these features may be displayed this means that different interfaces can be used with the same applicationwithout the application knowing about it it also means that any part of the system can be changed without affecting the operation of the other for examplethe way that the graphical interface (the lookdisplays the information could be changed without modifying the actual application or how input is handled (the feelindeed the application need not know what type of interface is currently connected to it at all pydraw mvc architecture the mvc structure of the pydraw application has top level controller class pydrawcontroller and top level view class the pydrawframe (there is no model as the top level mvc triad does not hold any explicit data itselfthis is shown belowat the next level down there is another mvc structurethis time for the drawing element of the application there is drawingcontrollerwith drawingmodel and drawingpanel (the viewas illustrated below
19,133
the structure of the application the drawingmodeldrawingpanel and drawingcontroller classes exhibit the classic mvc structure the view and the controller classes (drawingpanel and drawingcontrollerknow about each other and the drawing modelwhereas the drawingmodel knows nothing about the view or the controller the view is notified of changes in the drawing through the paint event additional classes there are also four types of drawing object (of figure)circlelinesquare and text figures the only difference between these classes is what is drawn on the graphic device context within the on_paint(method the figure classfrom which they all inheritdefines the common attributes used by all objects within drawing ( point representing an and location and sizethe pydrawframe class also uses pydrawmenubar and pydrawtoolbar class the first of these extends the wx menubar with menu items for use within the pydraw application in turn the pydrawtoolbar extends the wx toolbar and provides icons for use in pydraw
19,134
pydraw wxpython example application the final class is the pydrawapp class that extends the wx app class object relationships howeverthe inheritance hierarchy is only part of the story for any object oriented application the following figure illustrates how the objects relate to one another within the working application the pydrawframe is responsible for setting up the controller and the drawingpanel the pydrawcontroller is responsible for handling menu and tool bar user interactions this separates graphical elements from the behaviour triggered by the user
19,135
the structure of the application the drawingpanel is responsible le for displaying any figures held by the drawingmodel the drawingcontroller manages all user interactions with the drawingpanel including adding figures and clearing all figures from the model the drawingmodel holds list of figures to be displayed the interactions between objects we have now examined the physical structure of the application but not how the objects within that application interact in many situations this can be extracted from the source code of the application (with varying degrees of difficultyhoweverin the case of an application such as pydrawwhich is made up of number of different interacting componentsit is useful to describe the system interactions explicitly the diagrams illustrating the interactions between the objects use the following conventionsa solid arrow indicates message senda square box indicates classa name in brackets indicates the type of instancenumbers indicate the sequence of message sends these diagrams are based on the collaboration diagrams found in the uml (unified modelling languagenotation the pydrawapp when the pydrawapp is instantiated the pydrawframe in created and displayed using the oninit(method the mainloop(method is then invoked this is shown belowclass pydrawapp(wx app)def oninit(self)""initialise the gui display""frame pydrawframe(title='pydraw'frame show(return true run the gui application app pydrawapp(app mainloop(
19,136
pydraw wxpython example application the pydrawframe constructor the pydrawframe constructor method sets up the main display of the ui application and also initialises the controllers and drawing elements this is shown below using collaboration diagramthe pydrawframe constructor sets up the environment for the application it creates the top level pydrawcontroller it creates the drawingpanel and initialises the display layout it initialises the menu bar and tool bar it binds the controllers menu handler to the menus and centers itself changing the application mode one interesting thing to note is what happens when the user selects an option from the drawing menu this allows the mode to be changed to squarecircleline or text the interactions involved are shown below for the situation where user selects the 'circlemenu item on the drawing menu (using collaboration diagram)
19,137
the interactions between objects when the user selects one of the menu items the command_menu_handler (method of the pydrawcontroller is invoked this method determines which menu item has been selectedit then calls an appropriate setter method (such as set_circle_mode(or set_line_mode(etc these methods set the mode attribute of the controller to an appropriate value adding graphic object user adds graphic object to the drawing displayed by the drawingpanel by pressing the mouse button when the user clicks on the drawing panelthe drawingcontroller responds as shown below
19,138
pydraw wxpython example application the above illustrates what happens when the user presses and releases mouse button over the drawing panelto create new figure when the user presses the mouse buttona mouse clicked message is sent to the drawingcontrollerwhich decides what action to perform in response (see abovein pydrawit obtains the cursor point at which the event was generated by calling the getposition(method on the mouse_event the controller then calls its own add(method passing in the current mode and the current mouse location the controller obtains the current mode (from the pydrawcontroller using the method callback provided when the drawingcontroller is instantiatedand adds the appropriate type of figure to the drawingmodel the add(method then adds new figure to the drawing model based on the specified mode the classes this section presents the classes in the pydraw application as these classes build on concepts already presented in the last few they shall be presented in their entirety with comments highlighting specific points of their implementations note that the code imports the wx module from the wxpython librarye import wx the pydrawconstants class the purpose of this class is to provide set of constants that can be referenced in the remainder of the application it is used to provide constants for the ids used with menu items and toolbar tools it also provides constants used to represent the current mode (to indicate whether linesquarecircle or test should be added to the displayclass pydrawconstantsline_id square_id circle_id text_id square_mode 'squareline_mode 'linecircle_mode 'circletext_mode 'text
19,139
the classes the pydrawframe class the pydrawframe class provides the main window for the application note that due to the separation of concerns introduced via the mvc architecturethe view class is only concerned with the layout of the componentsclass pydrawframe(wx frame)""main frame responsible for the layout of the ui ""def __init__(selftitle)super(__init__(nonetitle=titlesize=( )set up the controller self controller pydrawcontroller(selfset up the layout fo the ui self vertical_box_sizer wx boxsizer(wx verticalself setsizer(self vertical_box_sizerset up the menu bar self setmenubar(pydrawmenubar()set up the toolbar self vertical_box_sizer add(pydrawtoolbar(self)wx id_anywx expand wx allsetup drawing panel self drawing_panel drawingpanel(selfself controller get_modeself drawing_controller self drawing_panel controller add the panel to the frames sizer self vertical_box_sizer add(self drawing_panelwx id_anywx expand wx allset up the command event handling for the menu bar and tool bar self bind(wx evt_menuself controller command_menu_handlerself centre(
19,140
pydraw wxpython example application the pydrawmenubar class the pydrawmenubar class is subclass of the wx menubar class which defines the contents of the menu bar for the pydraw application it does this by creating two wx menu objects and adding them to the menu bar each wx menu implements drop down menu from the menu bar to add individual menu items the wx menuitem class is used these menu items are appended to the menu the menus are themselves appended to the menu bar note that each menu item has an id that can be used to identify the source of command event in an event handler this allows single event handler to deal with events generated by multiple menu items class pydrawmenubar(wx menubar)def __init__(self)super(__init__(filemenu wx menu(newmenuitem wx menuitem(filemenuwx id_newtext="new"kind=wx item_normalnewmenuitem setbitmap(wx bitmap("new gif")filemenu append(newmenuitemloadmenuitem wx menuitem(filemenuwx id_opentext="open"kind=wx item_normalloadmenuitem setbitmap(wx bitmap("load gif")filemenu append(loadmenuitemfilemenu appendseparator(savemenuitem wx menuitem(filemenuwx id_savetext="save"kind=wx item_normalsavemenuitem setbitmap(wx bitmap("save gif")filemenu append(savemenuitemfilemenu appendseparator(quit wx menuitem(filemenuwx id_exit'&quit\tctrl+ 'filemenu append(quitself append(filemenu'&file'drawingmenu wx menu(linemenuitem wx menuitem(drawingmenupydraw_constants line_idtext="line"kind=wx item_normaldrawingmenu append(linemenuitemsquaremenuitem wx menuitem(drawingmenupydraw_constants square_idtext="square"kind=wx item_normaldrawingmenu append(squaremenuitemcirclemenuitem wx menuitem(drawingmenu
19,141
the classes pydraw_constants circle_idtext="circle"kind=wx item_normaldrawingmenu append(circlemenuitemtextmenuitem wx menuitem(drawingmenupydraw_constants text_idtext="text"kind=wx item_normaldrawingmenu append(textmenuitemself append(drawingmenu'&drawing'the pydrawtoolbar class the drawtoolbar class is subclass of wx toolbar the classes constructor initialises three tools that are displayed within the toolbar the realize(method is used to ensure that the tools are rendered appropriately note that appropriate ids have been used to allow an event handler to identify which tools generated particular command event by reusing the same ids for related menu items and command toolsa single handler can be used to manage events from both types of sources class pydrawtoolbar(wx toolbar)def __init__(selfparent)super(__init__(parentself addtool(toolid=wx id_newlabel="new"bitmap=wx bitmap("new gif")shorthelp='open drawing'kind=wx item_normalself addtool(toolid=wx id_openlabel="open"bitmap=wx bitmap("load gif")shorthelp='open drawing'kind=wx item_normalself addtool(toolid=wx id_savelabel="save"bitmap=wx bitmap("save gif")shorthelp='save drawing'kind=wx item_normalself realize(the pydrawcontroller class this class provides the control element of the top level view it maintains the current mode and implements handler that can handle events from menu items and from the tool bar tools an id is used to identify each individual menu or tool which allows single handler to be registered with the frame
19,142
pydraw wxpython example application class pydrawcontrollerdef __init__(selfview)self view view set the initial mode self mode pydrawconstants square_mode def set_circle_mode(self)self mode pydrawconstants circle_mode def set_line_mode(self)self mode pydrawconstants line_mode def set_square_mode(self)self mode pydrawconstants square_mode def set_text_mode(self)self mode pydrawconstants text_mode def clear_drawing(self)self view drawing_controller clear(def get_mode(self)return self mode def command_menu_handler(selfcommand_event)id command_event getid(if id =wx id_newprint('clear the drawing area'self clear_drawing(elif id =wx id_openprint('open drawing file'elif id =wx id_saveprint('save drawing file'elif id =wx id_exitprint('quite the application'self view close(elif id =pydrawconstants line_idprint('set drawing mode to line'self set_line_mode(elif id =pydrawconstants square_idprint('set drawing mode to square'self set_square_mode(elif id =pydrawconstants circle_idprint('set drawing mode to circle'self set_circle_mode(elif id =pydrawconstants text_idprint('set drawing mode to text'self set_text_mode(elseprint('unknown option'id
19,143
the classes the drawingmodel class the drawingmodel class has contents attribute that is used to hold all the figures in the drawing it also provides some convenience methods to reset the contents and to add figure to the contents class drawingmodeldef __init__(self)self contents [def clear_figures(self)self contents [def add_figure(selffigure)self contents append(figurethe drawingmodel is relatively simple model which merely records set of graphical figures in list these can be any type of object and can be displayed in any way as long as they implement the on_paint(method it is the objects themselves which determine what they look like when drawn the drawingpanel class the drawingpanel class is subclass of the wx panel class it provides the view for the drawing data model this uses the classical mvc architecture and has model (drawingmodel) view (the drawingpaneland controller (the drawingcontrollerthe drawingpanel instantiates its own drawingcontroller to handle mouse events it also registers for paint events so that it knows when to refresh the display class drawingpanel(wx panel)def __init__(selfparentget_mode)super(__init__(parent- self setbackgroundcolour(wx colour( )self model drawingmodel(self controller drawingcontroller(selfself modelget_modeself bind(wx evt_paintself on_paintself bind(wx evt_left_downself controller on_mouse_click
19,144
pydraw wxpython example application def on_paint(selfevent)"""set up the device context (dcfor painting""dc wx paintdc(selffor figure in self model contentsfigure on_paint(dcthe drawingcontroller class the drawingcontroller class provides the control class for the top level mvc architecture used with the drawingmodel (modeland drawingpanel (viewclasses in particular it handles the mouse events in the drawingpanel via the on_mouse_click(method it also defines an add method that is used to add figure to the drawingmodel (the actual figure depends on the current mode of the pydrawcontrollera final methodthe clear(methodremoves all figures from the drawing model and refreshes the display class drawingcontrollerdef __init__(selfviewmodelget_mode)self view view self model model self get_mode get_mode def on_mouse_click(selfmouse_event)point mouse_event getposition(self add(self get_mode()pointdef add(selfmodepointsize= )if mode =pydrawconstants square_modefig square(self viewpointwx size(sizesize)elif mode =pydrawconstants circle_modefig circle(self viewpointsizeelif mode =pydrawconstants text_modefig text(self viewpointsizeelif mode =pydrawconstants line_modefig line(self viewpointsizeself model add_figure(figdef clear(self)self model clear_figures(self view refresh(
19,145
the classes the figure class the figure class (an abstract superclass of the figure class hierarchycaptures the elements which are common to graphic objects displayed within drawing the point defines the position of the figurewhile the size attribute defines the size of the figure note that the figure is subclass of wx panel and thus the display is constructed from inner panels onto which the various figure shapes are drawn the figure class defines single abstract method on_paint(dcthat must be implemented by all concrete subclasses this method should define how the shape is drawn on the drawing panel class figure(wx panel)def __init__(selfparentid=wx id_anypos=nonesize=nonestyle=wx tab_traversal)wx panel __init__(selfparentid=idpos=possize=sizestyle=styleself point pos self size size @abstractmethod def on_paint(selfdc)pass the square class this is subclass of figure that specifies how to draw square shape in drawing it implements the on_paint(method inherited from figure class square(figure)def __init__(selfparentpossize)super(__init__(parent=parentpos=possize=sizedef on_paint(selfdc)dc drawrectangle(self pointself size
19,146
pydraw wxpython example application the circle class this is another subclass of figure it implements the on_paint(method by drawing circle note that the shape will be drawn within the panel size defined via the figure class (using the call to superit is therefore necessary to see the circle to fit within these bounds this means that the size attribute must be used to generate an appropriate radius also note that the drawcircle(method of the device context takes point that is the centre of the circle so this must also be calculated class circle(figure)def __init__(selfparentpossize)super(__init__(parent=parentpos=possize=wx size(sizesize)self radius (size self circle_center wx point(self point self radiusself point self radiusdef on_paint(selfdc)dc drawcircle(pt=self circle_centerradius=self radiusthe line class this is another subclass of figure in this very simple examplea default end point for the line is generated alternatively the program could look for mouse released event and pick up the mouse at this location and use this as the end point of the line class line(figure)def __init__(selfparentpossize)super(__init__(parent=parentpos=possize=wx size(sizesize)self end_point wx point(self point sizeself point sizedef on_paint(selfdc)dc drawline(pt =self pointpt =self end_point
19,147
the classes the text class this is also subclass of figure default value is used for the text to displayhowever dialog could be presented to the user allowing them to input the text they wish to displayclass text(figure)def __init__(selfparentpossize)super(__init__(parent=parentpos=possize=wx size(sizesize)def on_paint(selfdc)dc drawtext(text='text'pt=self point references the following provides some background on the model-view-controller architecture in user interfaces krasners popea cookbook for using the model-view controller user interface paradigm in smalltalk- joop ( ) - ( exercises you could develop the pydraw application further by adding the following featuresa delete option you can add button labelled delete to the window it should set the mode to "deletethe drawingpanel must be altered so that the mousereleased method sends delete message to the drawing the drawing must find and remove the appropriate graphic object and send the changed message to itself resize option this involves identifying which of the shapes has been selected and then either using dialog to enter the new size or providing some option that allows the size fo the shape to be indicated using the mouse
19,148
computer games
19,149
introduction to games programming introduction games programming is performed by developers/coders who implement the logic that drives game historically games developers did everythingthey wrote the codedesigned the sprites and iconshandled the game playdealt with sounds and musicgenerated any animations required etc howeveras the game industry has matured games companies have developed specific roles including computer graphics (cganimatorsartistsgames developers and games engine and physics engine developers etc those involved with code development may develop physics enginea games enginethe games themselvesetc such developers focus on different aspects of game for examples game engine developer focusses on creating the framework within which the game will run in turn physics engine developer will focus on implementing the mathematics behind the physics of the simulated games world (such as the effect of gravity on characters and components within that worldin many cases there will also be developers working on the ai engine for game these developers will focus on providing facilities that allow the game or characters in the game to operate intelligently those developing the actual game play will use these engines and frameworks to create the overall end result it is they who give life to the game and make it an enjoyable (and playableexperience games frameworks and libraries there are many frameworks and libraries available that allow you to create anything from simple games to large complex role playing games with infinite worlds (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,150
introduction to games programming one example is the unity framework that can be used with the cprogramming language another such framework is the unreal engine used with the +programming language python has also been used for games development with several well known games titles depending on it in one way or another for examplebattlefield by digital illusions ce is military simulator first-person shooter game battlefield heroes handles portions of the game logic involving game modes and scoring using python other games that use python include civilisation iv (for many of the tasks)pirates of the caribbean online and overwatch (which makes its choices with pythonpython is also embedded as scripting engine within tools such as autodesk' maya which is computer animation toolkit that is often used with games python games development for those wanting to learn more about game developmentpython has much to offer there are many examples available online as well as several game oriented frameworks the frameworks/libraries available for games development in python includingarcade this is python library for creating style video games pyglet is windowing and multimedia library for python that can also be used for games development cocos is framework for building games that is built on top of pyglet pygame is probably the most widely used library for creating games within the python world there are also many extensions available for pygame that help to create wide range of different types of games we will focus on pygame in the next two in this book other libraries of interest to python games developers includepyode this is an open-source python binding for the open dynamics engine which is an open-source physics engine pymunk pymunk is easy-to-use physics library that can be used whenever you need rigid body physics with python it is very good when you need physics in your gamedemo or other application it is built on top of the physics library chipmunk pybox pybox is physics library for your games and simple simulations it' based on the box library written in +it supports several shape
19,151
python games development types (circlepolygonthin line segmentsas well as number of joint types (revoluteprismaticwheeletc blender this is open-source computer graphics software toolset used for creating animated filmsvisual effectsart printed modelsinteractive applications and video games blender' features include modelingtexturingraster graphics editingrigging and skinningetc python can be used as scripting tool for creationprototypinggame logic and more quake army knife which is an environment for developing maps for games based on the quake engine it is written in delphi and python using pygame in the next two we will explore the core pygame library and how it can be used to develop interactive computer games the next explores pygame itself and the facilities it provides the following developers simple interactive game in which the user moves starship around avoiding meteors which scroll vertically down the screen online resources for further information games programming and the libraries mentioned in this seedynamics engine pybox blender knife autodesks maya computer animation software
19,152
building games with pygame introduction pygame is cross-platformfree and open source python library designed to make building multimedia applications such as games easy development of pygame started back in october with pygame version being released six months later the version of pygame discussed in this is version if you have later version check to see what changes have been made to see if they have any impact on the examples presented here pygame is built on top of the sdl library sdl (or simple directmedia layeris cross platform development library designed to provide access to audiokeyboardsmousejoystick and graphics hardware via opengl and direct to promote portabilitypygame also supports variety of additional backends including windibx linux frame buffer etc sdl officially supports windowsmac os xlinuxios and android (although other platforms are unofficially supportedsdl itself is written in and pygame provides wrapper around sdl howeverpygame adds functionality not found in sdl to make the creation of graphical or video games easier these functions include vector mathscollision detection sprite scene graph managementmidi supportcamerapixel array manipulationtransformationsfilteringadvanced freetype font support and drawing the remainder of this introduces pygamethe key conceptsthe key modulesclasses and functions and very simple first pygame application the next steps through the development of simple arcade style video game which illustrates how game can be created using pygame (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,153
building games with pygame the display surface the display surface (aka the displayis the most important part of pygame game it is the main window display of your game and can be of any sizehowever you can only have one display surface in many ways the display surface is like blank piece of paper on which you can draw the surface itself is made up of pixels which are numbered from , in the top left hand corner with the pixel locations being indexed in the axis and the axis this is shown belowthe above diagram illustrates how pixels within surface are indexed indeed surface can be used to draw linesshapes (such as rectanglessquarescircles and elipses)display imagesmanipulate individual pixels etc lines are drawn from one pixel location to another (for example from location , to location , which would draw line across the top of the above display surfaceimages can be displayed within the display surface given starting point such as the display surface is created by the pygame display set_mode(function this function takes tuple that can be used to specify the size of the display surface to be returned for exampledisplay_surface pygame display set_mode(( )this will create display surface (windowof by pixels once you have the display surface you can fill it with an appropriate background colour (the default is blackhowever if you want different background colour or want to clear everything that has previously been drawn on the surfacethen you can use the surface' fill(methodwhite ( display_surface fill(whitethe fill method takes tuple that is used to define colour in terms of redgreen and blue (or rgbcolours although the above examples uses meaningful name for the tuple representing the rgb values used for whitethere is of course no requirement to do this (although it is considered good practice
19,154
the display surface to aid in performance any changes you make to the display surface actually happen in the background and will not be rendered onto the actual display that the user sees until you call the update(or flip(methods on the surface for examplepygame display update(pygame display flip(the update(method will redraw the display with all changes made to the display in the background it has an optional parameter that allows you to specify just region of the display to update (this is defined using rect which represents rectangular area on the screenthe flip(method always refreshes the whole of the display (and as such does exactly the same as the update(method with no parametersanother methodwhich is not specifically display surface methodbut which is often used when the display surface is createdprovides caption or title for the top level window this is the pygame display set_caption(function for examplepygame display set_caption('hello world'this will give the top level window the caption (or title'hello world events just as the graphical user interface systems described in earlier have an event loop that allows the programmer to work out what the user is doing (in those cases this is typically selecting menu itemclicking button or entering data etc )pygame has an event loop that allows the game to work out what the player is doing for examplethe user may press the left or right arrow key this is represented by an event event types each event that occurs has associated information such as the type of that event for examplepressing key will result in keydown type of eventwhile releasing key will result in keyup event type selecting the window close button will generate quit event type etc using the mouse can generate mousemotion events as well as mousebuttondown and mousebuttonup event types
19,155
building games with pygame using joystick can generate several different types of event including joyaxismotionjoyballmotionjoybuttondown and joybu ttonup these event types tell you what occurred to generate the event this means that you can choose which types of events you want to deal with and ignore other events event information each type of event object provides information associated with that event for example key oriented event object will provide the actual key pressed while mouse oriented event object will provide information on the position of the mousewhich button was pressed etc if you try an access an attribute on an event that does not support that attributethen an error will be generated the following lists some of the attributes available for different event typeskeydown and keyupthe event has key attribute and mod attribute (indicating if any other modifying keys such as shift are also being pressedmousebuttonup and mousebuttondown has an attribute pos that holds tuple indicating the mouse location in terms of and coordinates on the underlying surface it also has button attribute indicating which mouse was pressed mousemotion has posrel and buttons attributes the pos is tuple indicating the and location of mouse cursor the real attribute indicates the amount of mouse movement and buttons indicates the state of the mouse buttons as an example if we want to check for keyboard event type and then check that the key pressed was the space barthen we can writeif event type =pygame keydowncheck to see which key is pressed if event key =pygame k_spaceprint('space'this indicates that if it is key pressed event and that the actual key was the space barthen print the string 'spacethere are many keyboard constants that are used to represent the keys on the keyboard and pygame k_space constant used above is just one of them all the keyboard constants are prefixed with 'k_followed by the key or the name of the keyfor example
19,156
events k_tabk_spacek_plusk_ k_ k_atk_ak_bk_zk_deltek_downk_leftk_rightk_left etc further keyboard constants are provided for modifier states that can be combined with the above such as kmod_shiftkmod_capskmod_ctrl and kmod_alt the event queue events are supplied to pygame application via the event queue the event queue is used to collect together events as they happen for examplelet us assume that user clicks on the mouse twice and key twice before program has chance to process themthen there will be four events in the event queue as shown belowthe application can then obtain an iterable from the event queue and process through the events in turn while the program is processing these events further events may occur and will be added to the event queue when the program has finished processing the initial collection of events it can obtain the next set of events to process one significant advantage of this approach is that no events are ever lostthat is if the user clicks the mouse twice while the program is processing previous set of eventsthey will be recorded and added to the event queue another advantage is that the events will be presented to the program in the order that they occurred the pygame event get(function will read all the events currently on the event queue (removing them from the event queuethe method returns an eventlist which is an iterable list of the events read each event can then be processed in turn for examplefor event in pygame event get()if event type =pygame quitprint('received quit event:'elif event type =pygame mousebuttondownprint('received mouse event'elif event type =pygame keydownprint('received keydown event'
19,157
building games with pygame in the above code snippet an eventlist is obtained from the event queue containing the current set of events the for loop then processes each event in turn checking the type and printing an appropriate message you can use this approach to trigger appropriate behaviour such as moving an image around the screen or calculating the players score etc howeverbe aware that if this behaviour takes too long it can make the game difficult to play (although the examples in this and the next are simple enough that this is not problem first pygame application we are now at the point where we can put together what we have looked at so far and create simple pygame application it is common to create hello world style program when using new programming language or using new application framework etc the intention is that the core elements of the language or framework are explored in order to generate the most basic form of an application using the language or framework we will therefore implement the most basic application possible using pygame the application we will create will display pygame windowwith 'hello worldtitle we will then be able to quit the game although technically speaking this isn' gameit does possess the basic architecture of pygame application the simple helloworld game will initialise pygame and the graphical display it will then have main game playing loop that will continue until the user selects to quit the application it will then shut down pygame the display created by the program is shown below for both mac and windows operating systemsto quit the program click on the exit button for the windowing system you are using
19,158
first pygame application the simple helloworld game is given belowimport pygame def main()print('starting game'print('initialising pygame'pygame init(required by every pygame application print('initialising helloworldgame'pygame display set_mode(( )pygame display set_caption('hello world'print('update display'pygame display update(print('starting main game playing loop'running true while runningfor event in pygame event get()if event type =pygame quitprint('received quit event:'eventrunning false print('game over'pygame quit(if __name__ ='__main__'main(there are several key steps highlighted by this examplethese steps are import pygame pygame is of course not one of the default modules available within python you must first import pygame into you code the import pygame statement imports the pygame module into your code and makes the functions and classes in pygame available to you (note the capitalisation pygame is not the same module name as pygameit is also common to find that programs import from pygame locals import this adds several constants and functions into the namespace of your program in this very simple example we have not needed to do this initialise pygame almost every pygame module needs to be initialised in some way and the simplest way to do this is to call pygame init(this will do what is required to set the pygame environment up for use if you forget to call this function you will typically get an error message such as pygame errorvideo system not initialised (or something similarif you get such
19,159
building games with pygame method check to see that you have called pygame init(note that you can initialise individual pygame modules (for example the pygame font module can be initialised using pygame font init()if required however pygame init(is the most commonly used approach to setting up pygame set up the display once you have initialised the pygame framework you can setup the display in the above code examplethe display is set up using the pygame display set_mode(function this function takes tuple specifying the size of the window to be created (in this case pixels wide by pixels highnote that if you try and invoke this function by passing in two parameters instead of tuplethen you will get an error this function returns the drawing surface or screen/window that can be used to display items within the game such as iconsmessagesshapes etc as our example is so simple we do not bother saving it into variable howeveranything more complex than this will need to do so we also set the window/frame' caption (or titlethis is displayed in the title bar of the window render the display we now call the pygame display update(function this function causes the current details of the display to be drawn at the moment this is blank window howeverit is common in games to perform series of updates to the display in the background and then when the program is ready to update the display to call this function this batches series of updates and the causes the display to be refreshed in complex display it is possible to indicate which parts of the display need to be redrawn rather than redrawing the whole window this is done by passing parameter into the update(function to indicate the rectangle to be redrawn howeverour example is so simple we are ok with redrawing the whole window and therefore we do not need to pass any parameters to the function main game playing loop it is common to have main game playing loop that drives the processing of user inputsmodifies the state of the game and updates the display this is represented above by the while runningloop the local variable running is initialised to true this means that the while loop ensures that the game continues until the user selects to quit the game at which point the running variable is set to false which causes the loop to exit in many cases this loop will call update(to refresh the display the above example does not do this as nothing is changed in the display however the example developed later in this will illustrate this idea monitor for events that drive the game as mentioned earlier the event queue is used to allow user inputs to be queued and then processed by the game in the simple example shown above this is represented by for loop that receives events using pygame event get(and then checking to see if the event is pygame quit event if it isthen it sets the running flag to false which will cause the main while loop of the game to terminate quit pygame once finished in pygame any module that has an init(function also has an equivalent quit(function that can be used to perform any cleanup operations as we called init(on the pygame module at the
19,160
first pygame application start of our program we will therefore need to call pygame quit(at the end of the program to ensure everything is tidied up appropriately the output generated from sample run of this program is given belowpygame hello from the pygame community starting game initialising pygame initialising helloworldgame update display starting main game playing loop received quit eventgame over further concepts there are very many facilities in pygame that go beyond what we can cover in this bookhowever few of the more common are discussed below surfaces are hierarchy the top level display surface may contain other surfaces that may be used to draw images or text in turn containers such as panels may render surfaces to display images or text etc other types of surface the primary display surface is not the only surface in pygame for examplewhen an imagesuch as png or jpeg image is loaded into game then it is rendered onto surface this surface can then be displayed within another surface such as the display surface this means that anything you can do to the display surface you can do with any other surface such as draw on itput text on itcolour itadd another icon onto the surface etc fonts the pygame font font object is used to create font that can be used to render text onto surface the render method returns surface with the text rendered on it that can be displayed within another surface such as the display surface note that you cannot write text onto an existing surface you must always obtain new surface (using renderand then add that to an existing surface the text can only be displayed in single line and the surface holding the text will be of the dimensions required to render the text for exampletext_font pygame font font('freesansbold ttf' text_surface text_font render('hello world'antialias=truecolor=bluethis creates new font object using the specified font with the specified font size (in this case it will then render the string 'hello worldon to new surface using the specified font and font size in blue specifying that antialias is true indicates that we would like to smooth the edges of the text on the screen
19,161
building games with pygame rectangles (or rectsthe pygame rect class is an object used to represent rectangular coordinates rect can be created from combination of the top left corner coordinates plus width and height for flexibility many functions that expect rect object can also be given rectlike listthis is list that contains the data necessary to create rect object rects are very useful in pygame game as they can be used to define the borders of game object this means that they can be used within games to detect if two objects have collided this is made particularly easy because the rect class provides several collision detection methodspygame rect contains(test if one rectangle is inside another pygame rect collidepoint(test if point is inside rectangle pygame rect colliderect(test if two rectangles overlap pygame rect collidelist(test if one rectangle in list intersects pygame rect collidelistall(test if all rectangles in list intersect pygame rect collidedict(test if one rectangle in dictionary intersects pygame rect collidedictall(test if all rectangles in dictionary intersect the class also provides several other utility methods such as move(which moves the rectangle and inflate(which can grow or shrink the rectangles size drawing shapes the pygame draw module has numerous functions that can be used to draw lines and shapes onto surfacefor examplepygame draw rect(display_surfaceblue[xywidthheight]this will draw filled blue rectangle (the defaultonto the display surface the rectangle will be located at the location indicated by and (on the surfacethis indicates the top left hand corner of the rectangle the width and height of the rectangle indicate its size note that these dimensions are defined within list which is structure referred to as being rect like (see belowif you do not want filled rectangle ( you just want the outlinethen you can use the optional width parameter to indicate the thickness of the outer edge other methods available includepygame draw polygon(draw shape with any number of sides pygame draw circle(draw circle around point pygame draw ellipse(draw round shape inside rectangle pygame draw arc(draw partial section of an ellipse pygame draw line(draw straight line segment pygame draw lines(draw multiple contiguous line segments pygame draw aaline(draw fine antialiased lines pygame draw aalines(draw connected sequence of antialiased lines
19,162
further concepts images the pygame image module contains functions for loadingsaving and transforming images when an image is loaded into pygameit is represented by surface object this means that it is possible to drawmanipulate and process an image in exactly the same way as any other surface which provides great deal of flexibility at minimum the module only supports loading uncompressed bmp images but usually also supports jpegpnggif (non-animated)bmptiff as well as other formats howeverit only supports limited set of formats when saving imagesthese are bmptgapng and jpeg an image can be loaded from file usingimage_surface pygame image load(filenameconvert(this will load the image from the specified file onto surface one thing you might wonder at is the use of the convert(method on the object returned from the pygame image load(function this function returns surface that is used to display the image contained in the file we call the method convert(on this surfacenot to convert the image from particular file format (such as pngor jpeginstead this method is used to convert the pixel format used by the surface if the pixel format used by the surface is not the same as the display formatthen it will need to be converted on the fly each time the image is displayed on the screenthis can be fairly time consuming (and unnecessaryprocess we therefore do this once when the image is loaded which means that it should not hinder runtime performance and may improve performance significantly on some systems once you have surface containing an image it can be rendered onto another surfacesuch as the display surface using the surface blit(method for exampledisplay_surface blit(image_surface(xy)note that the position argument is tuple specifying the and coordinates to the image on the display surface strictly speaking the blit(method draws one surface (the source surfaceonto another surface at the destination coordinates thus the target surface does not beed to be the top level display surface clock clock object is an object that can be used to track time in particular it can be used to define the frame rate for the game that is the number of frames rendered per second this is done using the clock tick(method this method should be called once (and only onceper frame if you pass the optional framerate argument to the tick(the functionthen pygame will ensure that
19,163
building games with pygame the games refresh rate is slower then the the given ticks per second this can be used to help limit the runtime speed of game by calling clock tick ( once per framethe program will never run at more than frames per second more interactive pygame application the first pygame application we looked at earlier just displayed window with the caption 'hello worldwe can now extend this little by playing with some of the features we have looked at above the new application will add some mouse event handling this will allow us to pick up the location of the mouse when the user clicked on the window and draw small blue box at that point if the user clicks the mouse multiple times we will get multiple blue boxes being drawn this is shown below this is still not much of game but does make the pygame application more interactive the program used to generate this application is presented belowimport pygame frame_refresh_rate blue ( background ( white width height def main()print('initialising pygame'pygame init(required by every pygame application
19,164
more interactive pygame application print('initialising box game'display_surface pygame display set_mode(( )pygame display set_caption('box game'print('update display'pygame display update(print('setup the clock'clock pygame time clock(clear the screen of current contents display_surface fill(backgroundprint('starting main game playing loop'running true while runningfor event in pygame event get()if event type =pygame quitprint('received quit event:'eventrunning false elif event type =pygame mousebuttondownprint('received mouse event'eventxy event pos pygame draw rect(display_surfaceblue[xywidthheight]update the display pygame display update(defines the frame rate the number of frames per second should be called once per frame (but only onceclock tick(frame_refresh_rateprint('game over'now tidy up and quit python pygame quit(if __name__ ='__main__'main(note that we now need to record the display surface in local variable so that we can use it to draw the blue rectangles we also need to call the pygame display update(function each time round the main while loop so that the new rectangles we have drawn as part of the event processing for loop are displayed to the user we also set the frame rate each time round the main while loop this should happen once per frame (but only onceand uses the clock object initialised at the start of the program
19,165
building games with pygame alternative approach to processing input devices there are actually two ways in which inputs from device such as mousejoystick or the keyboard can be processed one approach is the event based model described earlier the other approach is the state based approach although the event based approach has many advantages is has two disadvantageseach event represents single action and continuous actions are not explicitly represented thus if the user presses both the key and the key then this will generate two events and it will be up to the program to determine that they have been pressed at the same time it is also up to the program to determine that the user is still pressing key (by noting that no keyup event has occurredboth of these are possible but can be error prone an alternative approach is to use the state based approach in the state based approach the program can directly check the state of input device (such as key or mouse or keyboardfor exampleyou can use pygame key get_pressed(which returns the state of all the keys this can be used to determine if specific key is being pressed at this moment in time for examplepygame key get_pressed()[pygame k_spacecan be used to check to see if the space bar is being pressed this can be used to determine what action to take if you keep checking that the key is pressed then you can keep performing the associated action this can be very useful for continues actions in game such as moving an object etc howeverif the user presses key and then releases it before the program checks the state of the keyboard then that input will be missed pygame modules there are numerous modules provided as part of pygame as well as associated libraries some of the core modules are listed belowpygame display this module is used to control the display window or screen it provides facilities to initialise and shutdown the display module it can be used to initialise window or screen it can also be used to cause window or screen to refresh etc
19,166
pygame modules pygame event this module manages events and the event queue for example pygame event get(retrieves events from the event queuepygame event poll(gets single event from the queue and pygame event peek(tests to see if there are any event types on the queue pygame draw the draw module is used to draw simple shapes onto surface for exampleit provides functions for drawing rectangle (pygame draw rect) polygona circlean ellipsea line etc pygame font the font module is used to create and render truetype fonts into new surface object most of the features associated with fonts are supported by the pygame font font class free standing module functions allow the module to be initialised and shutdownplus functions to access fonts such as pygame font get_fonts(which provides list of the currently available fonts pygame image this module allows images to be saved and loaded note that images are loaded into surface object (there is no image class unlike many other gui oriented frameworkspygame joystick the joystick module provides the joystick object and several supporting functions these can be used for interacting with joysticksgamepads and trackballs pygame key this module provides support for working with inputs from the keyboard this allows the input keys to be obtained and modifier keys (such as control and shiftto be identified it also allows the approach to repeating keys to be specified pygame mouse this module provides facilities for working with mouse input such as obtaining the current mouse positionthe state of mouse buttons as well as the image to use for the mouse pygame time this is the pygame module for managing timing within game it provides the pygame time clock class that can be used to track time online resources there is great deal of information available on pygame includingnews://gmane comp python pygame the official pygame news group
19,167
starshipmeteors pygame creating spaceship game in this we will create game in which you pilot starship through field of meteors the longer you play the game the larger the number of meteors you will encounter typical display from the game is shown below for apple mac and windows pcwe will implement several classes to represent the entities within the game using classes is not required way to implement game and it should be noted that many developers avoid the use of classes howeverusing class allows data associated with an object within the game to be maintained in one placeit also simplifies the creation of multiple instances of the same object (such as the meteorswithin the game (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,168
starshipmeteors pygame the classes and their relationships are shown belowthis diagram shows that the starship and meteor classes will extend class called gameobject in turn it also shows that the game has : relationship with the starship class that is the game holds reference to one starship and in turn the starship holds single reference back to the game in contrast the game has to many relationship with the meteor class that is the game object holds references to many meteors and each meteor holds reference back to the single game object the main game class the first class we will look at will be the game class itself the game class will hold the list of meteors and the starship as well as the main game playing loop it will also initialise the main window display (for example by setting the size and the caption of the windowin this case we will store the display surface returned by the pygame display set_mode(function in an attribute of the game object called display_surface this is because we will need to use it later on to display the starship and the meteors we will also hold onto an instance of the pygame time clock(class that we will use to set the frame rate each time round the main game playing while loop the basic framework of our game is shown belowthis listing provides the basic game class and the main method that will launch the game the game also defines three global constants that will be used to define the frame refresh rate and the size of the display
19,169
the main game class import pygame set up global 'constantsframe_refresh_rate display_width display_height class game""represents the game itself and game playing loop ""def __init__(self)print('initialising pygame'pygame init(set up the display self display_surface pygame display set_mode((display_widthdisplay_height)pygame display set_caption('starship meteors'used for timing within the program self clock pygame time clock(def play(self)is_running true main game playing loop while is_runningwork out what the user wants to do for event in pygame event get()if event type =pygame quitis_running false elif event type =pygame keydownif event key =pygame k_qis_running false update the display pygame display update(defines the frame rate self clock tick(frame_refresh_ratelet pygame shutdown gracefully pygame quit(def main()print('starting game'game game(game play(print('game over'if __name__ ='__main__'main(
19,170
starshipmeteors pygame the main play(method of the game class has loop that will continue until the user selects to quit the game they can do this in one of two wayseither by pressing the 'qkey (represented by the event key k_qor by clicking on the window close button in either case these events are picked up in the main event processing for loop within the main while loop method if the user does not want to quit the game then the display is updated (refreshedand then the clock tick((or framerate is set when the user selects to quit the game then the main while loop is terminated (the is_running flag is set to falseand the pygame quit(method is called to shut down pygame at the moment this not very interactive game as it does not do anything except allow the user to quit in the next section we will add in behaviour that will allow us to display the space ship within the display the gameobject class the gameobject class defines three methodsthe load_image(method can be used to load an image to be used to visually represent the specific type of game object the method then uses the width and height of the image to define the width and height of the game object the rect(method returns rectangle representing the current area used by the game object on the underlying drawing surface this differs from the images own rect(which is not related to the location of the game object on the underlying surface rects are very useful for comparing the location of one object with another (for example when determining if collision has occurredthe draw(method draws the gameobjectsimage onto the display_surface held by the game using the gameobjects current and coordinates it can be overridden by subclasses if they wish to be drawn in different way the code for the gameobject class is presented belowclass gameobjectdef load_image(selffilename)self image pygame image load(filenameconvert(self width self image get_width(self height self image get_height(def rect(self)""generates rectangle representing the objects location and dimensions ""
19,171
the gameobject class return pygame rect(self xself yself widthself heightdef draw(self)""draw the game object at the current xy coordinates ""self game display_surface blit(self image(self xself )the gameobject class is directly extended by the starship class and the meteor class currently there are only two types of game elementsthe starship and the meteorsbut this could be extended in future to planetscometsshooting stars etc displaying the starship the human player of this game will control starship that can be moved around the display the starship will be represented by an instance of the class starship this class will extend the gameobject class that holds common behaviours for any type of element that is represented within the game the starship class defines its own __init__(method that takes reference to the game that the starship is part of this initialisation method sets the initial starting location of the starship as half the width of the display for the coordinate and the display height minus for the coordinate (this gives bit of buffer before the end of the screenit then uses the load_image(method from the gameobject parent class to load the image to be used to represent the starship this is held in file called starship png for the moment we will leave the starship class as it is (however we will return to this class so that we can make it into movable object in the next sectionthe current version of the starship class is given belowclass starship(gameobject)""represents starship""def __init__(selfgame)self game game self display_width self display_height self load_image('starship png'
19,172
starshipmeteors pygame in the game class we will now add line to the __init__(method to initialise the starship object this line isset up the starship self starship starship(selfwe will also add line to the main while loop within the play(method just before we refresh the display this line will call the draw(method on the starship objectdraw the starship self starship draw(this will have the effect of drawing the starship onto the windows drawing surface in the background before the display is refreshed when we now run this version of the starshipmeteor game we now see the starship in the displayof course at the moment the starship does not movebut we will address that in the next section moving the spaceship we want to be able to move the starship about within the bounds of the display screen to do this we need to change the starships and coordinates in response to the user pressing various keys we will use the arrow keys to move up and down the screen or to the left or right of the screen to do this we will define four methods within the starship classthese methods will move the starship updownleft and right etc
19,173
moving the spaceship the updated starship class is shown belowthis version of the starship class defines the various move methods these methods use new global value starship_speed to determine how far and how fast the starship moves if you want to change the speed that the starship moves then you can change this global value depending upon the direction intended we will need to modify either the or coordinate of the starship if the starship moves to the left then the coordinate is reduced by starship_speedif it moves to the right then the coordinate is increased by starship_speedin turn if the starship moves up the screen then the coordinate is decremented by starship_speed
19,174
starshipmeteors pygame but if it moves down the screen then the coordinate is increased by starship_speed of course we do not want our starship to fly off the edge of the screen and so test must be made to see if it has reached the boundaries of the screen thus tests are made to see if the or values have gone below zero or above the display_width or display_height values if any of these conditions are met then the or values are reset to an appropriate default we can now use these methods with player input this player input will indicate the direction that the player wants to move the starship as we are using the leftrightup and down arrow keys for this we can extend the event processing loop that we have already defined for the main game playing loop as with the letter qthe event keys are prefixed by the letter and an underbarbut this time the keys are named k_leftk_rightk_up and k_down when one of these keys is pressed then we will call the appropriate move method on the starship object already held by the game object the main event processing for loop is nowwork out what the user wants to do for event in pygame event get()if event type =pygame quitis_running false elif event type =pygame keydowncheck to see which key is pressed if event key =pygame k_rightright arrow key has been pressed move the player right self starship move_right(elif event key =pygame k_leftleft arrow has been pressed move the player left self starship move_left(elif event key =pygame k_upself starship move_up(elif event key =pygame k_downself starship move_down(elif event key =pygame k_qis_running false howeverwe are not quite finished if we try and run this version of the program we will get trail of starships drawn across the screenfor example
19,175
moving the spaceship the problem is that we are redrawing the starship at different positionbut the previous image is still present we now have two choices one is to merely fill the whole screen with blackeffectively hiding anything that has been drawn so faror alternatively we could just draw over the area used by the previous image position which approach is adopted depends on the particular scenario represented by your game as we will have lot of meteors on the screen once we have added themthe easiest option is to overwrite everything on the screen before redrawing the starship we will therefore add the following lineclear the screen of current contents self display_surface fill(backgroundthis line is added just before we draw the starship within the main game playing while loop now when we move the starship the old image is removed before we draw the new imageone point to note is that we have also defined another global value background used to hold the background colour of the game playing surface this is set to black as shown below
19,176
starshipmeteors pygame define default rgb colours background ( if you want to use different background colour then change this global value adding meteor class the meteor class will also be subclass of the gameobject class howeverit will only provide move_down(method rather than the variety of move methods of the starship it will also need to have random starting coordinate so that when meteor is added to the game its starting position will vary this random position can be generated using the random randint(function using value between and the width of the drawing surface the meteor will also start at the top of the screen so will have different initial coordinate to the starship finallywe also want our meteors to have different speedsthis can be another random number between and some specified maximum meteor speed to support these we need to add random to the modules being imported and define several new global valuesfor exampleimport pygamerandom initial_meteor_y_location max_meteor_speed we can now define the meteor classclass meteor(gameobject)""represents meteor in the game ""def __init__(selfgame)self game game self random randint( display_widthself initial_meteor_y_location self speed random randint( max_meteor_speedself load_image('meteor png'def move_down(self)""move the meteor down the screen ""self self self speed if self display_heightself def __str__(self)return 'meteor(str(self 'str(self ')
19,177
adding meteor class the __init__(method for the meteor class has the same steps as the starshipthe difference is that the coordinate and the speed are randomly generated the image used for the meteor is also different as it is 'meteor pngwe have also implemented move_down(method this is essentially the same as the starships move_down(note that at this point we could create subclass of gameobject called moveablegameobject (which extends gameobjectand push the move operations up into that class and have the meteor and starship classes extend that class however we don' really want to allow meteors to move just anywhere on the screen we can now add the meteors to the game class we will add new global value to indicate the number of initial meteors in the gameinitial_number_of_meteors next we will initialise new attribute for the game class that will hold list of meteors we will use list here as we want to increase the number of meteors as the game progresses to make this process easy we will use list comprehension which allows for loop to run with the results of an expression captured by the listset up meteors self meteors [meteor(selffor in range( initial_number_of_meteors)we now have list of meteors that need to be displayed we thus need to update the while loop of the play(method to draw not only the starship but also all the meteorsdraw the meteors and the starship self starship draw(for meteor in self meteorsmeteor draw(the end result is that set of meteor objects are created at random starting locations across the top of the screen
19,178
starshipmeteors pygame moving the meteors we now want to be able to move the meteors down the screen so that the starship has some objects to avoid we can do this very easily as we have already implemented move_down(method in the meteor class we therefore only need to add for loop to the main game playing while loop that will move all the meteors for examplemove the meteors for meteor in self meteorsmeteor move_down(this can be added after the event processing for loop and before the screen is refreshed/redrawn or updated now when we run the game the meteors move and the player can navigate the starship between the falling meteors identifying collision at the moment the game will play for ever as there is no end state and no attempt to identify if starship has collided with meteor we can add meteor/starship collision detection using pygame rects as mentioned in the last rect is pygame class used to represent rectangular coordinates it is particularly useful as the pygame rect class provides several collision detection methods that can be used to test if one rectangle (or pointis inside another rectangle we can therefore use one of the methods to test if the rectangle around the starship intersects with any of the rectangles around the meteors
19,179
identifying collision the gameobject class already provides method rect(that will return rect object representing the objectscurrent rectangle with respect to the drawing surface (essentially the box around the object representing its location on the screenthus we can write collision detection method for the game class using the gameobject generated rects and the rect class colliderect(methoddef _check_for_collision(self)""checks to see if any of the meteors have collided with the starship ""result false for meteor in self meteorsif self starship rect(colliderect(meteor rect())result true break return result note that we have followed the convention here of preceding the method name with an underbar indicating that this method should be considered private to the class it should therefore never be called by anything outside of the game class this convention is defined in pep (python enhancement proposalbut is not enforced by the language we can now use this method in the main while loop of the game to check for collisioncheck to see if meteor has hit the ship if self _check_for_collision()starship_collided true this code snippet also introduces new local variable starship_collided we will initially set this to false and is another condition under which the main game playing while loop will terminateis_running true starship_collided false main game playing loop while is_running and not starship_collidedthus the game playing loop will terminate if the user selects to quit or if the starship collides with meteor
19,180
starshipmeteors pygame identifying win we currently have way to loose the game but we don' have way to win the gamehoweverwe want the player to be able to win the game by surviving for specified period of time we could represent this with timer of some sort howeverin our case we will represent it as specific number of cycles of the main game playing loop if the player survives for this number of cycles then they have won for examplesee if the player has won if cycle_count =max_number_of_cyclesprint('winner!'break in this case message is printed out stating that the player won and then the main game playing loop is terminated (using the break statementthe max_number_of_cycles global value can be set as appropriatefor examplemax_number_of_cycles increasing the number of meteors we could leave the game as it is at this pointas it is now possible to win or loose the game howeverthere are few things that can be easily added that will enhance the game playing experience one of these is to increase the number of meteors on the screen making it harder as the game progresses we can do this using new_meteor_cycle_interval new_meteor_cycle_interval when this interval is reached we can add new meteor to the list of current meteorsit will then be automatically drawn by the game class for exampledetermine if new meteors should be added if cycle_count new_meteor_cycle_interval = self meteors append(meteor(self)
19,181
increasing the number of meteors now every new_meteor_cycle_interval another meteor will be added at random coordinate to the game pausing the game another feature that many games have is the ability to pause the game this can be easily added by monitoring for pause key (this could be the letter represented by the event_key pygame k_pwhen this is pressed the game could be paused until the key is pressed again the pause operation can be implemented as method _pause(that will consume all events until the appropriate key is pressed for exampledef _pause(self)paused true while pausedfor event in pygame event get()if event type =pygame keydownif event key =pygame k_ppaused false break in this method the outer while loop will loop until the paused local variable is set too false this only happens when the 'pkey is pressed the break after the statement setting paused to false ensures that the inner for loop is terminated allowing the outer while loop to check the value of paused and terminate the _pause(method can be invoked during the game playing cycle by monitoring for the 'pkey within the event for loop and calling the _pause(method from thereelif event key =pygame k_pself _pause(note that again we have indicated that we don' expect the _pause(method to be called from outside the game by prefixing the method name with an underbar (' '
19,182
starshipmeteors pygame displaying the game over message pygame does not come with an easy way of creating popup dialog box to display messages such as 'you won'or 'you lostwhich is why we have used print statements so far howeverwe could use gui framework such as wxpython to do this or we could display message on the display surface to indicate whether the player has won or lost we can display message on the display surface using the pygame font font class this can be used to create font object that can be rendered onto surface that can be displayed onto the main display surface we can therefore add method _display_message(to the game class that can be used to display appropriate messagesdef _display_message(selfmessage)""displays message to the user on the screen ""print(messagetext_font pygame font font('freesansbold ttf' text_surface text_font render(messagetruebluewhitetext_rectangle text_surface get_rect(text_rectangle center (display_width display_height self display_surface fill(whiteself display_surface blit(text_surfacetext_rectangleagain the leading underbar in the method name indicates that it should not be called from outside the game class we can now modify the main loop such that appropriate messages are displayed to the userfor examplecheck to see if meteor has hit the ship if self _check_for_collision()starship_collided true self _display_message('collisiongame over'
19,183
displaying the game over message the result of the above code being run when collision occurs is shown below the starshipmeteors game the complete listing for the final version of the starshipmeteors game is given belowimport pygamerandomtime frame_refresh_rate display_width display_height white ( background ( initial_meteor_y_location initial_number_of_meteors max_meteor_speed starship_speed max_number_of_cycles new_meteor_cycle_interval
19,184
starshipmeteors pygame class gameobjectdef load_image(selffilename)self image pygame image load(filenameconvert(self width self image get_width(self height self image get_height(def rect(self)""generates rectangle representing the objects location and dimensions ""return pygame rect(self xself yself widthself heightdef draw(self)""draw the game object at the current xy coordinates ""self game display_surface blit(self image(self xself )class starship(gameobject)""represents starship""def __init__(selfgame)self game game self display_width self display_height self load_image('starship png'def move_right(self)""moves the starship right across the screen ""self self starship_speed if self self width display_widthself display_width self width def move_left(self)""move the starship left across the screen ""self self starship_speed if self self def move_up(self)""move the starship up the screen ""self self starship_speed if self self def move_down(self)""move the starship down the screen ""self self starship_speed if self self height display_height
19,185
the starshipmeteors game self display_height self height def __str__(self)return 'starship(str(self 'str(self ')class meteor(gameobject)""represents meteor in the game ""def __init__(selfgame)self game game self random randint( display_widthself initial_meteor_y_location self speed random randint( max_meteor_speedself load_image('meteor png'def move_down(self)""move the meteor down the screen ""self self self speed if self display_heightself def __str__(self)return 'meteor(str(self 'str(self ')class game""represents the game itselfholds the main game playing loop ""def __init__(self)pygame init(set up the display self display_surface pygame display set_mode((display_widthdisplay_height)pygame display set_caption('starship meteors'used for timing within the program self clock pygame time clock(set up the starship self starship starship(selfset up meteors self meteors [meteor(selffor in range( initial_number_of_meteors)def _check_for_collision(self)""checks to see if any of the meteors have collided with the starship ""result false for meteor in self meteorsif self starship rect(colliderect(meteor rect())result true
19,186
starshipmeteors pygame break return result def _display_message(selfmessage)""displays message to the user on the screen ""text_font pygame font font('freesansbold ttf' text_surface text_font render(messagetruebluewhitetext_rectangle text_surface get_rect(text_rectangle center (display_width display_height self display_surface fill(whiteself display_surface blit(text_surfacetext_rectangledef _pause(self)paused true while pausedfor event in pygame event get()if event type =pygame keydownif event key =pygame k_ppaused false break def play(self)is_running true starship_collided false cycle_count main game playing loop while is_running and not starship_collidedindicates how many times the main game loop has been run cycle_count + see if the player has won if cycle_count =max_number_of_cyclesself _display_message('winner!'break work out what the user wants to do for event in pygame event get()if event type =pygame quitis_running false elif event type =pygame keydowncheck to see which key is pressed if event key =pygame k_rightright arrow key has been pressed move the player right self starship move_right(elif event key =pygame k_leftleft arrow has been pressed
19,187
the starshipmeteors game move the player left self starship move_left(elif event key =pygame k_upself starship move_up(elif event key =pygame k_downself starship move_down(elif event key =pygame k_pself _pause(elif event key =pygame k_qis_running false move the meteors for meteor in self meteorsmeteor move_down(clear the screen of current contents self display_surface fill(backgrounddraw the meteors and the starship self starship draw(for meteor in self meteorsmeteor draw(check to see if meteor has hit the ship if self _check_for_collision()starship_collided true self _display_message('collisiongame over'determine if new mateors should be added if cycle_count new_meteor_cycle_interval = self meteors append(meteor(self)update the display pygame display update(defines the frame rate the number is number of frames per second should be called once per frame (but only onceself clock tick(frame_refresh_ratetime sleep( let pygame shutdown gracefully pygame quit(def main()print('starting game'game game(game play(print('game over'if __name__ ='__main__'main(
19,188
starshipmeteors pygame online resources there is great deal of information available on pygame includingcode exercises using the example presented in this add the followingprovide score counter this could be based on the number of cycles the player survives or the number of meteors that restart from the top of the screen etc add another type of gameobjectthis could be shooting star that moves across the screen horizontallyperhaps using an random starting coordinate allow the game difficulty to be specified at the start this could affect the number of initial meteorsthe maximum speed of meteorthe number of shooting stars etc
19,189
introduction to testing introduction this considers the different types of tests that you might want to perform with the systems you develop in python it also introduces test driven development types of testing there are at least two ways of thinking about testing it is the process of executing program with the intent of finding errors/bugs (see glenford myersthe art of software testing it is process used to establish that software components fulfil the requirements identified for themthat is that they do what they are supposed to do these two aspects of testing tend to have been emphasised at different points in the software lifecycle error testing is an intrinsic part of the development processand an increasing emphasis is being placed on making testing central part of software development (see test driven developmentit should be noted that it is extremely difficult--and in many cases impossible-to prove that software works and is completely error free the fact that set of tests finds no defects does not prove that the software is error-free 'absence of evidence is not evidence of absence!this was discussed in the late and early by dijkstra and can be summarised astesting shows the presencenot the absence of bugs testing to establish that software components fulfil their contract involves checking operations against their requirements although this does happen at (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science
19,190
introduction to testing development timeit forms major part of quality assurance (qaand user acceptance testing it should be noted that with the advent of test-driven developmentthe emphasis on testing against requirements during development has become significantly higher there are of course many other aspects to testingfor exampleperformance testing which identifies how system will perform as various factors that affect that system change for exampleas the number of concurrent requests increaseas the number of processors used by the underlying hardware changesas the size of the database grows etc however you view testingthe more testing applied to system the higher the level of confidence that the system will work as required what should be testedan interesting question is 'what aspects of your software system should be subject to testing?in generalanything that is repeatable should be subject to formal (and ideally automatedtesting this includes (but is not limited to)the build process for all technologies involved the deployment process to all platforms under consideration the installation process for all runtime environments the upgrade process for all supported versions (if appropriatethe performance of the system/servers as loads increase the stability for systems that must run for any period of time ( systemsthe backup processes the security of the system the recovery ability of the system on failure the functionality of the system the integrity of the system notice that only the last two of the above list might be what is commonly considered areas that would be subject to testing howeverto ensure the quality of the system under considerationall of the above are relevant in facttesting should cover all aspects of the software development lifecycle and not just the qa phase during requirements gathering testing is the process of looking for missing or ambiguous requirements during this phase consideration should also be made with regard to how the overall requirements will be testedin the final software system
19,191
what should be tested test planning should also look at all aspects of the software under test for functionalityusabilitylegal complianceconformance to regulatory constraintssecurityperformanceavailabilityresilienceetc testing should be driven by the need to identify and reduce risk testing software systems as indicated above there are number of different types of testing that are commonly used within industry these types areunit testingwhich is used to verify the behaviour of individual components integration testing that tests that when individual components are combined together to provide higher-level functional unitsthat the combination of the units operates appropriately regression testing when new components are added to systemor existing components are changedit is necessary to verify that the new functionality does not break any existing functionality such testing is known as regression testing performance testing is used to ensure that the systemsperformance is as required andwithin the design parametersand is able to scale as utilisation increases stability testing represents style of testing which attempts to simulate system operation over an extended period of time for examplefor online shopping application that is expected to be up and running stability test might ensure that with an average load that the system can indeed run hours day for days week
19,192
introduction to testing security testing ensures that access to the system is controlled appropriately given the requirements for examplefor an online shopping system there may be different security requirements depending upon whether you are browsing the storepurchasing some products or maintaining the product catalogue usability testing which may be performed by specialist usability group and may involved filming users while they use the system system testing validates that the system as whole actually meets the user requirements and conforms to required application integrity user acceptance testing is form of user oriented testing where users confirm that the system does and behaves in the way they expect installationdeployment and upgrade testing these three types of testing validate that system can be installed and deployed appropriate including any upgrade processes that may be required smoke tests used to check that the core elements of large system operate correctly they can typically be run quickly and in faction of the time taken to run the full system tests key testing approaches are discussed in the remainder of this section unit testing unit can be as small as single function or as large as subsystem but typically is classobjectself-contained library (apior web page by looking at small self-contained component an extensive set of tests can be developed to exercise the defined requirements and functionality of the unit unit testing typically follows white box approach(also called glass box or structural testing)where the testing utilizes knowledge and understanding of the code and its structurerather than just its interface (which is known as the black box approachin white box testingtest coverage is measured by the number of code paths that have been tested the goal in unit testing is to provide coverageto exercise every instructionall sides of each logical branchall called objectshandling of all data structuresnormal and abnormal termination of all loops etc of course this may not always be possible but it is goal that should be aimed for many automated test tools will include code coverage measure so that you are aware of how much of your code has been exercised by any given set of tests unit testing is almost always automated--there are many tools to help with thisperhaps the best-known being the xunit family of test frameworks such as junit for java and pyunit for python the framework allows developers tofocus on testing the unitsimulate data or results from calling another unit (representative good and bad results)
19,193
testing software systems create data driven tests for maximum flexibility and repeatabilityrely on mock objects that represent elements outside the unit that it must interact with having the tests automated means that they can be run frequentlyat the very least after initial development and after each change that affects the unit once confidence is established in the correct functioning of one unitdevelopers can then use it to help test other units with which it interfacesforming larger units that can also be unit tested oras the scale gets largerput through integration testing integration testing integration testing is where several units (or modulesare brought together to be tested as an entity in their own right typicallyintegration testing aims to ensure that modules interact correctly and the individual unit developers have interpreted the requirements in consistent manner an integrated set of modules can be treated as unit and unit tested in much the same way as the constituent modulesbut usually working at "higherlevel of functionality integration testing is the intermediate stage between unit testing and full system testing thereforeintegration testing focuses on the interaction between two or more units to make sure that those units work together successfully and appropriately such testing is typically conducted from the bottom up but may also be conducted top down using mocks or stubs to represented called or calling functions an important point to note is that you should not aim to test everything together at once (so called big bang testingas it is more difficult to isolate bugs in order that they can be rectified this is why it is more common to find that integration testing has been performed in bottom up style system testing system testing aims to validate that the combination of all the modulesunitsdatainstallationconfiguration etc operates appropriately and meets the requirements specified for the whole system testing the system has whole typically involves testing the top most functionality or behaviours of the system such behaviour based testing often involves end users and other stake holders who are less technical to support such tests range of technologies have evolved that allow more english style for test descriptions this style of testing can be used as part of the requirements gathering process and can lead to behaviour driven development (bddprocess the python module pytest-bdd provides bdd style extension to the core pytest framework
19,194
introduction to testing installation/upgrade testing installation testing is the testing of fullpartial or upgrade install processes it also validates that the installation and transition software needed to move to the new release for the product is functioning properly typicallyit verifies that the software may be completely uninstalled through its back-out process determines what files are addedchanged or deleted on the hardware on which the program was installed determines whether any other programs on the hardware are affected by the new software that has been installed determines whether the software installs and operates properly on all hardware platforms and operating systems that it is supposed to work on smoke tests smoke test is test or suite of tests designed to verify that the fundamentals of the system work smoke tests may be run against new deployment or patched deployment in order to verify that the installation performs well enough to justify further testing failure to pass smoke test would halt any further testing until the smoke tests pass the name derives from the early days of electronicsif device began to smoke after it was powered ontesters knew that there was no point in testing it further for software technologiesthe advantages of performing smoke tests includesmoke tests are often automated and standardised from one build to another because smoke tests validate things that are expected to workwhen they fail it is usually an indication that something fundamental has gone wrong (the wrong version of library has been usedor that new build has introduced bug into core aspects of the system if system is built dailyit should be smoke tested daily it will be necessary to periodically add to the smoke tests as new functionality is added to the system automating testing the actual way in which tests are written and executed needs careful consideration in generalwe wish to automate as much of the testing process as is possible as this makes it easy to run the tests and also ensures not only that all tests are run but that
19,195
automating testing they are run in the same way each time in additiononce an automated test is set up it will typically be quicker to re-run that automated test than to manually repeat series of tests howevernot all of the features of system can be easily tested via an automated test tool and in some cases the physical environment may make it hard to automate tests typicallymost unit testing is automated and most acceptance testing is manual you will also need to decide which forms of testing must take place most software projects should have unit testingintegration testingsystem testing and acceptance testing as necessary requirement not all projects will implement performance or stability testingbut you should be careful about omitting any stage of testing and be sure it is not applicable test driven development test driven development (or tddis development technique whereby developers write test cases before they write any implementation code the tests thus drive or dictate the code that is developed the implementation only provides as much functionality as is required to pass the test and thus the tests act as specification of what the code does (and some argue that the tests are thus part of that specification and provide documentation of what the system is capable oftdd has the benefit that as tests must be written firstthere are always set of tests available to perform unitintegrationregression testing etc this is good as developers can find that writing tests and maintaining tests is boring and of less interest than the actual code itself and thus put less emphasis into the testing regime than might be desirable tdd encouragesand indeed requiresthat developers maintain an exhaustive set of repeatable tests and that those tests are developed to the same quality and standards as the main body of code there are three rules of tdd as defined by robert martinthese are you are not allowed to write any production code unless it is to make failing unit test pass you are not allowed to write any more of unit test than is sufficient to failand compilation failures are failures you are not allowed to write any more production code than is sufficient to pass the one failing unit test this leads to the tdd cycle described in the next section
19,196
introduction to testing the tdd cycle there is cycle to development when working in tdd manner the shortest form of this cycle is the tdd mantrared green refactor which relates to the unit testing suite of tools where it is possible to write unit test within tools such as pycharmwhen you run pyunit or pytest test test view is shown with red indicating that test failed or green indicating that the test passed hence red/greenin other words write the test and let it failthen implement the code to ensure it passes the last part of this mantra is refactor which indicates once you have it working make the code cleanerbetterfitter by refactoring it refactoring is the process by which the behaviour of the system is not changed but the implementation is altered to improve it the full tdd cycle is shown by the following diagram which highlights the test first approach of tddthe tdd mantra can be seen in the tdd cycle that is shown above and described in more detail below write single test run the test and see it fail implement just enough code to get the test to pass run the test and see it pass refactor for clarity and deal with any issue of reuse etc repeat for next test
19,197
test driven development test complexity the aim is to strive for simplicity in all that you do within tdd thusyou write test that failsthen do just enough to make that test pass (but no morethen you refactor the implementation code (that is change the internals of the unit under testto improve the code base you continue to do this until all the functionality for unit has been completed in terms of each testyou should again strive for simplicity with each test only testing one thing with only single assertion per test (although this is the subject of lot of debate within the tdd worldrefactoring the emphasis on refactoring within tdd makes it more than just testing or test first development this focus on refactoring is really focus on (re)design and incremental improvement the tests provide the specification of what is needed as well as the verification that existing behaviour is maintainedbut refactoring leads to better design software thuswithout refactoring tdd is not tdd design for testability testability has number of facets configurability set up the object under test to an appropriate configuration for the test controllability control the input (and internal stateobservability observe its output verifiability that we can verify that output in an appropriate manner testability rules of thumb if you cannot test code then change it so that you canif your code is difficult to validate then change it so that it isn'tonly one concrete class should be tested per unit test and then mock the restif you code is hard to reconfigure to work with mocks then make it so that you code can use mocksdesign your code for testability
19,198
introduction to testing online resources see the following online resources for more information on testing and test driven development (tddintroduction to software testing introduction to software testing wiki book simple introduction to tdd with python game kata which presents worked example of how tdd can be used to create ten pin bowls scoring keeping application book resources the art of software testingg myersc sandler and badgettjohn wiley sons rd edition (dec )
19,199
pytest testing framework introduction there are several testing frameworks available for pythonalthough only oneunittest comes as part of the typical python installation typical libraries include unit test(which is available within the python distribution by defaultand pytest in this we will look at pytest and how it can be used to write unit tests in python for both functions and classes what is pytestpytest is testing library for pythonit is currently one of the most popular python testing libraries (others include unittest and doctestpytest can be used for various levels of testingalthough its most common application is as unit testing framework it is also often used as testing framework within tdd based development project in factit is used by mozilla and dropbox as their python testing framework pytest offers large number of features and great flexibility in how tests are written and in how set up behaviour is defined it automatically finds test based on naming conventions and can be easily integrated into range of editors and ides including pycharm (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science