XNA Example with a Bouncing Sprite

Taken from this forum post.

This is a 'sprite bouncing' example, using the XNA Game Development Framework. You will need to install the XNA Framework Redistributable, as well as the DirectX End-User Runtimes.

XNA is a framework for writing games on the PC and the XBox 360. Because the XBox uses the Compact Edition of .NET, it doesn't yet support IronPython - although hopefully this will change.

The example also requires the following image, as 'sprite.jpg' in the directory from which it is run:



When running, it looks like this (except bigger and moving):



Although this example doesn't crash when using Python.NET, it doesn't really work either (you just see a screen full of static).

import clr clr.AddReference('Microsoft.Xna.Framework') clr.AddReference('Microsoft.Xna.Framework.Game')

from Microsoft.Xna.Framework import * from Microsoft.Xna.Framework.Graphics import * from Microsoft.Xna.Framework.Content import *

class MyGame(Game): def __init__(self): self.spriteX = self.spriteY = 0 self.spriteSpeedX = self.spriteSpeedY = 1 self.initializeComponent

def initializeComponent(self): self.graphics = GraphicsDeviceManager(self) self.content = ContentManager(self.Services)

def LoadGraphicsContent(self, loadAllContent): if loadAllContent: self.texture = Texture2D.FromFile(self.graphics.GraphicsDevice, "sprite.jpg") self.spriteBatch = SpriteBatch(self.graphics.GraphicsDevice) def UnloadGraphicsContent(self, unloadAllContent): if unloadAllContent: self.texture.Dispose self.spritebatch.Dispose

def Update(self, gameTime): self.UpdateSprite Game.Update(self, gameTime)

def UpdateSprite(self): self.spriteX += self.spriteSpeedX self.spriteY += self.spriteSpeedY

maxX = self.graphics.GraphicsDevice.Viewport.Width - self.texture.Width if self.spriteX > maxX: self.spriteSpeedX *= -1 self.spriteX = maxX elif self.spriteX < 0: self.spriteSpeedX *= -1 self.spriteX = 0

maxY = self.graphics.GraphicsDevice.Viewport.Height - self.texture.Height if self.spriteY > maxY: self.spriteSpeedY *= -1 self.spriteX = maxY elif self.spriteY < 0: self.spriteSpeedY *= -1 self.spriteY = 0

def Draw(self, gameTime): self.graphics.GraphicsDevice.Clear(Color.CornflowerBlue) self.DrawSprite Game.Draw(self, gameTime) def DrawSprite(self): self.spriteBatch.Begin self.spriteBatch.Draw(self.texture, Rectangle(self.spriteX, self.spriteY, self.texture.Width, self.texture.Height), Color.White) self.spriteBatch.End

game = MyGame game.Run

Back to Contents.