Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

GA3333

GA3333 - Introduction to Scripting Languages
by

Glenn Lewis

on 10 November 2015

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of GA3333

GA3333
Introduction to
Scripting Languages
Programming can be fun!
Instructor: Glenn Lewis
e-mail: ga3333ai@gmail.com
week 1
Right now, please send me an e-mail
with the following information:
Your name
Your Student ID
Your major or focus
Any programming experience you may have
Any 3D application experience you may have
Anything else you think I should know
(Cover syllabus)
"ArtOC" 89074
Python
Ruby
MEL
JavaScript
MAXScript
Perl
Processing
Maya
3ds Max
Maya
Blender
Sketchup
App Engine
web browsers
Flash
ActionScript
Some popular scripting languages
Great for:
quick experiments
prototyping
applications
extensions
websites
Start up a cmd window and check the PATH settings for python
Python 2.6
Start -> Run
cmd
path
Start -> Run
cmd
python
>>>
Ctrl-Z <Enter> to exit
1 + 2 * 8
(1+2)*8
parentheses
unary operators
**
* / %
+ -
comparisons
8 / 4
1 / 3
1.0 / 3
1 / 3.0
1.0 / 3.0
int
float
string ('str')
list (aka array)
dictionary (aka hash)
type(72)
type(72.0)
type("72.0")
type('72')
True
False
None
(case sensitive)
8 / 2
8 % 2
7 / 2
7 % 2
1 % 2
"value: %s" % 5
"a%sb%sc" % (1, 2)
%s %d %f %x %X %%
modifiers
%03d %4.1f %-20s
import os
import sys
import math
math.pi
math.e
from math import *
os.getcwd( )
os.chdir("C:/mydir")
os.system("dir")
random.randint(1,10)
sin(0.2)
BREAK
start up python
use as a calculator
order of precedence rules
division
types
specials
modulo
string formatting
importing modules
function calls
variables - assignment
looping - while - for - range() - lists
print
running external python scripts
using ".py" extension
using "shebang" on first line
capturing output of script to file
external utilities
fcheck
imconvert
x = 4
type(x)
x = 4.5
type(x)
x = "x used to be: %s" % x
type(x)
while True: print "hi"
Ctrl-C
"white space" matters in python
blocks
two <Enter>s to finish the block
x = 1
while x < 10:
print x
x = x + 1
range(1,11) # returns a list
for i in range(1,11):
print i
while False:
print "Not going to happen."
Use notepad, wordpad,
or your favorite text editor.

Add the ".py" extension to
the filename. e.g. myscript.py

% python myscript.py

% python myscript.py > output.txt

For portability, you will often see
the first line of the file look like this:
#!/usr/bin/env python
Linux, Cygwin, and other operating
systems use the first two characters
of the file to identify its type instead
of relying on the extension of the
filename. The two characters "#!"
are often called "shebang".
Check the PATH and if necessary, add
C:\Program Files/Autodesk/Maya2010/bin
to it.

Generate an image. Use fcheck to view it.

Convert the image to another format
and resize it:
imconvert # to get help
imconvert myfile.png -resize 100 thumb.jpg
BREAK
fire up Maya

create a 100-frame animation
and batch-render 640x480
PNG 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 them
using the following format:
yourInitials_####.jpg
example: gml_0947.jpg
Other requirements:

No spaces allowed in filename for this assignment.

Use 'print' statement immediately before conversion
command 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 script
2) captured output when running the script
3) Any one of the original PNG images
4) 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.php
http://javascript-reference.info/
http://www.flashdevelop.org/
python quick reference
MEL quick reference
ZScript
ZBrush
Linear Interpolation
Week 2
Tcl/Tk
0
1
If 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 at
the first point and add this distance to it repeatedly until we reached the
end point.

So, for example, if we wanted to divide the above line segment into 2 equal
segments, 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 and
we 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 the
endpoint at 1.
a
b
Now 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 the
zero'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 range
from 0 to 1, inclusive. With it, we can find any point along the segment at
any fraction of the distance.
Now we will re-write this expression in terms of t:

position = (b - a) * t + a

If we do a little bit of re-arranging, we have:

position = b*t - a*t + a = b*t + a - a*t = b*t + a*(1-t)
position = t*b + (1-t)*a

As you get see, when t=0, we are left with only 'a',
and when t=1, we have only 'b'.
Equation of a line
y = mx + b
b
rise
run
rise
m = -----
run
plug in any value for 'x' and get the value of 'y'
vertical line has infinite slope
m is slope
b is the y-intercept
horizontal line has zero slope
Linear interpolation
between any two points
(x0,y0)
(x1,y1)
To linearly interpolate between any two points,
we simply extend the 1-dimensional
linear interpolation to two dimensions:

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

For 3 dimensions, add in the 3rd dimension:
Z = t*Z1 + (1-t)*Z0
Equation of a circle
(x0,y0)
R
(x - x0)^2 + (y - y0)^2 = R^2
This is great for some situations, but it is sometimes more
convenient to deal with the parametric representation of a circle...
(x0,y0)
R
theta
x = 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 of
the circle.

Now let's linearly interpolate around the edge of the
circle 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 set
theta = t*2*pi and we have:

x = x0 + R*cos(t*2*pi)
y = y0 + R*sin(t*2*pi)
Functions
"The Pragmatic Programmer" is an excellent book that contains many useful tips
and principles. One such principle is "Don't Repeat Yourself".

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

To get around this problem, programming languages often provide the ability to
write functions that extend the language by grouping together common sequences
of 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 accessed
from within that function. We say that variables are "locally scoped".
week 1
Text editor that supports
Python syntax highlighting
Fire up Maya
Open up the Script Editor window
Click on the Python tab
In the script editor, you can enter python
scripts and run them immediately by pressing Ctrl-Enter
or the Enter key on the number pad.

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

lerp(0, 10, 0)
lerp(0, 10, 0.5)
lerp(0, 10, 1)
lerp(20, 80, 0.2)

This function implements linear interpolation between
any two points. Prove to yourself that it is working
properly.
Now enter the following function definition:
import maya.cmds as cmds
def plotPointsOn2DLine(x0, y0, x1, y1, numPoints):
for i in range(0, numPoints+1):
t = i / float(numPoints)
x = lerp(x0, x1, t)
y = lerp(y0, y1, t)
print "plotting point (%s,%s,0)" % (x, y)
cmds.curve(d=0, p=[x, y, 0])
This function linearly interpolates along a line, plotting points as it goes.
Try it out:

plotPointsOn2DLine(0, 0, 20, 20, 10)
Try this out:
from math import *
def plotPointsOn2DCircle(x0, y0, radius, numPoints):
for i in range(0, numPoints):
t = i / float(numPoints)
angle = 2.0*pi*t
x = x0 + radius*cos(angle)
y = y0 + radius*sin(angle)
print "plotting point (%s,%s,0)" % (x, y)
cmds.curve(d=0, p=[x, y, 0])
plotPointsOn2DCircle(20,20,5,100)
String art in Maya using scripting
def pointOnCircle(x0, y0, radius, angle):
return (x0 + radius*cos(angle), y0 + radius*sin(angle))

def stringArt(x0, y0, radius, numPoints):
for i in range(0, numPoints+1):
t = i / float(numPoints)
angle1 = 2.0*pi*t
angle2 = 2.0*angle1
(x1, y1) = pointOnCircle(x0, y0, radius, angle1)
(x2, y2) = pointOnCircle(x0, y0, radius, angle2)
print "plotting line (%s,%s,0) to (%s,%s,0)" % (x1, y1, x2, y2)
cmds.curve(d=1, p=[[x1, y1, 0], [x2, y2, 0]])
Homework assignment due before class on Week 3 (100 points):
Problem #1 (50 points):
Write a complete script that divides a 3D line segment into 'N' parts and
plots 'N'+1 points along the line segment (including starting and ending point).
A complete script means that when loaded into a freshly-started Maya,
it will run correctly without any errors. Make sure you try it out!
The script will take the following arguments:
plot3Dline(x0, y0, z0, x1, y1, z1, n)
Turn in your script for this problem
Problem #2 (50 points):
Using the Maya Python Command Reference, write a Python script that creates
a 3D scene using at least the following primitives:
a nurbs sphere
a nurbs torus
a polygonal cube
a polygonal sphere
Turn in your script along with a 3D rendering of your scene where all 4 object types are visible.
(Hint: the cmds.move() and cmds.scale() functions can be useful or you can position your objects
as you create them.)
A total of 3 attachments are required for this assignment. E-mail to: ga3333ai@gmail.com
BREAK
BREAK
For homework assignment #1, here is an example solution:

import os
for x in range(1,101):
print "Now converting 'untitled_%s.png' to 'gml_%04d.jpg'..." % (x, x+900)
os.system("imconvert untitled_%s.png -resize 128 gml_%04d.jpg" % (x, x+900))
http://prezi.com/15cpfk3yjms_/
# e.g.: float(3) => 3.0
# only needs to be done once per session
# Calling our new function
# Calling it again with different parameters
# Calling Maya's 'curve' command
# to plot a 3D point - ignore warnings
# start point same as end point
# radians: 2*pi = 360 degrees
# needed only once per session or script
# needed to call sin & cos
stringArt(-5, 5, 5, 100)
(I will!)
Help available from menu: Help -> Python Command Reference
Remember: Check out:
Help -> Python Command Reference
from math import *
to call a function,
timestwo(5)
value = timestwo(any_expression)
Introduction to MEL scripting
MEL scripting is conceptually very similar to Python, with some of
the following differences:

no need for importing
variable names always start with '$' (e.g. "$myVar = 5;")
every statement MUST end with a semicolon (";")
comments start with '//' like C++, JavaScript, ActionScript, etc.
MEL doesn't care about white space... but
MEL blocks are surrounded by curley braces. For example:
while ($x < 100) {
// do something useful
$x = $x + 1;
}
MEL variables are strongly typed, and its type can not change
So, for example, if your variable is first a float, it later can
not be an array.
Declaring the type of the variable is not always required, but
is a good practice.
functions are defined with 'proc' and the argument types and
return types need to be declared.
for loops have a different syntax:
for (init statment; while statement; increment statement) { ... }
example: for ($i=0; $i < $numPoints; $i++) { ... }
easy variable increment: $var++; $var += 30.0;
easy variable decrement or subtraction: $var--; $var -= 10.0;
use print("x="+$x+", y="+$y); instead of: print "x=%s, y=%s" % (x, y)
MEL version:
// Comments start with '//' to end of line
proc float lerp(float $startVal, float $endVal, float $t) {
return ($endVal*$t + (1.0 - $t)*$startVal);
};
lerp(0, 10, 0);
lerp(0, 10, 0.5);
lerp(0, 10, 1);
lerp(20, 80, 0.2);
proc plotPointsOn2DLine(float $x0, float $y0, float $x1, float $y1, int $numPoints) {
for ($i=0; $i <= $numPoints; $i++) {
$t = $i / float($numPoints);
$x = lerp($x0, $x1, $t);
$y = lerp($y0, $y1, $t);
print("plotting point ("+$x+","+$y+",0)");
curve -d 0 -p $x $y 0;
}
};
plotPointsOn2DLine(10, 10, 15, 15, 100);
week 3
Lists (aka Arrays)
Variables of type "int" or "float" are containers that hold a single value.

Lists allow us to keep track of many values and also keep them ordered.

Lists are created by using square brackets:
myList = [ ] # an empty array
type(myList) # => (type 'list')

To find the number of items in a list, use the "len( )" function:
len(myList) # => 0

Items in a list are separated by commas and can be of any type:

myList = [ 22/7, 3.14159265, "pi" ]
len(myList) # => 3
type(myList) # => (type 'list')

To access individual items in the list, use an integer index:

myTypes = [ type(myList[0]), type(myList[1]), type(myList[2]) ]
myTypes # => [type('int'), type('float'), type('str')]

Lists are mutable (you can change items in-place): myList[0] = 4
Common built-in functions for Lists
len(x) # returns length of list x
x[a:b] # slice - similar to range(a,b) - doesn't include b
min(x) # minimum value found in list x
max(x) # maximum value found in list x
val in x # True if val found in list x, False otherwise
val not in x # opposite of 'val in x'
x.count(val) # number of times val found in list x
x.index(val) # first time that val is found in list x (or error if not found)
x.sort( ) # sorts list x in-place
x.sorted( ) # returns new sorted list of x, leaving list x alone
x.reverse( ) # reverses list x in-place
x.append(val) # appends val to end of list x
x.pop( ) # removes and returns last item of list x
x.pop(n) # removes and returns 'n'th item of list x
Tuples - immutable Lists
Tuples are very similar to Lists, but are immutable
meaning that the contents of the tuple can not be changed
once created. New tuples can be made and assigned over
the same variable, but individual items within the tuple can
not be modified.

Tuples are created using parentheses instead of square brackets:

myTuple = ( 22/7, 3.14159265, "pi" )
len(myTuple) # => 3

myTuple[0] # => 3
myTuple[2] # => 'pi'

myTuple[1] = 40 # TypeError: 'tuple' object does not support item assignment

Strings are a lot like tuples. They can not be modified, but you can access
individual 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 based
on a 'key' and not on an integer index. Dictionaries hold values that
are accessed by keys. They are created using curly braces:

myHash = { }
len(myHash) # => 0

myHash = { 'key1' : 'val1', 'key2' : 'val2' }
len(myHash) # => 2
myHash['key1'] # => 'val1'
myHash['key2'] # => 'val2'

Dictionaries are mutable:
myHash['key1'] = 30

'key2' in myHash # => True
'notThere' in myHash # => False
'val1' in myHash # => False - 'in' used only for keys, not values
Common built-in functions for Dictionaries
len(d) # number of key/value pairs in dictionary d
key in d # boolean if key exists in dictionary d
d.has_key(key) # same as key in d
d.clear( ) # same as d = { }
d.items( ) # Returns a list of tuples from dictionary d
# e.g. [ ('key1','val1'), ('key2','val2') ]
d.keys( ) # Returns a list of keys from dictionary d
# e.g. [ 'key1', 'key2' ]
d.values( ) # Returns a list of values from dictionary d
# e.g. [ 'val1', 'val2' ]
d.pop(key) # Removes and returns the value associated
# with 'key' from dictionary d
Comparisons, Conditional Statements
Comparisons enable your script to make decisions
based on the results of expressions. Here are some
common comparisons:

a < b # True if the value of a is less than the value of b
a > b # a greater than b
a <= b # a less than or equal to b
a >= b # a greater than or equal to b
a != b # a not equal to b
a in b # can be used when b is a dictionary, tuple, or hash
cond1 or cond2 # True if cond1 is True or if cond2 is True
cond1 and cond2 # True if both cond1 and cond2 are True
not 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:

if cond1:
print "cond1 is True"
elif cond2:
print "cond2 is True"
else:
print "cond1 and cond2 are both False"
Lab: Simple user interaction
#!/usr/bin/env python

import random

board = range(1,10) # [1,2,3,4,5,6,7,8,9]

def printBoard():
print
for i in range(0,3):
print " | | "
print " %s | %s | %s " % (board[i*3], board[i*3+1], board[i*3+2])
print " | | "
if i != 2:
print "---|---|---"

def possibleMove():
moves = []
for i in range(0,9):
if board[i] != 'X' and board[i] != 'O':
moves.append(i+1)
if len(moves) > 0:
return moves[random.randint(0,len(moves)-1)]
return False

def playAgain():
print "Want to play again? (Y/n): ",
answer = raw_input()
if answer == 'n':
return False
for i in range(0,9):
board[i] = i+1
return True
def announceWinner(winner):
if winner == 'X':
printBoard()
print "You won!"
playAgain()
elif winner == 'O':
printBoard()
print "I won!"
playAgain()

def checkWin():
for i in range(0,3):
# Check horizontal win
if board[i*3] == board[i*3+1] and board[i*3] == board[i*3+2]:
winner = board[i*3]
announceWinner(winner)
return winner
# Check vertical win
if board[i] == board[i+3] and board[i] == board[i+6]:
winner = board[i]
announceWinner(winner)
return winner
# Check diagonal
if board[0] == board[4] and board[0] == board[8]:
winner = board[0]
announceWinner(winner)
return winner
# Check other diagonal
if board[2] == board[4] and board[2] == board[6]:
winner = board[2]
announceWinner(winner)
return winner
return False
while possibleMove():
printBoard()
print "Your move (1-9,q): ",
move = raw_input()
if move == 'q':
break
try:
move = int(move)
except:
print "Please enter 1-9 or 'q' to quit."
continue
if board[move-1] == move:
board[move-1] = 'X'
else:
print "Please enter 1-9 or 'q' to quit."
continue
if checkWin():
continue
move = possibleMove()
if move:
print "I move to %s." % move
board[move-1] = 'O'
checkWin()
else:
printBoard()
print "I can't move. Draw."
playAgain()
BREAK
Creating custom GUIs within Maya using Python
To create a custom GUI within Maya, you first need a window.
By default, all windows are invisible when you create them so
that you can build up the whole GUI with all its widgets before
it is displayed for the first time.

All objects within Maya are named, and you need to know the name
of 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 w
cmds.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 visible
There are many types of controls that you can put into a window,
but before you do, you need to specify what kind of layout the
window 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 label
w = 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 line
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.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 parameters
cmds.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.'

cmds.window()
cmds.columnLayout()
cmds.button(label='My Button', command=myButtonPush)
cmds.showWindow()
To get the GUI to perform an action, we need to add commands:
BREAK
Homework Assignment #3: Battleship
You are given the two-dimensional array:
b = [[0,0,0,0,0,0,0,0,0,0], #row a
[0,0,0,0,0,0,0,0,0,0], #row b
[0,0,0,0,0,0,0,0,0,0], #row c
[0,0,0,2,0,0,0,0,0,0], #row d
[0,0,0,2,0,0,0,0,0,0], #row e
[0,0,0,0,0,5,5,5,5,5], #row f
[0,4,0,0,0,0,0,0,0,0], #row g
[0,4,0,0,0,0,0,0,0,0], #row h
[0,4,0,0,0,0,3,3,3,0], #row i
[0,4,0,0,0,0,0,0,0,0]] #row j
This represents a 10x10 grid with 4 ships
on it: a patrol boat (2's), a submarine (3's),
a destroyer (4's), and a battleship (5's).

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 integer
at the specified location within the board grid by accessing the variable 'b'.
For example:
getBoard('a1') # => 0
getBoard('f10') # => 5
getBoard('j2') # => 4
getBoard('i9') # => 3 hint #2: 'my string'[2:] == 'string'
hint #1: ord('c') - ord('a') == 2
Problem #2 of 6: (20 points)
Write a function setBoard(pos, value) that will change the value of the
board 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 total
number 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) == 5
countNumber(2) == 2
countNumber(0) == 86
hint: b[0].count(0) == 10
Problem #4 of 6: (120 points)
Write a Python script that uses the functions from problems 1 through 3
to implement an interactive one-sided game of battleship where the user
tries to sink the computer's ships.

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

The moment a ship is sunk, print the message "You sunk my <boat name>!".

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 they
don't. For this problem, you may re-initialize it to the same starting value.

Here's an example:
% python battleship.py
Where do you wish to shoot? a1
Miss.
Where do you wish to shoot? d4
Hit!
Where do you wish to shoot? e4
Hit! You sunk my patrol boat!
Where do you wish to shoot? k3
Invalid shot. Try again.
Where do you wish to shoot? a1
You 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 grid
such 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 game
if 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's
moves are no longer random but more intelligent, meaning
that if a win is possible, it will attempt to win the game.

Also, fix the bug where it doesn't exit sometimes after
saying 'n' to play again. Hint: use the "exit( )" function.
Due in TWO (2) Weeks - Week 5 - 200 Points (plus 50 points extra credit)
as always, due before class begins on Week 5
0 1 2
3 4 5
6 7 8
quiz
week 4
Layout Managers
All custom GUIs (Graphical User Interfaces) are created within a window.

Every window must have at least one layout manager used to arrange
the 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 within
each other to lay out the controls as desired.
columnLayout
formLayout
frameLayout
gridLayout
menuBarLayout
paneLayout
rowColumnLayout
rowLayout
scrollLayout
shelfLayout
shelfTabLayout
tabLayout
single vertical column
exact absolute and relative positioning
draws a border and provides a label for the frame
arranged controls in a 2D grid
enables embedding a menu bar within the layout
provides moveable panes - aka splitter panel
provides either a row layout or a column layout
single horizontal row
provides horizontal and/or vertical scrollbars for scrolling
creates a shelf where command scripts can be dropped
a tabLayout with drop capability and a garbage icon
provides tab groups for collections of controls
columnLayout
formLayout
frameLayout
gridLayout
menuBarLayout
paneLayout
rowColumnLayout
rowLayout
scrollLayout
BREAK
shelfLayout
shelfTabLayout
tabLayout
BREAK
"closed book"
no internet
no computers
no assistance from others
So after all this, I thought... wouldn't it be cool if someone
noticed 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 this
search were the best...)

The first URL that came up was:
http://www.exood4.com/melanie.php?lang=en
click 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 it
Export to Maya
Column and Row Layouts
Controls
Select item, then Edit its size
Properties editor
Hierarchy of layouts
and controls
Help
Your new GUI
Export your new MEL GUI script to a file.
Then you can 'source' it within Maya's MEL script editor. Or you
could just open it up with WordPad or 'type' it in a CMD window
then copy and paste the contents into Maya's MEL script editor
and execute it with Ctrl-Enter or Enter on the numeric keypad.
No new homework
assignment this week.

For lab time, work on your
homework assignment #3 that
is due before class next week.
week 5
Quiz Results
Midterm Exam
100 points
plus 20 points extra credit
"closed book"
no internet
no computers
no assistance from others
Scripting languages have a huge number of possible applications.

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

There are a large number of technologies available for
designing 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 into
two files within the 'helloworld' directory:

helloworld.py
app.yaml

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

dev_appserver.py helloworld

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

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


All website interaction is handled in python.

Google App Engine stores all the persistent data
and handles caching the website and handling demand.

Flash communicates directly with the python scripts.

Python modifies the web pages sent so that Flash gets
the proper variable values from the web page.
Final Group Projects
Groups of 2 to 4 students will design a final project
using python and will all present the working project on Week 11
in front of the class as the final exam. Students will also
hand 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 game
design a conversion tool that converts one format to another
design a GUI for Maya that provides a custom feature
create an interactive website with Google App Engine
use a GUI toolkit like PyQt, PyTk, PyFltk, etc. to create
a nice graphical user interface for a game or tool
write a script that plays another game running in a different
window using AutoIT3 (www.autoitscript.com)
week 6
Midterm Exam
Testing Your Scripts
It 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' that
can be incredibly handy. The contents of the 'assert' must be
true or the script will fail at that point.

def getBoard(pos):
row = ....
assert(row >= 0 and row < len(b))
col = ....
assert(col >= 0 and col < len(b[row]))
return b[row][col]

Sometimes it is beneficial to start with the assertions and then
fill in the rest of the code.
Type checking can be useful when you need to make sure
that 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't
want the script to crash on unexpected input.
Group Project Proposals Due
E-mail the following information to ga3333ai@gmail.com:

1. Names of the 2-4 people in your group
2. The name of your Project
3. Description of the Project
4. Describe how you will present
the project to the class
week 7
Debugging and Troubleshooting
When 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 state
of your program during a run, but sometimes you need a debugger.

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

Python comes with a debugger called 'pdb'.

The typical way to start it is:
python -m pdb myscript.py
glewis@glenn-HP ~/src/ga3333 $ python -m pdb tictactoe.py
> /home/glewis/src/ga3333/tictactoe.py(3)<module>()
-> import random
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(5)<module>()
-> board = range(1,10) # [1,2,3,4,5,6,7,8,9]
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(7)<module>()
-> def printBoard():
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(16)<module>()
-> def possibleMove():
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(25)<module>()
-> def playAgain():
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(34)<module>()
-> def announceWinner(winner):
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(44)<module>()
-> def checkWin():
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(68)<module>()
-> while possibleMove():
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(69)<module>()
-> printBoard()
(Pdb) n

| |
1 | 2 | 3
| |
---|---|---
| |
4 | 5 | 6
| |
---|---|---
| |
7 | 8 | 9
| |
> /home/glewis/src/ga3333/tictactoe.py(70)<module>()
-> print "Your move (1-9,q): ",
(Pdb) n
Your move (1-9,q): > /home/glewis/src/ga3333/tictactoe.py(71)<module>()
-> move = raw_input()
(Pdb) n
1
> /home/glewis/src/ga3333/tictactoe.py(72)<module>()
-> if move == 'q':
(Pdb) p move
'1'
(Pdb) b possibleMove
Breakpoint 1 at /home/glewis/src/ga3333/tictactoe.py:16
(Pdb) c
> /home/glewis/src/ga3333/tictactoe.py(17)possibleMove()
-> moves = []
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(18)possibleMove()
-> for i in range(0,9):
(Pdb) n
> /home/glewis/src/ga3333/tictactoe.py(19)possibleMove()
-> if board[i] != 'X' and board[i] != 'O':
(Pdb)
"next" or "step over"
"print" or examine a variable
set a breakpoint
"continue"
"s" = "step into"
"q" to quit
Week 7 Quiz
"Fixing the bugs"
http://docs.python.org/library/pdb.html
http://codepad.org/KvphQvls
// This python script contains 4 bugs. Fix each bug so that the script runs.

s = 'xLMTIZGFOZGRLMH%@@bLF@SZEV@URCVW@GSV@YFTH*'
xform = ()
xform['%'] = '!'
xform['*'] = '.'
xform['@'] = ' '
for x in range(0,26):
xform[chr(x+97)] = chr(25-x+65)
xform[chr(x+65)] = chr(25-x+97)

out = ''
for c in string:
out = '%s%s' % (out, xform[c])
print out
e-mail corrected script to ga3333ai@gmail.com - worth 20 points
open book - feel free to use the computer to correct the bugs
Homework Week 7
Due: Week 10 - 100 Points
Problem #1: 50 points
Create a GUI in Maya with a table using the grid layout
manager which contains both text graphics. Make the grid
at 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 points
Create a window using Python and the Tkinter module
with a table using a grid layout manager which contains
both 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 10
to ga3333ai@gmail.com
Interesting talk on the future of games
What does this have to do with scripting languages
or 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 download
Fixing the bugs quiz: The Sequel
Open-book quiz - use the computer
This 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!!!

HINT: All white space (indentation) is correct already
http://codepad.org/pDJpZEQO
that is a
capital 'O'
click on 'raw code'
to download
e-mail to
ga3333ai@gmail.com
week 8
Scripting and Animation
particle systems

crowds

renderfarm

automation of repetitive tasks

tools

prototyping

pipeline

physics simulations - pod racers
Scripting vs Compiled Languages
interpreter

virtual machines - JVM (Java), Python, BEAM (Erlang), Dalvik (Android)

byte code vs machine code

developing speed vs execution speed

lines are sometimes blurry

strong typing vs dynamic typing

object-oriented programming, functional programming, stack-based

"live" programming environments - no compile/link/run cycles

garbage collection and high-level languages
Problem-Solving Skills
week 9
Problem-solving skills are important to becoming an effective
programmer.

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

To solve the puzzle, it needs to be broken down into smaller
pieces that can be understood and solved individually so that,
when all the smaller parts have solutions, the bigger problem
is "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

"Teach" (program) the computer how to find
the solution
Full transcript