Tuesday, May 27, 2008

Magic Numbers

It is a good practice not to hardcode numbers into your code, like “if x < 24”. In this case, “24” is a magic number and should be replaced with a variable name like “page_length.” While magic numbers are generally considered bad, programmers still use them from time to time.

I am slowly working on MTG Forge version 2.0 and I was trying to make the cards stay in their zone, i.e. making sure you can’t move a card from your hand into play and thus confusing yourself. Version 2.0 is still very alpha and only lets you move a few cards around the screen.

Right now I divide up the screen into three areas, your hand, your in-play area, and the computer’s in-play area. Logically you shouldn’t be able to move a card from your hand to your in-play area.

I am using Python and PyGame. PyGame is a graphical library which will let me draw the cards on the screen much like Shandalar. In PyGame every sprite has a rectangle object that has properties that can be changed. PyGame uses this rectangle to know the sprite’s location, its x y coordinates, and its size. To move a sprite you just changes the rectangle’s x and y, sprite.rect.center = [200,200].

The code below uses magic numbers and keeps the card sprite from moving out of its zone. Only the y coordinate is checked since the zones extend all the way across the screen. It’s been awhile since I’ve used simple x y geometry but thankfully nothing has been too hard.

#rect is short for rectangle
def keepCardInZone(self, card, originalX, originalY):
if originalY < 250:
if card.rect.bottom > 250:
card.rect.bottom = 250

elif originalY < 550:
if card.rect.top < 250:
card.rect.top = 250

if card.rect.bottom > 550:
card.rect.bottom = 550 + 1

else:
if card.rect.top < 550:
card.rect.top = 550

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.