[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] people hating python for game dev.



Warning: pretty off-topic, for Pygame anyway...

I have written a CPU emulator, complete with compiler etc... it's in C, but the concepts are still the same in any language (I can post the source, if you really want).

The solution I used was this:

The first byte of the instruction defined the instruction opcode (so thats 256 different instruction/opcode variations). Then I defined a table of 256 pointers to functions, each function being an implementation of the instruction+opcode combo. In python, you'd probably have something like this:

# define a function like this:
def my_add_instruction(self,cpu_pc)
  return(cpu_pc[0]+cpu_pc[1])

functions=[]
functions.append(my_add_instruction)
# do this for all opcodes...

# code to find function is something like:
return(functions[opcode_value](cpu_pc))

Well, I hope that makes sense.Essentially use a look-up table of functions rather than a vast if..elif..elif..else loop.

On 5/17/06, Luke Paireepinart <rabidpoobear@xxxxxxxxx> wrote:
Chris Ashurst wrote:
> Sure thing.
>
> http://www.telestatic.net/python/cpu/
>
> It's a tad untidy, and I shoved some of my own stuff in there, but it's got
> the comments from the original author liberally sprinkled throughout.
Ah, not to say anything negative about your code,
since the number of opcodes is small,
the whole "if -elif" branch (which in a C++ emu would probably be a switch)
is okay because it's concise.
However, in a larger subset of opcodes,
it starts too look ugly and hard to manage.
I know there's a more elegant approach to this,
and I've thought about it a lot.
You have any ideas on this?
the reason I ask is because I'm writing a
CPU emulator that has ~57 opcodes
and 13 addressing modes and
I really don't want a giant if-elif branch.
I don't care if there's a slight speed hit
by making them classes or functions or something.
My goal is to make the code understandable
and pretty, not fast.  I can make it fast later
if I need to.  I'm not going to try to write optimized code
off the bat.
So if you have any idea on how to implement the opcodes
in a less-switchy way, I'd appreciate the input.
Thanks.
-Luke



--
Science is open source religion