Sunday, 23 December 2012

Bouncy Text and Christmas Trees

First a quick video of the demo!

Code is available here.

The code runs much smoother than on YouTube :-) Hopefully each post in future will come with a video. The defaults are for the demo to run at 320 by 240 but you can adjust these values via the WinWidth and WinHeight Variables.

So how do we make the text bounce like this? Well, do you remember the Sin wave from trigonometry? Watch the 'M' in the video climb up to the top, back to the middle and then the bottom of the window and back up. We use a little bit of math to store the coordinates of this path in a list and each time we draw the window we move onto the next set of coordinates thus moving the text along the path. When it's gone through the list it goes back to the start so our animation loops.

The background Christmas trees dimensions are worked out and stored in treewidth and treeheight. We then have a couple of loops so we have 4 columns of trees over 3 rows. To liven things up the c3B data item adjust the shade of green. Can you figure out how to add more (smaller) trees to the scene?

The rest of the program covers the usual plumbing. An update function moves the text to the next set of coordinates in the list and it is called on a schedule. There is the on_draw handler for the window that actually takes care of the drawing.

One last point to mention is that we want the text to appear in front of the trees. Pyglet has the concept of groups. Have a look at the objects foreground and background. By setting up our objects in the right group we can ensure Pyglet draws them in the desired order.

Hope to return with something 3D next time around. Happy Python/Pyglet-ing!!

Thursday, 20 December 2012

Simple Starfield in PyGlet

How about more stars?

Whilst stuck in bed unwell, I stumbled upon a fun video tutorial on how to write an asteroid game in pyglet. Pyglet is available for Python 2 and 3 (in alpha form) and provides a pure Python wrapper to OpenGL. Whilst not been as extensive a library as say PyGame, it does offer some interesting capabilities such as sprite rotation and scaling plus a route into the OpenGL world. The example code was very clean and readable. I do miss the lack of built in primitives but you can get round that.

I thought it would be fun to revisit the star field program and convert it to pyglet. At first I was disappointed with the speed. Cutting down the number of stars worked but what made a real difference was drawing each layer as a single batch/OpenGL command. That put things back at warp speed with the regular numbers!

I highly recommend the asteroid tutorial video. My Starfield demo code is available here.

Thursday, 18 October 2012

PyWeek 15 PostMortem

Now that some time has passed, I thought it would be good to look back at PyWeek 15 to review how it went. First a screenshot!

I quite liked the look of this game with the bright colours and use of shades. I liked the generate landscape. Disappointed that there is not much to do except zap without a goal. Some systems seem to be unable to cope with the game and get next to no keyboard response making it unplayable :-( Definitely felt unfinished but I had a horrible cold that week so I simply ran out of energy some nights.

So lessons learned...

  • It was fun to do new stuff!
  • Even a simple sound effect can add to a game!
  • Test on a range of systems regularly - watch that CPU usage.
  • Allow time for review and correction.
  • Have a clear idea - this one suffered from 'just keeping busy'.
  • Players like smooth movement.
  • Players like to be in the center of the screen.
  • A few warm up projects certainly help.

Here's to next time!

Wednesday, 29 August 2012

Make Cool Game Menus with SGC

SGC (Simple Game Code) is a new project that describes itself as 'A GUI toolkit for PyGame, to ease game development for Pygame developers'. The idea being that it takes care of menus, checkboxes, inputs etc so you can get on with the game itself. I have been following this project on the PyGame mailing list and had the idea to create a skeleton 'game' to try out the menus. They look great and even have nice transitions! So we have a simple functional menu with an options screen with one option. Start the game with the option on/off for a different number of bad guys (boxes in this case). Press q to quit the game screen. Will definitely be using this for PyWeek!
Code is available from the DaftPython Google Code Project. The menu is loaded from the dmenu file so you need that as well as the .py python file.


Monday, 20 August 2012

Returning To The Stars

My previous post with a simple starfield has proved to be one of the most popular posts on this blog so far. I thought it was high time I gave the 'solution' to the challenge of a 'layered' version.

Having several starfields on top of each other running at different speeds in order to give the idea of depth. This required no changes to the starfield code (though I did tweak it not to use tuples anymore - more to avoid confusion). A screenshot doesn't do it justice - run the demo to see the movement!



All examples from this blog will appear on the new DaftPython Google Code site. The latest star code is here.

Friday, 10 August 2012

Screenshot Viewer For Minecraft - Now Released

The screenshot viewer is now available! Only tested on Windows for now so Linux/Mac users (who make a good proportion of visitors to this site) be warned. I have created a Google code project for all the code on this blog at http://code.google.com/p/daftpython/ 

You can get the latest Screenshot viewer here. It is a single .PY file tested on Python 2.6.6 and wxPython 2.8. We have been trying out a CXFreeze version with a Windows Installer and it is looking good. I'd like to look at maintaining aspect ratio for the thumbnails and display.

If you run it on a non-Windows platform I would appreciate a screenshot. Any other thoughts, please leave a comment!


Tuesday, 7 August 2012

Minecraft Screenshot Viewer in wxPython - A Preview

There's a lot of Minecraft going on in this house! The boys all love it and come up with some creative designs for houses, statues, machines and roller-coasters. Minecraft has a built in feature for taking screenshots 'F2' and I encourage them to do this if they have made something. Eventually we will make a slideshow video of them.

But there is no easy way to view the screenshots in the game and it is a bit 'hidden' under .minecraft so what a great excuse for a wxPython program. Not quite ready for the prime-time (needs Linux tested at least) but my eldest was impressed by the demo of it and is keen to get it installed on the main family PC.

Here's a screenshot until I get some SVN sorted out:


Ideas for features welcome - leave a comment!

Friday, 27 July 2012

Simple Starfield In PyGame

Games are very often highly interactive with even some text adventures operating in real time. I thought it would be fun to go in the opposite direction and create a game with minimal interaction. So I settled on an outer space theme and had a text experiment of a probe travelling through the emptiness of space.

The next step was to create a graphical display and, of course, stars were the first order of business! I looked around at a few star field examples and ended up coding one for myself. Straightforward 2D scrolling is all I want - needs to be calm for the display. The class is nice and simple whilst the demo shows it off fairly well.

Exercise for the reader - can you make a layered demo? I'll share the code on a follow up post. Happy stargazing!




import random
import pygame
import sys
from pygame.locals import *

class starfield(object):
    def __init__(self, pos , size, max, speed):
        self.stars = []
        self.pos = pos
        self.size = size
        self.max = max
        self.speed = speed
        self.box = True
        self.color = (255,255,255)
        self.bordercolor = Color(255,255,255)
        self.backgroundcolor = Color(0,0,0)
        for loop in range(0, max):
            star = [random.randrange(0, size[0] - 1),
                    random.randrange(0, size[1] - 1)]
            self.stars.append(star);
    def draw(self, screen):
        if self.box:
             pygame.draw.rect(screen, self.backgroundcolor, Rect(self.pos[0], self.pos[1], self.size[0],self.size[1]), 0)
             pygame.draw.rect(screen, self.bordercolor, Rect(self.pos[0], self.pos[1], self.size[0],self.size[1]), 1)
        for loop in range(0, self.max):
            p = (self.pos[0] + self.stars[loop][0], self.pos[1] + self.stars[loop][1] )
            screen.set_at(p, self.color)
    def update(self):
        for loop in range(0, self.max):
            self.stars[loop] = (self.stars[loop][0] + self.speed, self.stars[loop][1])
            if self.stars[loop][0]>self.size[0]:
                self.stars[loop] = (0, self.stars[loop][1])

# DEMO
sf = [starfield( (50,50), (550,410), 80, 1 ),
      starfield( (80,150), (200,200), 33, 2 ),
      starfield( (380,150), (200,200), 33, 3 ),
      starfield( (5,5), (80,80), 12, 4 )
      ]

sf[1].color = (255,0,0)
sf[2].color = (0,255,0)
sf[3].color = (0,0,255)


TIMEREVENT = pygame.USEREVENT
UPDATEEVENT = pygame.USEREVENT+1
FPS = 50
pygame.init()
window = pygame.display.set_mode((640, 480))

background = None
background = pygame.Surface(window.get_size())
background.fill((0, 0, 0))

pygame.time.set_timer(TIMEREVENT, int(1000 / FPS))
pygame.time.set_timer(UPDATEEVENT, 50)

while True:

    for event in pygame.event.get():
        if event.type == TIMEREVENT:
            background.fill((0,0,0))
            for s in sf:
                s.draw(background)
            window.blit(background, (0, 0))
            pygame.display.flip()
        elif event.type == UPDATEEVENT:
            for s in sf:
                s.update()
            # Move starfield
            x = sf[3].pos[0] + 2
            y = sf[3].pos[1] + 2
            if x>640: x=-50
            if y>480: y=-40
            sf[3].pos = (x,y)

        elif event.type == pygame.QUIT:
            sys.exit()

Thursday, 12 July 2012

Particles Of Blue

Something I have not used in a PyGame game yet is particles of any sort. Thinking over a few ideas for a mining game, it seemed like a fun idea to have some sort of soil. This lead to a quick half-hour of coding and here is the result:


It is not terribly efficient or a good colour for soil but has potential.

Here's the code:
import pygame
import sys
import random

from pygame.event import *
from pygame.locals import *

TIMEREVENT = pygame.USEREVENT
FPS = 50
pygame.init()
window = pygame.display.set_mode((640, 480))
background = None
background = pygame.Surface(window.get_size())
background.fill((0, 0, 0))
pygame.time.set_timer(TIMEREVENT, int(1000 / FPS))
colour3 = Color(0, 0, 255)
ground = Color(0, 255, 0)
y = 100

def DrawText(bg, x, y, text, size=24, color=(255, 255, 255)):
    inst1_font = pygame.font.Font(None, size)
    inst1_surf = inst1_font.render(text, 1, color)
    bg.blit(inst1_surf, [x, y])

class grit(object):
    def __init__(self):
        self.x = random.randint(0,639)
        self.y = random.randint(0,125) - 50
        self.width = random.randint(1, 6)
        self.height = random.randint(1, 6)
        self.color = Color(0, 0, random.randint(119,255))
        self.active = True

def init():
    gritsL = 1000
    agrits = []
    while len(agrits)<gritsL:
        agrits.append(grit())
    return agrits

grits = init()

while True:

    for event in pygame.event.get():
        if event.type == TIMEREVENT:
            background.fill(pygame.Color("black"))
            DrawText(background, 25, 120, "Daftspaniel",126)
            pygame.draw.rect(background, ground, Rect(0, 450, 640,280), 0)
            pygame.draw.rect(background, ground, Rect(300, 250, 340,180), 0)

            for g in grits:
                pygame.draw.rect(background, g.color, Rect(g.x, g.y, g.width, g.height), 0)
                if g.active:
                    if g.y>-1 and g.y<(480-g.height):
                        c = background.get_at((g.x, g.y+g.height));
                        if c.r==0 and c.g==0:
                            g.y = g.y + 5
                        else:
                            g.active = False
                    if g.y<0:
                        g.y = g.y + 5
            window.blit(background, (0, 0))
            pygame.display.flip()
        elif event.type == pygame.KEYDOWN:
            keystate = pygame.key.get_pressed()
            if not keystate[K_w]==1:
                grits = init()
        elif event.type == pygame.QUIT:
            sys.exit()

Any suggested improvements? I would like to use this for a treaure hunt game. Two players digging for gold. Soil lumps might have to be bigger for a game.

Sunday, 8 July 2012

Python Tools For Visual Studio

Day to day I use Visual Studio for ASP.net and CSharp. It is okay-ish. I used to like Visual Studio then around version 6/7 it went rather multipurpose/multilanguage and lessened the experience. Nowadays it needs a lot of horsepower and big expensive plugins like Resharper to keep up. 

I have kept the monster of Visual Studio off my ageing Vista era laptop for some time. Sharp Develop is an FOSS IDE that fills that gap nicely. Microsoft do offer Express versions which are good but they are rather frustrating if you have used the full versions!


Anyway Microsoft also produce Python Tools for Visual Studio which can be run on top of the free Visual Studio Shell. PTVS is also free and open source. It supports various versions of Python - not just IronPython (I am currently using it for PyGame with CPython 2.6.6). The code completion is pretty good and, surprisingly, it is not too resource demanding on my ol' Dell Inspiron 1501! It has a long list of features including refactoring, debugging, Django, REPL. Also comes with some extras for Excel and the Xbox Kinect.

I jump around editors quite a lot but I think will hang around PTVS for a good while.

Friday, 6 July 2012

The Future Of PyGame

pgreloaded - PyGame Reloaded - Multimedia Framework for Python - Google Project Hosting: "Pygame Reloaded (aka pygame2, pgreloaded) started as a rewrite of the Pygame multimedia and game framework. As of 2012, the development focuses on providing a ctypes-based wrapper around SDL 2.0, along with a rich feature set for creating multimedia applications, games and graphics-based application prototypes." PyGame is built on SDL which has been a long lasting library. SDL has moved though and PyGame inevitably lags. A project exists to 'reboot' PyGame and move onto a newer SDL called Pgreloaded. As it is a Ctypes based wrapper and will allow for the library to run on other Python implementations such as IronPython. There is loss of compatibility with existing PyGame code. A lot of books will need to be rewritten I think! However the benefits of the Reload look promising. PyGame has a good future ahead of it so I am glad to be getting back into it at this time.

Saturday, 30 June 2012

Rediscovering Python and PyGame


After quite a long break, I find myself back into Python - specifically for PyGame projects. The day job is .Net centred and I've been dabbling in 6809 assembler, Android and HTML5 for personal development. I have been trying a few new technologies for various GFX programs but few have come close to the RAD, features and fun of Python with PyGame.

I have had some fun with HTML5 especially with the canvas - sadly the drawing primitives are not all there yet. Hate how slow HTML progresses so not holding my breath for a better canvas for a long time. True Python doesn't run in the browser but it is cross platform, free and fairly easy to install (more on that later).

PyWeek

Taking part in PyWeek again was a challenge but great fun and I came up with a game that met a good few of my goals:


I have received some great feedback this time around. There are many required game play tweaks (an area I sadly did not have time for during the competition). Better mapping, goal feedback and more interesting terrain. 

Lessons Learned in no particular order:
  • Not having sound is something people WILL notice.
  • The motto 'Keep it simple and complete' is an excellent strategy.
  • Even small animation and movement pay off. The feel of the game is improved so much.
  • Keeping classes small helps - never a problem that a bit of code was too small.
  • Don't leave all on screen controls until the end!
  • Write the User instructions and revisit them at the end.
  • Getting the IDE, libraries, tools etc chosen and installed in advance allows for a quicker start. Should maybe include packaging, installer for next time.
  • Some bits and pieces of Python (3) I did not know yet.
  • Small custom tools can save lots of time.


Would I do another one? Yes. Always fun and educational. I have tweaked the game a little since release but I feel I would get more from trying something different rather than writing a sequel! It was designed to be ported to HTML5 so next time I want to do something in the browser realm...

Versioning

One thing that came up during the judging of the PyWeek entry was the problems of versions. Not just an issue for the competition - I was only able to feedback on half the games I could have after wrestling with various versions of libraries and non-standard module set up. In the .Net world NuGet is rather good. Hopefully Python 4 will include a single common way to set up extra libraries on all systems.


Future


Currently working on a 2 player Cowboy game with input from my eldest son. Blog post on that one soon :-) Think it will be called '8bit Cowboy Goldrush'. Yee-ha!

Sunday, 24 June 2012

Reclaiming DaftPython!

Right trying to reclaim the DaftPython name on blogger. Sorry for this test post cluttering up your feed. Future posts will probably be full of PyGame related posts. See you soon!