Program Arcade Games
With Python And Pygame

Wait, What Else Can We Do?

What else can we do with programming skills? Once you finish this course and look around, you might find yourself doing something other than programming video games. Your programming probably won't be in Python. In fact, you might not realize you've got an opportunity to do programming at all.

In this chapter we'll look at different examples of what you can do with your programming skills. Even if you don't become a full-time programmer, you can save yourself a lot of time and effort by creating some small programs on the side that keep you from doing repetitive tasks.

5.1 Arduino Demonstration

fig.arduino

It used to be that combining programming skills with electronics to control robotics was difficult. Creating embedded systems that combine a small cheap computer that can manage servos, valves, motors, and lights required a very different type of programming. Embedded systems often don't even have an operating system like Microsoft Windows. They might not even have a disk drive!

In the last few years programming embedded systems has become so easy that even some grade school kids are doing it. One of the products helping this new movement of do-it-yourselfers is the Arduino. The specifications for the Arduino are free and open, allowing anyone to create their own embedded solutions for very little money.

There are many other companies that sell Arduino kits. If you have a good Radio Shack in your neighborhood, it may have a selection of Arduino computers. Adafruit (one of my favorite companies) sells an excellent starter pack with an Arduino computer, some lights, a motor, a servo, and a few other odds and ends can be purchased for various companies for less than $100.
http://adafruit.com/products/170

This experimenter's package can be used to build the following Arduino example that controls nine LED lights, one multi-color LED light, and uses a force sensor to control a servo arm.

Video: Arduino Demonstration
fig.LEDDemo_01
Figure 47.16: Adruino Example: Hooking up an LED

Figure 47.16 shows how to hook up one LED light to the Arduino. The LED hooks up to pin 13 on the Arduino. A “resistor” is also placed in-line to keep the electricity from flowing too fast and burning out the LED. Resistors have different values, and the color codes on the resistor allow a person to select the correct resistor.

This setup for pin 13 is repeated for pins 13 down to 4, so that a total of 9 LEDs can be hooked up to the Arduino.

fig.LEDDemo_02
Figure 47.17: Adruino Example: Hooking up an RGB LED

If you don't want to be stuck with only one color of LED, you can use a multi-color LED. Multi-color LEDs have three LEDs built into them. One for red, one blue, and one green. Sound familiar? Colors are specified for the LED by controlling how bright red, green, and blue are. This is just like programming our game!

Hooking up the multi-colored LED is shown in Figure 47.17.

fig.LEDDemo_03
Figure 47.18: Adruino Example: Force sensor controlling a servo

Figure 47.18 shows how to hook up a force sensor to control how far a servo arm moves. The force sensor is very sensitive, and based on how gently it is squeezed, the robotic servo arm can do your work. A little more work and you can create your own exoskeleton!

Take a look at the code below. The code is in the computer language “C.” You'll find the C language has many things that are similar to what we've learned in Python:

// Import servo library
#include <Servo.h>

// Global Variables
long currentPin=4;
Servo myservo;

// Setup function
void setup() {
    // Attach the servo object to pin 3
    myservo.attach(3);
    // Set pins 1 to 13 for output.
    for( int i=1; i <= 13; i++ )
        pinMode(i, OUTPUT);
}

// Main program loop
void loop()
{
    // Loop from pins 4 to 13
    for( int i=4; i <= 13; i++ ) {
        // Figure out if the LED should be lit
        if( currentPin == i ) {
            digitalWrite(i, HIGH); // On
        } else {
            digitalWrite(i, LOW);  // Off
        }
    }
    // Set the next LED to light up next time
    currentPin += 1;
    // Reset back to the beginning
    if( currentPin > 13 ) {
        currentPin = 4;
    }

    // Get random color values
    int r=random(0,256);
    int g=random(0,256);
    int b=random(0,256);

    // Set red, green, and blue parts of LED
    analogWrite(0, r);
    analogWrite(1, g);
    analogWrite(2, b);

    // Read force sensor on pin A5 (possible range 0-1023)
    int sensorValue = analogRead(A5);
    // Write out servo position (possible range 0-255)
    myservo.write(sensorValue / 4);

    // Delay 150ms before we do this again
    delay(150);
}

5.2 Excel Macro Demonstration

47.2.1 Introduction

Imagine you graduate from college and start work in the business world. A nightmare! You weren't hired as a VP! You are a lowly peon in the business world set to do menial tasks for someone else. This isn't at all like what the college brochure promised you.

You have to create the same charts, over and over for some financial analyst. He makes too much money to be stuck creating charts, so you have your first job creating these charts for him in Excel.

Wait, boring, repetitive tasks! The exact thing that programming was created to help eliminate! And you took this class in programming, so you should be all set! Follow the outline below in Excel and create your own macro that will automatically create charts for stocks. (This is actually what happened to me in my first job, and was the start to my being able to land my first big project.)

Video: Excel Macro Demonstration

47.2.2 Tutorial

This is what your Visual Basic script should look like after recording:

47.2.3 Code Listings

Sub CreateChart()
'
' CreateChart Macro
'

'
    Workbooks.Add
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;http://finance.yahoo.com/q/hp?s=wfc", Destination:=Range("$A$1"))
        .Name = "hp?s=wfc"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlSpecifiedTables
        .WebFormatting = xlWebFormattingNone
        .WebTables = "16"
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLine
    ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$G$69")
    ActiveChart.Location Where:=xlLocationAsNewSheet
    ActiveChart.ChartArea.Select
    ActiveChart.Legend.Select
    Selection.Delete
    ActiveChart.ChartArea.Select
    ActiveChart.SeriesCollection(5).Select
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.ChartArea.Select
    ActiveChart.ChartTitle.Select
    ActiveChart.ChartTitle.Text = "WFC"
    Selection.Format.TextFrame2.TextRange.Characters.Text = "WFC"
    With Selection.Format.TextFrame2.TextRange.Characters(1, 3).ParagraphFormat
        .TextDirection = msoTextDirectionLeftToRight
        .Alignment = msoAlignCenter
    End With
    With Selection.Format.TextFrame2.TextRange.Characters(1, 3).Font
        .BaselineOffset = 0
        .Bold = msoTrue
        .NameComplexScript = "+mn-cs"
        .NameFarEast = "+mn-ea"
        .Fill.Visible = msoTrue
        .Fill.ForeColor.RGB = RGB(0, 0, 0)
        .Fill.Transparency = 0
        .Fill.Solid
        .Size = 18
        .Italic = msoFalse
        .Kerning = 12
        .Name = "+mn-lt"
        .UnderlineStyle = msoNoUnderline
        .Strike = msoNoStrike
    End With
End Sub

Once you modify the script to take a parameter so you can graph any stock, it should look like this:

Sub CreateChart(ticker)
'
' CreateChart Macro
'

'
    Workbooks.Add
    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;http://finance.yahoo.com/q/hp?s=" + ticker, Destination:=Range("$A$1"))
        .Name = "hp?s=wfc"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlSpecifiedTables
        .WebFormatting = xlWebFormattingNone
        .WebTables = "16"
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLine
    ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$G$69")
    ActiveChart.Location Where:=xlLocationAsNewSheet
    ActiveChart.ChartArea.Select
    ActiveChart.Legend.Select
    Selection.Delete
    ActiveChart.ChartArea.Select
    ActiveChart.SeriesCollection(1).Select
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.SeriesCollection(1).Delete
    ActiveChart.ChartArea.Select
    ActiveChart.ChartTitle.Select
    ActiveChart.ChartTitle.Text = ticker
    Selection.Format.TextFrame2.TextRange.Characters.Text = ticker
    With Selection.Format.TextFrame2.TextRange.Characters(1, 3).ParagraphFormat
        .TextDirection = msoTextDirectionLeftToRight
        .Alignment = msoAlignCenter
    End With
    With Selection.Format.TextFrame2.TextRange.Characters(1, 3).Font
        .BaselineOffset = 0
        .Bold = msoTrue
        .NameComplexScript = "+mn-cs"
        .NameFarEast = "+mn-ea"
        .Fill.Visible = msoTrue
        .Fill.ForeColor.RGB = RGB(0, 0, 0)
        .Fill.Transparency = 0
        .Fill.Solid
        .Size = 18
        .Italic = msoFalse
        .Kerning = 12
        .Name = "+mn-lt"
        .UnderlineStyle = msoNoUnderline
        .Strike = msoNoStrike
    End With
End Sub
Sub CreateCharts()
    CreateChart ("WMT")
    CreateChart ("INTC")
    CreateChart ("WFC")
    CreateChart ("BBY")
    CreateChart ("FDX")
End Sub

47.2.4 Multiple Choice Quiz

Click here for a multiple-choice quiz.

47.2.5 Short Answer Worksheet

Click here for the chapter worksheet.

47.2.6 Lab

Click here for the chapter lab.


You are not logged in. Log in here and track your progress.