- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Snake game in PyGTK
In this part of the PyGTK programming tutorial, we will create a Snake game clone.
Snake game
Snake is an older classic video game. It was first created in late 70s. Later it was brought to PCs. In this game the player controls a snake. The objective is to eat as many apples as possible. Each time the snake eats an apple, its body grows. The snake must avoid the walls and its own body. This game is sometimes called Nibbles.
Development
The size of each of the joints of a snake is 10px. The snake is controlled with the cursor keys. Initially the snake has three joints. The game starts immediately. If the game is finished, we display "Game Over" message in the middle of the Board.
snake.py
#!/usr/bin/python # ZetCode PyGTK tutorial # # This is a simple snake game # clone # # author: jan bodnar # website: zetcode.com # last edited: February 2009 import sys import gtk import cairo import random import glib WIDTH = 300 HEIGHT = 270 DOT_SIZE = 10 ALL_DOTS = WIDTH * HEIGHT / (DOT_SIZE * DOT_SIZE) RAND_POS = 26 x = [0] * ALL_DOTS y = [0] * ALL_DOTS class Board(gtk.DrawingArea): def __init__(self): super(Board, self).__init__() self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0, 0, 0)) self.set_size_request(WIDTH, HEIGHT) self.connect("expose-event", self.expose) self.init_game() def on_timer(self): if self.inGame: self.check_apple() self.check_collision() self.move() self.queue_draw() return True else: return False def init_game(self): self.left = False self.right = True self.up = False self.down = False self.inGame = True self.dots = 3 for i in range(self.dots): x[i] = 50 - i * 10 y[i] = 50 try: self.dot = cairo.ImageSurface.create_from_png("dot.png") self.head = cairo.ImageSurface.create_from_png("head.png") self.apple = cairo.ImageSurface.create_from_png("apple.png") except Exception, e: print e.message sys.exit(1) self.locate_apple() glib.timeout_add(100, self.on_timer) def expose(self, widget, event): cr = widget.window.cairo_create() if self.inGame: cr.set_source_rgb(0, 0, 0) cr.paint() cr.set_source_surface(self.apple, self.apple_x, self.apple_y) cr.paint() for z in range(self.dots): if (z == 0): cr.set_source_surface(self.head, x[z], y[z]) cr.paint() else: cr.set_source_surface(self.dot, x[z], y[z]) cr.paint() else: self.game_over(cr) def game_over(self, cr): w = self.allocation.width / 2 h = self.allocation.height / 2 (x, y, width, height, dx, dy) = cr.text_extents("Game Over") cr.set_source_rgb(65535, 65535, 65535) cr.move_to(w - width/2, h) cr.show_text("Game Over") self.inGame = False def check_apple(self): if x[0] == self.apple_x and y[0] == self.apple_y: self.dots = self.dots + 1 self.locate_apple() def move(self): z = self.dots while z > 0: x[z] = x[(z - 1)] y[z] = y[(z - 1)] z = z - 1 if self.left: x[0] -= DOT_SIZE if self.right: x[0] += DOT_SIZE if self.up: y[0] -= DOT_SIZE if self.down: y[0] += DOT_SIZE def check_collision(self): z = self.dots while z > 0: if z > 4 and x[0] == x[z] and y[0] == y[z]: self.inGame = False z = z - 1 if y[0] > HEIGHT - DOT_SIZE: self.inGame = False if y[0] < 0: self.inGame = False if x[0] > WIDTH - DOT_SIZE: self.inGame = False if x[0] < 0: self.inGame = False def locate_apple(self): r = random.randint(0, RAND_POS) self.apple_x = r * DOT_SIZE r = random.randint(0, RAND_POS) self.apple_y = r * DOT_SIZE def on_key_down(self, event): key = event.keyval if key == gtk.keysyms.Left and not self.right: self.left = True self.up = False self.down = False if key == gtk.keysyms.Right and not self.left: self.right = True self.up = False self.down = False if key == gtk.keysyms.Up and not self.down: self.up = True self.right = False self.left = False if key == gtk.keysyms.Down and not self.up: self.down = True self.right = False self.left = False class Snake(gtk.Window): def __init__(self): super(Snake, self).__init__() self.set_title('Snake') self.set_size_request(WIDTH, HEIGHT) self.set_resizable(False) self.set_position(gtk.WIN_POS_CENTER) self.board = Board() self.connect("key-press-event", self.on_key_down) self.add(self.board) self.connect("destroy", gtk.main_quit) self.show_all() def on_key_down(self, widget, event): key = event.keyval self.board.on_key_down(event) Snake() gtk.main()
First we will define some globals used in our game.
The WIDTH
and HEIGHT
constants determine the size of the Board. The DOT_SIZE
is the size of the apple and the dot of the snake. The ALL_DOTS
constant defines the maximum number of possible dots on the Board. The RAND_POS
constant is used to calculate a random position of an apple. The DELAY
constant determines the speed of the game.
x = [0] * ALL_DOTS y = [0] * ALL_DOTS
These two lists store x, y coordinates of all possible joints of a snake.
The init_game()
method initialises variables, loads images and starts a timeout function.
self.left = False self.right = True self.up = False self.down = False self.inGame = True self.dots = 3
When the game starts, the snake has three joints. And it is heading to the right.
In the move()
method we have the key algorithm of the game. To understand it, look at how the snakeis moving. You control the head of the snake. You can change its direction with the cursor keys. The rest of the joints move one position up the chain. The second joint moves where the first was, the third joint where the second was etc.
while z > 0: x[z] = x[(z - 1)] y[z] = y[(z - 1)] z = z - 1
This code moves the joints up the chain.
if self.left: x[0] -= DOT_SIZE
Move the head to the left.
In the checkCollision()
method, we determine if the snake has hit itself or one of the walls.
while z > 0: if z > 4 and x[0] == x[z] and y[0] == y[z]: self.inGame = False z = z - 1
We finish the game if the snake hits one of its joints with the head.
if y[0] > HEIGHT - DOT_SIZE: self.inGame = False
We finish the game if the snake hits the bottom of the Board.
The locate_apple()
method locates an apple randomly on the form.
r = random.randint(0, RAND_POS)
We get a random number from 0 to RAND_POS - 1.
self.apple_x = r * DOT_SIZE ... self.apple_y = r * DOT_SIZE
These line set the x, y coordinates of the apple object.
self.connect("key-press-event", self.on_key_down) ... def on_key_down(self, widget, event): key = event.keyval self.board.on_key_down(event)
We catch the key press event in the Snake class, and delegate the processing to the board object.
In the on_key_dow()
method of the Board class, we determine which keys the player hit.
if key == gtk.keysyms.Left and not self.right: self.left = True self.up = False self.down = False
If we hit the left cursor key, we set self.left
variable to True. This variable is used in the move()
method to change coordinates of the snake object. Notice also that when the snake is heading to the right, we cannot turn immediately to the left.

This was the Snake computer game programmed using PyGTK programming library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论