Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 10 May 2005
Offline Last Active Dec 20 2013 10:05 AM

Topics I've Started

Elegant way to do this in Python?

23 June 2011 - 07:01 AM

I'm working on a project where we have a lot of existing code which checks some readings from sensors and other parts of the code and acts accordingly, all in Python. Much of it is like a state machine and it currently goes to the next state after a single 'frame' of data matching some criterion. This works fine *most* of the time, but if we get a single bad frame, it can throw the system into another state which is highly undesirable. I'm trying to make a generic means of checking for consistency over time. Here's what I've got so far: a class which checks if 3 of the last 5 values have been 'good'.

[source lang="python"]class ConsistencyCheck: def __init__(self, count=3, total=5): self.count = 3 self.total = 5 self.values = [] def check(self, value): self.values.append(value) if len(self.values) > self.total: self.values[:] = self.values[-self.total:] if len( filter(lambda x: x == True, self.values) ) > self.count: return True else: return Fals[/source]

This is fine, but I'd like a less cumbersome means of using this. To change an existing condition to use this, I need to make a member variable of the class which uses the condition, then put self.some_checker.check() around the predicate. It's OK, but I'd prefer if I could just wrap the predicate directly in a consistency checker. For example:

[source lang="python"]## This:if ConsistencyCheck( distance < close_threshold ): change_state()## Instead of:self.close_checker = ConsistencyCheck()# Some time later....if self.close_checker.check( distance < close_threshold ): change_state()[/source]

This is ideal because it consolidates the changes, doesn't require a member variable for every status check and lets us specify the configuration of the predicate (ie. count and total values) at the same place that it is used, not back at initialization. However, I can't think of any way to do this. Is anyone's Python magic stronger than mine?

So I wrote a Lisp

10 July 2010 - 09:22 AM

ApochPiQ suggested in a thread on practicing recursion writing a simple Lisp dialect interpreter. I took that suggestion. With an almost shockingly small amount of Python code, I have a working Lisp interpreter. So far, I've avoided the harder parts - call/cc and macros, specifically. It's now reasonably functional, and I've had fun implementing some neat stuff, like the streams system from SICP.

I'm at a cross roads now with no obvious, essential next feature to implement. My current feeling with the project so-far is that while it's been neat, almost everything I've done has had a 1-to-1 mapping onto features of Python; closures, garbage collection, dynamic typing, etc. It's less like I'm implementing Lisp and more like I'm leaching Python's features into Lisps syntax. Here's what I'm thinking my options for the next step are:

1). Macros. This requires me learning, say, Scheme's macros, which wouldn't be a bad thing either. This sounds like an ambitious project, though.

2). call-with-current-continuation. I've thought a little about this, and have yet to come up with a reasonable way to achieve it, which I guess makes it a challenge.

3). Reimplementing it all. Writing it in another language would force me to "truly" implement the features of Lisp without just using those same features in another language. C++ wouldn't be bad, but the lack of a garbage collector makes the project into something quite large, and I'm not particularly interested in writing a GC. C# would be another option, but, again, it has most of the features of Lisp already (dynamic typing, however, would be gone). I've considered Haskell, too. I've put some time into learning Haskell, but have hardly written more than factorial programs in it, so this might give me something to expand into.

4). Modify to not use Python's obviously corresponding features. Though something feels wrong about simply overlooking a language feature just to be "more hardcore". I guess it's not far from just writing it in a lower-level language like C++. This just doesn't seem too exciting.

5). Lisp compiler to the .NET CIL? I've never done anything like this before (I hadn't done anything like writing an interpreter before, either!). Would this be a phenomenal amount of work? I assume it still would let me leach the .NET garbage collector, which I consider a good thing.

6). Going through "Lisp in Small Pieces" and doing it's projects. I guess I'd rather figure this all out on my own or through referring to language specification. (I've been using Scheme's R5RS. Any other suggestions?)

What do you all think a good next project would be? Am I overestimating the difficultly of a domain-specific GC implementation? I'm interested in investing several weeks to a couple months to get something fairly concrete. I've really enjoyed the interpreter project thus-far and want to continue. I'm not interested in making this a truly useful language or project; there's already more than enough Lisp dialects out there. So speed concerns, library support, and all those actually useful things can be essentially ignored.

And my thanks to ApochPiQ for the original suggestion!

Controller latency

07 January 2010 - 02:50 AM

This is a decent article trying to quantify a not-uncommon problem with video games; unresponsive or laggy controls. I like that this issue is being examined and measured and I hope that game companies will try to measure this before releasing their games in the future. However, the article made some claims I wasn't sure of. Namely, they state that 67ms is the minimum latency for a 60fps game, and 100ms for a 30fps game. For example, this basic game loop:
while running:
Reading the inputs happens immediately before drawing the frame. If the button was pressed immediately before handle_inputs polls for events (and ignoring inherent latency in hardware or operating system), the latency is only however long it takes to run handle_inputs() and draw_frame() (and for the monitor to refresh). There's no reason that would be 67ms! For a 60fps game, it would be at most 16.7ms. Even if the input was given shortly after handle_inputs polls for inputs, it still only takes the time of at most 2 handle_inputs(), two draw_frames() and a cap_framerate_to_60(), which will be at most 33ms. I'd be comfortable adding in another frame or maybe the two that the article gives based on latency from hardware and operating system, but I see no reason to give this 67ms as some hard minimum. A game with a quick update and draw functions (which is capped at 60fps by v-sync) could have almost immediate responses with less than a frame of latency, depending on when in the loop you pressed the button. So how do they come up with such set-in-stone numbers? Is there some justification for the additional 33ms of hardware and other latency inherent outside of the game or does that number just come from thin air? Or am I missing something in my analysis of the minimum latency? Furthermore, I find that subtracting out the response time of the screen is a little naive - the human mind still sees that as part of the latency and developers should be developing for what people are playing on, not some theoretical perfect monitor.

Flatland: The Video Game

05 January 2010 - 06:46 AM

What if a video game took place in Flatland? It is not the Victorian era social commentary of Flatland that resonates as a game play mechanic but the introduction of higher dimensions to a previously "flat" 2D world. A Square, with the help of his friend the sphere, would have exactly the kind of powers that make up a gimmicky platformer or puzzle game, not to mention some potential educational value. So embrace the gimmick and brainstorm what game play this could open up! The primary challenge I see is that the powers of having extra-dimensional aid are too great. The sphere could lift our friend the Square up out of Flatland and place him back down at his destination, avoiding all platformer-style obstacles in the way. Most standard puzzles would be easily avoided this way, too; any locked door can be gotten around, any blocks rearranged, any button pressed, etc. In short, there must be some way to restrict sphere's powers. But restrictions on Sphere's powers would be hard to come by if they are only in Flatland. We could make Sphereland restrictions that, too, block Sphere. A 3D box with the goal inside, could intersect Flatland and act as a barrier to both Square and Sphere. But this weakens the Flatland setting of the game; the only true obstacles are the ones that exist in Spaceland! The obstacles have to interact interestingly with both Spaceland and Flatland, otherwise we are squandering the gimmick. For this, we might be saved by some abilities that Square has that Sphere cannot. For example, our 3D box in Spaceland intersecting Flatland might have an infinitely thin slit (conveniently in the same place as Flatland!) through which Square could fit comfortably but which would shame poor Sphere. But I have yet to think of any interesting puzzles or game play that could be worked out with this scheme. Does anyone else have thoughts? Some other ideas:
  • Sphere can flip 2D things over, making them their mirror image. This is otherwise impossible in Flatland.
  • Some restrictions originating in Flatland may still pose a challenge in Spaceland: a rope between two blocks can still connect the two in three dimensions.
  • There is the possible mechanic of being able to move Flatland through Spaceland. As the plane of Flatland intersects different parts of Spaceland objects, they might grow, shrink, suddenly change, or even disappear abruptly. Objects in Flatland could still block the movement of Flatland; a Flatland object inside an enclosed 3D box still would stop all of flatland from moving (so long as the 3D box is fixed).
  • This idea can, of course, be extended to higher (or lower, I suppose) dimensions as the Edwin Abbott would encourage us to do. However, I think that the possibilities of Spaceland being aided by Hyperspaceland shouldn't be considered too deeply until the Flatland-Spaceland relationship is fleshed out, game play wise.
  • Flatland need not be entirely "flat"! It could be Sphereland, for instance, where our (non-Euclidean) Square is restricted to the surface of a sphere. Or Rubberland (as one might call it), which can be stretched and distorted easily in three dimensions. Or Torusland where such well-known characters as Pacman reside.

Why is this unforgivably slow?

01 July 2009 - 11:26 PM

I had the itch to write some fast code yesterday - speed is something I generally don't consider and don't need to consider, but it sounded kinda fun and certainly educational to learn how to profile and optimize code. Well, so I booted up the ol' Visual C++ 2008 and started a new project using SDL. Soon as I have a screen up and rendering, I notice how incredibly slow it is. With only an event poll and a screen buffer flip, I am getting 34 fps at 800x600 resolution. I got on the IRC chat and got a lot of suggestions, none of which went anywhere: I tried SDL_HWSURFACE, SDL_SWSURFACE, SDL_DOUBLEBUF, not SDL_DOUBLEBUF, and plenty of combinations thereof. The only thing that changed the FPS noticeably was changing the screen resolution. At 640x480, I got 52fps, at 200x200 I get 230 to 250fps. I'm running in Release mode with optimizations (/O2) turned on. So how can my blank screen be so incredibly slow? I checked some of my older programs I had written years ago in DevC++ with SDL - they got 90-100fps and ~130fps at 640x480 with some actual rendering going on. What's could the difference be? Here's the (supremely simple) code:
#include "SDL.h"
#include <stdlib.h>

int main(int argc, char **args)
	SDL_Surface *screen;
	int running = 1;
	int i;
	Uint32 startTime;
	int frameCount = 0;
	FILE* logFile;
	logFile = fopen("log.txt", "w");

	if( SDL_Init(SDL_INIT_VIDEO) < 0 )
		fprintf(stderr, "Error initializing SDL: %s\n", SDL_GetError());

	screen = SDL_SetVideoMode(800,600, 32, SDL_HWSURFACE);
	if( screen == NULL )
		fprintf(stderr, "Error initializing the screen: %s\n", SDL_GetError());
	SDL_WM_SetCaption("Particles", NULL);

	startTime = SDL_GetTicks();
	while( running==1 )
		SDL_Event event;
			switch(event.type) {
				case SDL_QUIT:
					running = 0;
				case SDL_KEYDOWN:
					running = 0;

		SDL_UpdateRect(screen, 0,0,0,0);

	fprintf(logFile,"Average FPS: %f\n", 1000.0f * (float)frameCount / (SDL_GetTicks() - startTime));

	return 0;
I also tried out CodeAnalyst and attempted to profile my program. Turns out that about 90% of my program's execution time is spent in a single assembly instruction: rep movsd es:[edi],ds[esi] in nv4_displ.dll. Does that mean anything?