Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

A Simple Python Alarm Clock

Friday, April 11, 2008

Problem: You are all alone in a far away land and needed to wake up early the next day. The problem is, you forgot to bring any alarm clock. But, you brought a Linux-powered laptop computer with you. Say for example an Asus Eee PC.


Solution
: Most Linux distributions have Python installed out-of-the-box. All you need is this very simple Python alarm clock script:




import time
import os

not_executed = 1

while(not_executed):
dt = list(time.localtime())
hour = dt[3]
minute = dt[4]
if hour == 5 and minute == 45:
os.popen2("open /Users/jun/shout.mp3")
not_executed = 0


Happy Hacking! :)

Create Games the Easy Way with Pygame

Thursday, March 13, 2008

Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. It is built over the Simple DirectMedia Layer (SDL) library, with the intention of allowing real-time computer game development without the restraints and low-level mechanics of the C programming language and its derivatives. This is based on the assumption that the most consuming functions inside games (mainly the graphics part) can be completely abstracted from the game logic in itself, making it probable to use a high-level programming language like Python to structure the game.

It is possible to write simple but decent games with just a few lines of code using the Pygame module. Anyone with a little programming knowledge can create like some of the games shown below:

Helicopters
Shoot the helicopters and the bombs they drop before they blow up your base!


Soccer
The game is a standard soccer with three players and a goal keeper. The players are named 1, 2 and 3. By using the number key on the keyboard you can switch/pass the ball to the player. The arrow keeps provide a mechanism to move the player around. The game runs for duration of 5 minutes. The goalkeepers are automatics and need not be controlled.


OilWorker
Oil Worker is an addictive and challenging arcade puzzle game developed in PyGame. You've been contracted by an oil company and your goal is to build a long pipe to carry the oil from the oil well to the refinery.


Pykanoid
Pykanoid is an Arkanoid clone game developed in Python/PyGame. It consist on a bouncing ball that player must control with a bat and try to destroy all blocks in the screen. It has powerups to enhance ball and bat.


Slipslide
Slipslide 2 is a simple puzzle game where the goal in each level is to get to the exit by sliding between obstacles. When you start moving in a certain direction, you can't stop or change direction until you hit an obstacle or a wall. And to add to the difficulty, some levels have holes in the ground which make you restart the level if you fall into them. There will be twenty-five different levels, all linked by a story that sees the main character trying to get to an ice-dancing competition in Antarctica.


Fishie Fishie
Fishie Fishie is a kaliedscope of high speed sea food, featuring a challenging one button fish control system, lovingly hand illustrated fish, fish related poetry, and fish.



Visit
Pygame.org for more info, to download and to see the documentation. There, you will also find tutorials and list of projects that make use of Pygame.
***

Extracting HTML Documents from Web Pages Using Python

Thursday, November 22, 2007

Question: Can you extract an HTML document from a live web page without even using an internet browser?
Answer: Yes you can. All you need is a Python interpreter and these short commands:

>>> import urllib
>>> sock = urllib.urlopen("PAGE URL")
>>> htmlSource = sock.read()
>>> sock.close()
>>> print htmlSource

Illustration (click to enlarge):


Python Related Posts:
* Will Real Python Hackers Please Stand Up
* How to Rescue Windows Files Using Linux and Python
* Highly Recommended Books on Python

Highly Recommended Books on Python

Monday, November 12, 2007

Here is my own list of highly recommended Python
programming books, classified according
to user’s experience level.




Beginner
:


Learning Python
By: Mark Lutz

With this hands-on book, you can master the fundamentals of the core Python language quickly and efficiently, whether you're new to programming or just new to Python. Once you finish, you will know enough about the language to use it in any application domain you choose. Learning Python is based on material from author Mark Lutz's popular training courses, which he's taught over the past decade. Each chapter is a self-contained lesson that helps you thoroughly understand a key component of Python before you continue. Along with plenty of annotated examples, illustrations, and chapter summaries, every chapter also contains Brain Builder, a unique section with practical exercises and review quizzes that let you practice new skills and test your understanding as you go.


Python For Dummies
By: Stef Maruch, Aahz Maruch

Python For Dummies is the quick-and-easy guide to getting the most out of this robust program. This hands-on book will show you everything you need to know about building programs, debugging code, and simplifying development, as well as defining what actions it can perform. You’ll wrap yourself around all of its advanced features and become an expert Python user in no time.


Python
By: Chris Fehily

The quick and easy way to master Python for Internet and Intranet programming-- Visual, step-by-step guide to the popular Python programming language-- Cross -platform coverage for the Mac, Windows, and Unix environments-- Teaches techniques for cookies, session management, and integration with XML. Visual QuickStart Guide helps readers master the language with simple steps, screen shots, and clear explanations. With the foundation laid, the book brings the Python language to real-world usage in Web development and is suitable for beginning to intermediate users who want to join the Python revolution.



Intermediate:

Python Cookbook
By: Alex Martelli, David Ascher

The Python Cookbook is a collection of problems, solutions, and practical examples for Python programmers, written by Python programmers. Over the past year, members of the Python community have contributed material to an online repository of Python recipes hosted by ActiveState. This book contains the best of those recipes, accompanied by overviews and background material by key Python figures. The recipes highlight Python best practices and can be used directly in day-to-day programming tasks, as a source of ideas, or as a way to learn more about Python. The book contains a foreword by Guido van Rossum, the creator of Python.


Programming Python
By: Mark Lutz

Whether you're a novice or an advanced practitioner, you'll find this refreshed book more than lives up to its reputation. Programming Python, 3rd Edition, teaches you the right way to code. It explains Python language syntax and programming techniques in a clear and concise manner, with numerous examples that illustrate both correct usage and common idioms. By reading this comprehensive guide, you'll learn how to apply Python in real-world problem domains such as: GUI programming Internet scripting Parallel processing Database management Networked applications Programming Python. Along the way, you'll also learn how to use the Python language in realistically scaled programs--concepts such as Object-Oriented Programming (OOP) and code reuse are recurring side themes throughout this text. If you're interested in Python programming, then this O'Reilly classic needs to be within arm's reach.


Beginning Python: From Novice to Professional
By: Magnus Lie Hetland

Beginning Python: From Novice to Professional is the most comprehensive book on the Python ever written. Based on Practical Python, this newly revised book is both an introduction and practical reference for a swath of Python-related programming topics, including addressing language internals, database integration, network programming, and web services. Advanced topics, such as extending Python and packaging/distributing Python applications, are also covered.



Advanced:

Dive Into Python
By: Mark Pilgrim

Whether you're an experienced programmer looking to get into Python or grizzled Python veteran who remembers the days when you had to import the string module, "Dive Into Python" is your 'desert island'. "Dive Into Python" is a hands-on guide to the Python language. Each chapter starts with a real, complete code sample, proceeds to pick it apart and explain the pieces, and then puts it all back together in a summary at the end. This is the perfect resource for you if you like to jump into languages fast and get going right away.


Python in a Nutshell
By: Alex Martelli

Ask any Python aficionado and you'll hear that Python programmers have it all: an elegant language that offers object-oriented programming support, a readable, maintainable syntax, integration with C components, and an enormous collection of precoded standard library and extension modules. Moreover, Python is easy to learn but powerful enough to take on the most ambitious programming challenges. But what Python programmers have lacked is one concise and clear reference resource, with the appropriate measure of guidance in how best to use Python's great power. Now Python in a Nutshell fills this need. Python in a Nutshell provides a solid, no-nonsense quick reference to information that programmers rely on the most. This latest addition to the best-selling "In a Nutshell" series will immediately earn its place in any Python programmer's library.


Python Essential Reference
By: David M. Beazley

Python Essential Reference, 3rd Edition, is a comprehensive reference to the Python programming language. The focus of& nbsp; this latest& nbsp; edition is to add coverage of significant new features and new library modules added to the language over the past five years.& nbsp; Clearly written with concise organization, & nbsp; the new& nbsp; features covered& nbsp; include new style classes, unification of types and classes, xmlrpclip, intertools, bz2 and optparse, making it the most up-to-date Python book on the market.


If there are other good and helpful Python programming books that you know but were not included here, feel free to drop me a comment.

How to Rescue Windows Files Using Linux and Python

Saturday, October 20, 2007

Problem: Windows Operating System is broken, must be a virus or something; need to rescue important files immediately.











Solution
: A Linux Live CD with Python pre-installed; an external storage device; this Python script:

#!/usr/bin/python
# Filename: backup.py
import os, time

source = ['DIRECTORY OF WINDOWS FILES TO BE BACKED-UP!’]
target_dir = 'LOCATION OF EXTERNAL STORAGE DEVICE!'
today = target_dir + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = raw_input('Enter a comment --> ')
if len(comment) == 0:
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip'
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))

if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'

Will Real Python Hackers Please Stand Up

Thursday, August 30, 2007

Filipino python hackers and enthusiasts, may I have your attention please. A few months ago, I emailed Guido van Rossum , Python’s author and BDFL( Benevolent Dictator For Life), asking him for some advice on organizing a PUG( Python User Group) here in the Philippines. To my surprise, I got a quick reply from him with some instructions on how to get it started. But time did not allow me to take some actions immediately until now.

I realize that this blog could help spread my desire in starting a PUG with the help of course from those who are interested and passionate of the Python Programming Language. The benefits of having a user group is plenty just like the importance of having Linux User Groups as most of you might know or even involved with. We can gain more knowledge from each other as none of us is as smart as all of us. We can also provide some technical help to those who are just beginning to learn the language as a great way of helping the open source community.

To those who are interested, you can leave a comment here and we can keep in touch later.

I will end this post with a quote from a bestselling author named Stephen Covey. He said,

“Synergy is the highest activity of life; it creates new untapped alternatives; it values and exploits the mental, emotional, and psychological differences between people.”

Think about it.

UPDATE: Pinoy Python User Group -- Pinoy PUG