programming

I guess you could say that my first taste of programming would have been in the attic at a friends house, where we played around creating a few BASIC programs. But that ain’t programming.

I really started when I picked up Mark Lutz’s awesome book Learning Python during the summer term of 2010. I’ve gotten a little bit better, bit by bit, and I’ve now set myself the task to program a fully functioning, albeit simple, game using Python and the Pygame SDL bindings. I plan to move onto more complicated lower level languages as my skills develop, but for now Python is a great learning tool.

Here are a few snippets of code I made a while ago. If (god forbid) you can find any use for them, then feel free. They’re in the public domain.

Here’s a bit of code for successive approximation, a process within audio-to-digital conversion:

#! /bin/python
"""
Successive approximation woo!

Essentially, for every bit of depth within the audio-to-digital conversion
process the script sets the bit to 1 if it's higher than the range's
mid-point or 0 if it's not before halving the range either upwards or
downwards depending on the result of the first process.

If run as the main program, 3 command line arguements set the following
parameters:
0: Voltage value we're measuring.
1: The total range of the voltage input.
2: The bit depth we want to use with our audio.

If no arguments or the incorrect number of arguements are given, it auto-
matically uses the values of 4.97, 10 and 16.

Paul Forey made this while bored in class, and he doesn't care what you
do with it.

http://runtime-audio.co.uk

"""

import sys # We need to import sys to get the command-line arguments.

def sucA(x, low, hi):
    """"
    Simply takes a value, the low point of the range and the high point
    of the range and outputs the resulting bit and the midpoint (for the
    other function to calculate the next range accordingly with).
    """
    midpoint = low + ((hi-low)/2.0)
    if x > midpoint:
        res = 1
    else:
        res = 0
    return res, midpoint

def proc(x, r=10, depth=16):
    """
    x is the voltage value we're converting. depth is the bit depth we're
    converting to, and r is the range the voltage can vary between, for
    instance 10 volts.
    """
    result = ''
    low = 0
    hi = r
    for i in range(depth):
        a, b = sucA(x, low, hi)
        if a: # if the bit is a 1
            low = b
        elif not a: # if the bit is a 0
            hi = b
        result += str(a)
    return result, b

if __name__ == '__main__':
    #Only does the following if this is the main script.
    try: res = proc(float(sys.argv[1]), float(sys.argv[2]), int(sys.argv[3]))
    except: res = proc(4.97, 10, 16)
    print(res)

And this old Processing code draws some super-fun-happy charactors which I was originally gonna use in my current project. I totally didn’t, although they still exist in the code (perhaps waiting).

void setup(){
  size(1024,480);
  background(0);
  noLoop();
}

void tri(float posX, float posY, float triWidth, float triHeight, boolean flip){
  float x1, x2, x3, y1, y2, y3;
  x1 = posX;
  x2 = posX + (triWidth/2);
  x3 = posX + triWidth;
  if (flip == true){
    y1 = posY - triHeight;
    y2 = posY;
    y3 = posY - triHeight;
  }
  else {
    y1 = posY;
    y2 = posY - triHeight;
    y3 = posY;
  }
  triangle(x1, y1, x2, y2, x3, y3);
}

void charactor(float posX, float posY, float charWidth, float charHeight, int emotion){ //emotions: 1 = aghast, 2 = sad, 3 = normal, 4 = cool, 5 = happiest
  float footHeight = charHeight/4;
  float truPosY = posY;
  posY = posY - footHeight;
  //main body
  fill (20, 155, 15);
  tri(posX, posY, charWidth, charHeight, false); //body
  tri(posX + (charWidth/6), truPosY, charWidth/4, footHeight, true); //left foot
  tri(posX + (charWidth/1.69), truPosY, charWidth/4, footHeight, true); //right foot
  boolean mouthFlip, eyeFlip;
  float mouthPosX, mouthPosY, mouthWidth, mouthHeight, leftEyePosX, rightEyePosX, eyePosY, eyeWidth, eyeHeight;
  if (emotion == 1 || emotion == 2){
    mouthFlip = false;
    mouthPosX = posX + (charWidth/4.5);
    mouthPosY = posY - (charHeight/16);
    mouthWidth = charWidth/1.8;
    mouthHeight = charHeight/3.5;
    leftEyePosX = posX + (charWidth/2.8);
    rightEyePosX = posX + (charWidth/2);
    eyeWidth = charWidth/6.5;
    eyeHeight = charHeight/6;
    if (emotion == 1){
      eyeFlip = false;
      eyePosY = posY - (charHeight/2);
    }
    else {
      eyeFlip = true;
      eyePosY = posY - (charHeight/2.5);
    }
  }
  else if (emotion == 3 || emotion == 4){
    mouthFlip = true;
    mouthPosX = posX + (charWidth/4);
    mouthPosY = posY - (charHeight/16);
    mouthWidth = charWidth/2;
    mouthHeight = charHeight/3.5;
    leftEyePosX = posX + (charWidth/2.8);
    rightEyePosX = posX + (charWidth/2);
    eyeWidth = charWidth/6.5;
    eyeHeight = charHeight/6;
    if (emotion == 3){
      eyeFlip = false;
      eyePosY = posY - (charHeight/2);
    }
    else {
      eyeFlip = true;
      eyePosY = posY - (charHeight/2.5);
    }
  }
  else{
    mouthFlip = true;
    eyeFlip = false;
    mouthPosX = posX + (charWidth/4.4);
    mouthPosY = posY - (charHeight/18);
    mouthWidth = charWidth/1.8;
    mouthHeight = charHeight/3;
    leftEyePosX = posX + (charWidth/3);
    rightEyePosX = posX + (charWidth/2);
    eyePosY = posY - (charHeight/2);
    eyeWidth = charWidth/5.5;
    eyeHeight = charHeight/4.5;
  }

  //face
  fill(0);
  tri(mouthPosX, mouthPosY, mouthWidth, mouthHeight, mouthFlip); //mouth
  tri(leftEyePosX, eyePosY, eyeWidth, eyeHeight, eyeFlip); //left eye
  tri(rightEyePosX, eyePosY, eyeWidth, eyeHeight, eyeFlip); //right eye
  //pupils
  fill(0,255,0);
  ellipse(posX + charWidth/2.4, posY - charHeight/1.9, 5, 5); //left pupil
  ellipse(posX + charWidth/1.75, posY - charHeight/1.9, 5, 5); //right pupil
}

void enemy(float posX, float posY, float charWidth, float charHeight){
  float footHeight = charHeight/4;
  float truPosY = posY;
  posY = posY - footHeight;
  //main body
  fill (20, 155, 150);
  tri(posX + (charWidth/6), truPosY, charWidth/4, footHeight + (charHeight/2), false); //left foot
  tri(posX + (charWidth/1.69), truPosY, charWidth/4, footHeight + (charHeight/2), false); //right foot
  tri(posX, posY, charWidth, charHeight, true); //body
  //face
  fill(0);
  tri(posX + (charWidth/4), posY - (charHeight/1.7), charWidth/5.5, charHeight/5, true); //left eye
  tri(posX + (charWidth/1.76), posY - (charHeight/1.7), charWidth/5.5, charHeight/5, true); //right eye
}  

void draw(){
  charactor(50, 200, 160, 120, 1); //aghast
  charactor(250, 200, 160, 120, 2); //sad
  charactor(450, 200, 160, 120, 3); //normal
  charactor(650, 200, 160, 120, 4); //cool
  charactor(850, 200, 160, 120, 5); //happiest
  enemy(50, 400, 160, 120);
}

Here’s a tiny script I made for working out the share of the shopping bills in my house:

#! /usr/bin/python
"""
This program generated awesome sauce by simplifying the task of getting my housemates to cough up the cash when I've spent all the money on food shopping.
"""

def difference(a,b):
	"""
	A simple function which returns the difference between the two inputs.
	It automatically works out which is bigger, so no problems there then!
	"""
	if a > b:
		result = a - b
	else:
		result = b - a
	return result

def userInput(question, answerType, outcomes=None):
	"""
	The idea behind this is that it will be able to tell whether or not something is an appropriate answer, and won't mess up the program if it isn't. It'll just ask the same question again.
	"""
	while True:
		goodAnswer = False
		answer = raw_input(question)
		if answerType == 'string':
			answer = answer.upper()
			for i in outcomes:
				if answer == i:
					goodAnswer = True
					break
		if answerType == 'float':
			if len(answer) <= 5:
				goodAnswer = True
		if goodAnswer:
			return answer
			break
		else:
			print "Your response to '%s' was unrecognised, please try again."	% question

while True:
	print "Welcome! When entering the payer's name, capitals don't\nmatter (go programming awesomeness!)\n"
	print "When you've added all the receipts, enter the payer's\nname as 'done' and the program will print the owed amounts.\n"
	print "Thank you for using this program to sort out your bills!\n"

	receiptList = []
	jamesPaid = 0
	paulPaid = 0
	simonPaid = 0

	while True:
		name = userInput("Who paid for this receipt? ", 'string', ['SIMON', 'JAMES', 'PAUL', 'DONE'])
		if name == 'DONE':
			break
		amount = userInput("Not counting luxuries, what is the total cost of the receipt? ", 'float')
		receiptList.append((name, float(amount)))
		print 'Successfully added to list.\n'

	for a in receiptList:
		if a[0] == "JAMES":
			jamesPaid = jamesPaid + a[1]
		if a[0] == "PAUL":
			paulPaid = paulPaid + a[1]
		if a[0] == "SIMON":
			simonPaid = simonPaid + a[1]

	jamesPaysPaul = paulPaid / 3
	jamesPaysSimon = simonPaid / 3
	paulPaysJames = jamesPaid / 3
	paulPaysSimon = simonPaid / 3
	simonPaysJames = jamesPaid / 3
	simonPaysPaul = paulPaid / 3

	debtList = [("James", "Paul", jamesPaysPaul, paulPaysJames), ("James", "Simon", jamesPaysSimon, simonPaysJames), ("Paul", "Simon", paulPaysSimon, simonPaysPaul)]

	for a in debtList:
		print a[0], "owes", a[1], difference(a[2], a[3])

	finished = raw_input("All done! To start again, press the enter key now, to quit press any other key followed by the enter key.")
	if finished == '':
		continue
	else:
		break

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>