Package: game2dboard
game2dboardThis Python GUI package provides a graphical user interface (GUI) for 2D arrays (matrix) to make it easy to create board-style games.What is the aim of this library?I created this project to help my students from an introductory course on computer programming at the University of Passo Fundo (Brazil) to write programs with two-dimensional arrays in an easy and fun way. I think it can be useful for others.What types of games can be created?Any game that can be represented as a two-dimensional array, such as checkers, life, tic-tac-toe, chess, 2048, minefield, among many others.InstallationYou can use thepipto installgame2dboard:pip3 install game2dboardOr install the latest release by cloning the repository:gitclonehttps://github.com/mjbrusso/game2dboard.gitcdgame2dboard
python3setup.pyinstall--userUsageThe API is documentedbellowand within the docstrings.This simple code only provides an overview. See the examples for more details.Before running, copythisandthisfiles into aimg/folder(credits).fromgame2dboardimportBoarddefmouse_fn(btn,row,col):# mouse calback functionb[row][col]=1ifnotb[row][col]else0b=Board(3,4)# 3 rows, 4 columns, filled w/ Noneb[0][0]=1b.title="Click me!"b.cell_size=120b.cell_color="bisque"b.on_mouse_click=mouse_fnb.show()ResultGalerySome screenshots from examples.Memory Game58 SLOCView sourceSnake86 SLOCView sourceKill the mosquito75 SLOC w/ Background image and SoundsView sourceAPICreationgame2dboard.Board(nrows, ncols)Creates a Board.nrows:int– The number of rows.ncols:int– The number of columns.Indexerself[i][j]Gets/sets the value at rowi, columnj.When assigning a value, the GUI will be updated. If there is an.pngfile in theimg/folder whose name is the same as the new value, it will be drawn at position[i][j]of the board. Otherwise, the value will be displayed as text.Example:b[1][0]=100# draw 'img/100.png' @ row 1, column 0b[0][2]="correct"# draw 'img/correct.png'b[3][0]="wait.png"# draw 'img/wait.png'PropertiesUse properties to access board attributes like public fields.Example:b.title="Hello"# Sets the window titlesz=b.size# Gets the total number of elementsBoard propertiessize:int(readonly)Number of elements in the arraynrows:int(readonly)Number of rows in the array.ncols:int(readonly)Number of columns in the array.width:int(readonly)Board width, in px. Only available after .show()height:int(readonly)Board height, in px. Only available after .show()title:strGets or sets the window title.cursor:strGets or sets the mouse cursor shape. Setting toNonehides the cursor.See avaliable cursor names inhttps://anzeljg.github.io/rin2/book2/2405/docs/tkinter/cursors.htmlbackground_image:strGets or sets the background image file name. The.pngfile must be in the folderimg/Setting this property forcesgrid_color,margin_colorandcell_colortoNone.margin:intGets or sets the board margin (px).cell_spacing:intGets or sets the space between cells (px).margin_color:strGets or sets the margin color.cell_color:strGets or sets cells colorSee available color names inhttps://htmlcolorcodes.com/color-names/grid_color:strGets or sets grid color.cell_size:int | (int, int)Gets or sets the cells dimension (width,height).Event propertieson_start:function()Gets or sets the game started callback function.The GUI is ready and the program is going to enter the main loop.on_key_press:function(key: str)Gets or sets the keyboard callback function.See key names inhttps://anzeljg.github.io/rin2/book2/2405/docs/tkinter/key-names.htmlon_mouse_click:function(button: int, row: int, column: int)Gets or sets the mouse callback function.on_timer:function()Gets or sets the timer callback function.Methodsshow()Create the GUI, display and enter the run loop.clear()Clear the board, setting all values toNone.close()Close the board, exiting the program.shuffle()Random shuffle all values in the board.fill(value, row=None, col=None)Fill the board (or a row, or a column) with a value.value– The value to storerow(int) – Index of row to fill. Default=None(all rows)col(int) – Index of column to fill. Default=None(all columns)copy()Returns a shallow copy of the array (only data, not the GUI) into a regular Python list (of lists).load()Copy data from regular Python 2D array (list of lists) into the Board.create_output(**kwargs)Create a output message bar.kwargs:color=strbackground_color=strfont_size=intprint(*objects, sep=' ', end='')Print message to output bar.Use like built-inprint()function.start_timer(msecs)Start a periodic timer that executes the a function everymsecsmillisecondsThe callback function must be registered using.on_timerproperty.msecs(int) – Time in milliseconds.stop_timer()Stops the current timer.pause(msecs, change_cursor=True)Delay the program execution for a given number of milliseconds.Warning:long pause freezes the GUI!msecs(int) – Time in milliseconds.change_cursor(bool) – Change the cursor to "watch" during pause?What about Sound?To play sounds in the game, use myaudioplayer package.audioplayeris a cross platform Python 3 package for playing sounds (mp3, wav, ...). It provides the key features of an player, such as opening a media file, playing (loop/block), pausing, resuming, stopping, and setting the playback volume.fromaudioplayerimportAudioPlayerimportos# Background musicbgm_file=os.path.join(os.path.dirname(__file__),'background.mp3')bgm=AudioPlayer(bgm_file)bgm.volume=50# 50% volumebgm.play(loop=True)# start playing# Audio player is lazy loaded: resources loading is delayed until the first call to play() method.explosion=AudioPlayer(os.path.join(os.path.dirname(__file__),'explosion.mp3'))deftimer_callback():ifcollides(enemy,bullet):explosion.play()For a full example using AudioPlayer, seeKill the Mosquito.What's in the roadmap?save_file(filename): Dump array data to a fileread_file(filename): Restore array data from fileredim(new_ncols, new_nrows): Useful to grow or shrink the board, for example, on level up.How to ContributeSubmitting an issueUse theissue trackerto submit bug reports and features or enhancements requests.TranslatingYou can contribute by translating this document into other languages ​​(exceptenandpt_br).Submitting a pull requestIf you can improve anything in this project, feel free to add apull request.Licensegame2dboard is underMIT license. It can be reused within proprietary software provided that all copies of the licensed software include a copy of the MIT License terms and the copyright notice.