For portability, you will often seethe first line of the file look like this:#!/usr/bin/env pythonLinux, Cygwin, and other operatingsystems use the first two charactersof the file to identify its type insteadof relying on the extension of thefilename. The two characters "#!"are often called "shebang".Check the PATH and if necessary, addC:\Program Files/Autodesk/Maya2010/binto it.

Generate an image. Use fcheck to view it.

Convert the image to another formatand resize it:imconvert # to get helpimconvert myfile.png -resize 100 thumb.jpgBREAKfire up Maya

create a 100-frame animationand batch-render 640x480PNG files using the format:"name_#.ext"Homework problem due before class Week 2 (worth 100 points):Write a python script that converts the images you created to 128x96 JPG,changes the frame range from 1..100 to 901..1000, and renames themusing the following format:yourInitials_####.jpgexample: gml_0947.jpgOther requirements:

No spaces allowed in filename for this assignment.

Use 'print' statement immediately before conversioncommand to show before and after filenames, e.g.:"Now converting 'untitled_1.png' to 'gml_0901.jpg'..."

Must use leading zeros for new frame range.Send e-mail to ga3333ai@gmail.com with 4 attachments before Week 2 class:1) your script2) captured output when running the script3) Any one of the original PNG images4) Any one of the converted JPG images (not the same frame number as #3)Useful URLs:http://www.python.org/http://rgruet.free.fr/http://www.fundza.com/http://www.imagemagick.org/script/command-line-options.phphttp://javascript-reference.info/http://www.flashdevelop.org/python quick referenceMEL quick referenceZScriptZBrushLinear InterpolationWeek 2Tcl/Tk01If we have a line segment that we wish to divide up into N equal segments,we would take the length of the segment, divide by N, and then start atthe first point and add this distance to it repeatedly until we reached theend point.

So, for example, if we wanted to divide the above line segment into 2 equalsegments, we would take the length of 1 and divide that by 2 (which is 0.5).The length of each of the 2 segments would be 0.5. To find each point,start at 0, add 0.5 to it (which is the midpoint), and add 0.5 again andwe reached the endpoint at 1.

If we wanted 100 equal segments, we divide the length (1) by 100 (0.01)then start at 0 and iteratively add 0.01 (100 times) until we reach theendpoint at 1.abNow let's say that we want to move from 'a' to 'b' in N equal steps.This is called linear interpolation, and is an extremely handy technique.

Once again, we take the length of the segment or distance we wish to cover.We divide this distance by the number of segments (so we have (b-a)/N).Now we step through the segment N times starting from 'a'.

Now let's say we just want the 'k'th point on that segment, where 'a' is thezero'th point and 'b' is the 'N'th point. To find the absolute position of the'k'th point in terms of k, a, b, and N, we just need to do a little math:

position = (b - a) * (k/N) + a

Prove it to yourself. Try out some examples.

Now let's replace (k/N) with the variable 't' which we will limit to the rangefrom 0 to 1, inclusive. With it, we can find any point along the segment atany fraction of the distance.Now we will re-write this expression in terms of t:

As you get see, when t=0, we are left with only 'a',and when t=1, we have only 'b'.Equation of a liney = mx + bbriserunrisem = ----- runplug in any value for 'x' and get the value of 'y'vertical line has infinite slopem is slopeb is the y-intercepthorizontal line has zero slopeLinear interpolationbetween any two points(x0,y0)(x1,y1)To linearly interpolate between any two points,we simply extend the 1-dimensionallinear interpolation to two dimensions:

x = t*x1 + (1-t)*x0y = t*y1 + (1-t)*y0

For 3 dimensions, add in the 3rd dimension:Z = t*Z1 + (1-t)*Z0Equation of a circle(x0,y0)R(x - x0)^2 + (y - y0)^2 = R^2This is great for some situations, but it is sometimes moreconvenient to deal with the parametric representation of a circle...(x0,y0)Rthetax = x0 + R*cos(theta)y = y0 + R*sin(theta)(x,y)As we sweep the angle 'theta' from 0 to 360 degrees(or 0 to 2*PI radians), we sweep out the points ofthe circle.

Now let's linearly interpolate around the edge of thecircle in the same way we interpolated between two points... By using the variable 't' range from 0 to 1...Since sin/cos in most scripting languages use radians, we settheta = t*2*pi and we have:

When writing programs, if we didn't have a way of grouping together a sequenceof actions that occur over and over again, the code would be very long, hard toread, and probably contain more errors because of forgetting to make changesin all the places that this sequence is used.

To get around this problem, programming languages often provide the ability towrite functions that extend the language by grouping together common sequencesof statements.

In python, functions are defined like this:def timestwo(x): return x*2

Functions can take any number of arguments and return any number of values:def interp2d(x0, y0, x1, y1, t): return (t*x1 + (1.0-t)*x0, t*y1 + (1.0-t)*y0)

Since the function is a block, you can put any number of statements within it.

Variables defined within a function are "local" to that function and can only be accessedfrom within that function. We say that variables are "locally scoped".week 1Text editor that supportsPython syntax highlightingFire up MayaOpen up the Script Editor windowClick on the Python tabIn the script editor, you can enter pythonscripts and run them immediately by pressing Ctrl-Enteror the Enter key on the number pad.

Enter the following script:# Comments start with '#' signdef lerp(startVal, endVal, t): return endVal*t + (1.0-t)*startValYou just defined a new function that you can call.Try it out:

Lists are mutable (you can change items in-place): myList[0] = 4Common built-in functions for Listslen(x) # returns length of list xx[a:b] # slice - similar to range(a,b) - doesn't include bmin(x) # minimum value found in list xmax(x) # maximum value found in list xval in x # True if val found in list x, False otherwiseval not in x # opposite of 'val in x'x.count(val) # number of times val found in list xx.index(val) # first time that val is found in list x (or error if not found)x.sort( ) # sorts list x in-placex.sorted( ) # returns new sorted list of x, leaving list x alonex.reverse( ) # reverses list x in-placex.append(val) # appends val to end of list xx.pop( ) # removes and returns last item of list xx.pop(n) # removes and returns 'n'th item of list xTuples - immutable ListsTuples are very similar to Lists, but are immutablemeaning that the contents of the tuple can not be changedonce created. New tuples can be made and assigned overthe same variable, but individual items within the tuple cannot be modified.

Strings are a lot like tuples. They can not be modified, but you can accessindividual characters or slices of the string:

s = "this is my string"s[0] # => 't's[4] # => ' 's[5:7] # => 'is'Dictionaries (aka Hashes or Associative Arrays)It is often useful to be able to store and look up values basedon a 'key' and not on an integer index. Dictionaries hold values thatare accessed by keys. They are created using curly braces:

a < b # True if the value of a is less than the value of ba > b # a greater than ba <= b # a less than or equal to ba >= b # a greater than or equal to ba != b # a not equal to ba in b # can be used when b is a dictionary, tuple, or hashcond1 or cond2 # True if cond1 is True or if cond2 is Truecond1 and cond2 # True if both cond1 and cond2 are Truenot cond1 # True if cond1 is False

To use these comparisons to change the way your script behaves,the "if/elif/else" statement can be used:

All objects within Maya are named, and you need to know the nameof an object to be able to modify or access it.

First, let's create a blank window:import maya.cmds as cmds

w = cmds.window()print wcmds.showWindow(w)# again, only needs to be done once per session or per script# see what the name of the new window is# make the new (empty) window visibleThere are many types of controls that you can put into a window,but before you do, you need to specify what kind of layout thewindow will use to arrange the controls.w = cmds.window()cmds.columnLayout()cmds.checkBox(label='My Checkbox')cmds.showWindow(w)# place all controls in a single column# create a checkbox with the given labelw = cmds.window()cmds.columnLayout()cmds.checkBox(label='My Checkbox')cmds.button(label='My Button')cmds.showWindow(w)Let's add a button to that (remember how to copy & paste)# <= the new linew = cmds.window()cmds.columnLayout()cmds.checkBox(label='My Checkbox')cmds.button(label='My Button')cmds.radioButtonGrp( label='Three Buttons', labelArray3=['One', 'Two', 'Three'], numberOfRadioButtons=3 )cmds.showWindow(w)Now try adding a group of 3 radio buttons...To create a label, use cmds.text(), and to get text from the user,use cmds.textField():w = cmds.window()cmds.columnLayout()cmds.checkBox(label='My Checkbox')cmds.button(label='My Button')cmds.radioButtonGrp( label='Three Buttons', labelArray3=['One', 'Two', 'Three'], numberOfRadioButtons=3 )cmds.text( label='Name' )cmds.textField()cmds.showWindow(w)w = cmds.window(width=238)cmds.columnLayout()cmds.image(image="c:/Windows/Web/exclam.gif")cmds.showWindow(w)You can also display images in your custom GUI:# change properties with added parameterscmds.window(menuBar=True, width=200)cmds.menu(label='File', tearOff=True)cmds.menuItem(label='New')cmds.menuItem(label='Open')cmds.menuItem(label='Save')cmds.menuItem(divider=True)cmds.menuItem(label='Quit')cmds.columnLayout()cmds.button()cmds.showWindow()You can create custom menus for your window:def myButtonPush(*args): print 'My Button was pushed.'

Rows are b[0]...b[9].Board position 'a1' is b[0][0].'i2' is b[8][1] => 4 (a destroyer)Problem #1 of 6: (20 points)Write a function "getBoard(pos)" that takes a string and returns the integerat the specified location within the board grid by accessing the variable 'b'.For example:getBoard('a1') # => 0getBoard('f10') # => 5getBoard('j2') # => 4getBoard('i9') # => 3 hint #2: 'my string'[2:] == 'string'hint #1: ord('c') - ord('a') == 2Problem #2 of 6: (20 points)Write a function setBoard(pos, value) that will change the value of theboard at the given position to the value specified.For example,setBoard('j2', 0) # sets b[9][1] to 0.Problem #3 of 6: (40 points)Write a function countNumber(num) that counts and returns the totalnumber of times that the given 'num' is found within the variable 'b'.So, for example, at the beginning of the game, the following will be true:

countNumber(5) == 5countNumber(2) == 2countNumber(0) == 86hint: b[0].count(0) == 10Problem #4 of 6: (120 points)Write a Python script that uses the functions from problems 1 through 3to implement an interactive one-sided game of battleship where the usertries to sink the computer's ships.

Your script will keep track of previous shots and notify the player if theytry to shoot again in the same spot.

When all ships are sunk, print the message "You won! Play again? (Y/n): "and re-initialize the board if the player wants to continue or exit if theydon't. For this problem, you may re-initialize it to the same starting value.

Here's an example:% python battleship.pyWhere do you wish to shoot? a1Miss.Where do you wish to shoot? d4Hit!Where do you wish to shoot? e4Hit! You sunk my patrol boat!Where do you wish to shoot? k3Invalid shot. Try again.Where do you wish to shoot? a1You already shot there. Try again.hint: boatNames = { 2 : 'patrol boat', 3 : .... }boatNames[2] == 'patrol boat'Problem #5 of 6: EXTRA CREDIT (25 points)Extend battleship.py from problems 1 through 4 by writing an initializeBoard( )function that randomly places the 4 boats onto the board gridsuch that they do not overlap and do not extend off the edge of the board.

Use this function before the first game and after each restart of the gameif the player wishes to continue.

Also, accept upper-case letters as well as lower-case letters (e.g. "J2")and also accept spaces or dashes in the input (e.g. "J 2" or "J-2").

Hints:"J2".lower( ) == 'j2'" J - 2 ".replace(' ', '') == 'J-2'Problem #6 of 6: EXTRA CREDIT (25 points)Modify the tictactoe.py script such that the computer'smoves are no longer random but more intelligent, meaningthat if a win is possible, it will attempt to win the game.

Every window must have at least one layout manager used to arrangethe contents (controls, groups, and collections) within the window.Each window can optionally have menus.

There are a variety of layout managers, and they can be nested withineach other to lay out the controls as desired.columnLayoutformLayoutframeLayoutgridLayoutmenuBarLayoutpaneLayoutrowColumnLayoutrowLayoutscrollLayoutshelfLayoutshelfTabLayouttabLayoutsingle vertical columnexact absolute and relative positioningdraws a border and provides a label for the framearranged controls in a 2D gridenables embedding a menu bar within the layoutprovides moveable panes - aka splitter panelprovides either a row layout or a column layoutsingle horizontal rowprovides horizontal and/or vertical scrollbars for scrollingcreates a shelf where command scripts can be droppeda tabLayout with drop capability and a garbage iconprovides tab groups for collections of controlscolumnLayoutformLayoutframeLayoutgridLayoutmenuBarLayoutpaneLayoutrowColumnLayoutrowLayoutscrollLayoutBREAKshelfLayoutshelfTabLayouttabLayoutBREAK"closed book"no internetno computersno assistance from othersSo after all this, I thought... wouldn't it be cool if someonenoticed that this GUI building stuff is repeatitive, boring,and rather mind-numbing... so I searched for:

maya ui builder

(actually, I tried a few others first, but the results of thissearch were the best...)

The first URL that came up was:http://www.exood4.com/melanie.php?lang=enclick on "Download MELANIE v0.5"

Save file to desktop

Double-click on melanie.zip

Double-click on setup.exe

Install in default location

Find new program in Start Menu and run itExport to MayaColumn and Row LayoutsControlsSelect item, then Edit its sizeProperties editorHierarchy of layoutsand controlsHelpYour new GUIExport your new MEL GUI script to a file.Then you can 'source' it within Maya's MEL script editor. Or youcould just open it up with WordPad or 'type' it in a CMD windowthen copy and paste the contents into Maya's MEL script editorand execute it with Ctrl-Enter or Enter on the numeric keypad.No new homeworkassignment this week.

For lab time, work on yourhomework assignment #3 thatis due before class next week.week 5Quiz ResultsMidterm Exam100 pointsplus 20 points extra credit"closed book"no internetno computersno assistance from othersScripting languages have a huge number of possible applications.

Another application that we have not yet explored is scriptingfor the web and designing interactive web-based applications.

There are a large number of technologies available fordesigning interactive websites and web-based applications.

One technology is called Google App Engine.

In a browser, visit: http://code.google.com/appengine/

Click on "Download" on the right.

Click on latest "GoogleAppEngine_*.msi" and then run it

Click on "Getting Started" and then on "Hello, World!"

Create a new directory on your desktop called "helloworld"Copy and Paste the contents on the web page intotwo files within the 'helloworld' directory:

helloworld.pyapp.yaml

In a cmd window, start up the Google App Enginedevelopment server from your Desktop directory:

dev_appserver.py helloworld

Point your browser to: http://localhost:8080/

Tweak the contents of "helloworld.py", save it, thenhit Reload on your browser to see the changes.

Python modifies the web pages sent so that Flash getsthe proper variable values from the web page.Final Group ProjectsGroups of 2 to 4 students will design a final projectusing python and will all present the working project on Week 11in front of the class as the final exam. Students will alsohand in evaluations of all other students after the presentations.

The design concept must first be approved in Week 6.

It can not be too simple and should not be too complex.

Possible ideas:

design an interactive gamedesign a conversion tool that converts one format to anotherdesign a GUI for Maya that provides a custom featurecreate an interactive website with Google App Engineuse a GUI toolkit like PyQt, PyTk, PyFltk, etc. to create a nice graphical user interface for a game or toolwrite a script that plays another game running in a different window using AutoIT3 (www.autoitscript.com)week 6Midterm ExamTesting Your ScriptsIt is often useful to put testing code right into your script.

In more advanced scripting, we'll get into unit testing.

Before then, however, there is a statement called 'assert' thatcan be incredibly handy. The contents of the 'assert' must betrue or the script will fail at that point.

Sometimes it is beneficial to start with the assertions and thenfill in the rest of the code.Type checking can be useful when you need to make surethat the parameters in a function are what you expected.

assert(type('this is a string') == str)

assert(type(100) == int)

assert(type(100.0) == float)

def getBoard(pos): assert(type(pos) == str) # ....

Don't use assertions on user input, though, as you don'twant the script to crash on unexpected input.Group Project Proposals DueE-mail the following information to ga3333ai@gmail.com:

1. Names of the 2-4 people in your group2. The name of your Project3. Description of the Project4. Describe how you will present the project to the classweek 7Debugging and TroubleshootingWhen programming, sometimes things go wrong.

Being able to debug your programs is an important skill to have.

print statements are often a quick way to see the internal stateof your program during a run, but sometimes you need a debugger.

A debugger allows you to set breakpoints in your code, examinevariable values, and step over statements and into functions.

out = ''for c in string: out = '%s%s' % (out, xform[c])print oute-mail corrected script to ga3333ai@gmail.com - worth 20 pointsopen book - feel free to use the computer to correct the bugsHomework Week 7Due: Week 10 - 100 PointsProblem #1: 50 pointsCreate a GUI in Maya with a table using the grid layoutmanager which contains both text graphics. Make the gridat least 2x2 to show that it is a grid. (2 columns, 2 rows.)Use either MEL or Python within Maya for Problem #1

Problem #2: 50 pointsCreate a window using Python and the Tkinter modulewith a table using a grid layout manager which containsboth text and graphics. (Again, at least a 2x2 grid.)Problem #2 is a stand-alone script *without* Maya.

E-mail both scripts before class on Week 10to ga3333ai@gmail.comInteresting talk on the future of gamesWhat does this have to do with scripting languagesor programming in general?!?http://fury.com/2010/02/http://fury.com/2010/02/jesse-shells-mindblowing-talk-on-the-future-of-games-dice-2010/(more specifically...)http://www.amazon.com/Art-Game-Design-book-lenses/dp/0123694965/Click on "raw code"to downloadFixing the bugs quiz: The SequelOpen-book quiz - use the computerThis quiz is worth 100 points.

BONUS: If you get it to draw the maze on the screen(which means you found and fixed all the bugs)you get an extra 100 bonus points!!!

garbage collection and high-level languagesProblem-Solving Skillsweek 9Problem-solving skills are important to becoming an effectiveprogrammer.

It is often useful to think of programming problems like they arepuzzles that need to be solved.

To solve the puzzle, it needs to be broken down into smallerpieces that can be understood and solved individually so that,when all the smaller parts have solutions, the bigger problemis "automatically" solved for you.

So the skill is developed by practicing solving challenging problems.Common steps in programming(and problem-solving in general)Understand the problem

Develop a strategy to solving the problem as if you would be solving it without the computer

Break the problem into smaller pieces

Determine what kind of data structures would be necessary to model the problem