PYTHON NOTES (drawing.py and drawstuff.py)

Similar documents
PyGame Unit ?

There s already a ton of code written called libraries that we can use by importing. One that we use often is random

pygame Lecture #5 (Examples: fruitgame)

Pygame In a Few Minutes

Pyganim Documentation

pygame Lecture #2 (Examples: movingellipse, bouncingball, planets, bouncingballgravity)

Introduction to Game Programming Lesson 5 Lecture Notes, Part 1: The draw Module

Introduction to Game Programming Lesson 4 Lecture Notes

slide 1 gaius Python Classes you can use theclass keyword to create your own classes here is a tiny example of a class

CS 140 Final Exam Review Problems

CHAPTER 1. Command Arguments Description Example. Prints something to the console. A value can be text in quotes or a variable name.

2 Multimedia Programming with Python and Pygame

Multimedia-Programmierung Übung 5

Multimedia-Programmierung Übung 6

Paint Tutorial (Project #14a)

Video Games. Writing Games with Pygame

Visual C# Program: Simple Game 3

EXCODE. Code An App From Scratch

GETTING STARTED WITH PYGAME ON THE RASPBERRY PI

Programming Fundamentals

PGE Introduction. PGE is a Predictive physics Game Engine it operates by predicting the time of next collision rather than using aframe based approach

Multimedia-Programmierung Übung 7

An Introduction to Processing

Paint/Draw Tools. Foreground color. Free-form select. Select. Eraser/Color Eraser. Fill Color. Color Picker. Magnify. Pencil. Brush.

To specify the dimensions of the drawing canvas use the size statement: ! size( 300, 400 );

GETTING STARTED WITH RASPBERRY PI

CISC 1600 Lecture 3.1 Introduction to Processing

(0,0) (600, 400) CS109. PictureBox and Timer Controls

PyGame Sprites. an excellent turorial exists for PyGame sprites here kai.vm.bytemark.co.uk/ piman/writing/spritetutorial.shtml.

a. Nothing. b. The game will run faster. c. The game will run slower. 5. What does this code do?

Let s Make a Front Panel using FrontCAD

Introduction To Inkscape Creating Custom Graphics For Websites, Displays & Lessons

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Programming Proverbs

W: The LiveWires module

Structured Programming Using C++ Lecture 10 : Graphics Programming with the Dark GDK Library. Dr. Amal Khalifa. Lecture Contents:

How to draw and create shapes

Adobe Illustrator. Quick Start Guide

How to...create a Video VBOX Gauge in Inkscape. So you want to create your own gauge? How about a transparent background for those text elements?

Custom Shapes As Text Frames In Photoshop

Please cite as: PDST, Leaving Certificate Computer Science, Python Workshop, Dublin, 2018

Corel Draw 11. What is Vector Graphics?

Garfield AP CS. Graphics

mith College Computer Science CSC103 How Computers Work Week 7 Fall 2017 Dominique Thiébaut

CSc 110, Autumn 2016 Lecture 7: Graphics. Adapted from slides by Marty Stepp and Stuart Reges

lundi 7 janvier 2002 Blender: tutorial: Building a Castle Page: 1

MathUtilities.randomInt(min, max) function unit conversions, simple drawings

Lab 7: Python Loops and Images 1

Making Games With Python & Pygame By Al Sweigart READ ONLINE

ADOBE TRAINING CS6 PHOTOSHOP BASICS: EDITING PHOTOS & WORKING WITH TEXT - 1

Creating or enlarging a hole in the center of a kaleidoscope (Paint Shop Pro)

This document should only be used with the Apple Macintosh version of Splosh.

Polygons and Angles: Student Guide

Adobe illustrator Introduction

CISC 1600, Lab 2.1: Processing

Shape and Line Tools. tip: Some drawing techniques are so much easier if you use a pressuresensitive

SketchUp Starting Up The first thing you must do is select a template.

JASCO CANVAS PROGRAM OPERATION MANUAL

To get a copy of this image you right click on the image with your mouse and you will get a menu. Scroll down the menu and select "Save Image As".

ACS-1805 Introduction to Programming (with App Inventor)

COMPUTE THE GCD OF TWO NUMBERS. Date: Aim: To compute the GCD of two numbers

Graphics and Java 2D Introduction OBJECTIVES. One picture is worth ten thousand words.


PyGame Overview. (A Tutorial with digressions) A Talk by Neil Muller. 23rd June 2007

Graphics: Legacy Library

""" idea.py simplest possible pygame display demonstrates IDEA / ALTER model Andy Harris, 5/06 """

Sprites and collisions

Technique or Feature Where Introduced

Ancient Cell Phone Tracing an Object and Drawing with Layers

- Is the process of combining texts and graphics layout to produce publications e.g. cards,

Motic Images Plus 3.0 ML Software. Windows OS User Manual

INKSCAPE BASICS. 125 S. Prospect Avenue, Elmhurst, IL (630) elmhurstpubliclibrary.org. Create, Make, and Build

EXAMINATIONS 2016 TRIMESTER 2

5Using Drawings, Pictures. and Graphs. Drawing in ReportSmith. Chapter

Ai Adobe. Illustrator. Creative Cloud Beginner

CSc 110, Spring 2018 Lecture 9: Parameters, Graphics and Random. Adapted from slides by Marty Stepp and Stuart Reges

Practice Written Examination, Fall 2016 Roger B. Dannenberg, instructor

Building Java Programs

Recipes4Success. Draw and Animate a Rocket Ship. Frames 5 - Drawing Tools

Drawing a Circle. 78 Chapter 5. geometry.pyde. def setup(): size(600,600) def draw(): ellipse(200,100,20,20) Listing 5-1: Drawing a circle

append() function, 66 appending, 65, 97, 296 applications (apps; programs), defined, 2, 296

PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY

CISC 1600, Lab 3.1: Processing

Use lists. Use loops. Use conditionals. Define and use functions. Create and use code modules

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM

Building Java Programs

HYPERSTUDIO TOOLS. THE GRAPHIC TOOL Use this tool to select graphics to edit. SPRAY PAINT CAN Scatter lots of tiny dots with this tool.

Using Graphics. Building Java Programs Supplement 3G

Points and lines. x x 1 + y 1. y = mx + b

A Study of Angles & Curves

Kimberly Nguyen Professor Oliehoek Introduction to Programming 8 September 2013

Multimedia-Programmierung Übung 7

Building Java Programs

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

Street Artist Teacher support materials Hour of Code 2017

Introduction to Processing

CMPSCI 119 LAB #2 Greebles / Anime Eyes Professor William T. Verts

CS 101 Computer Science I Fall Instructor Muller. stddraw API. (DRAFT of 1/15/2013)

Self-Teach Exercises: Getting Started Turtle Python

Working with images and scenes

Transcription:

PYTHON NOTES (drawing.py and drawstuff.py) INTRODUCTION TO PROGRAMMING USING PYGAME STEP 1: Importing Modules and Initialization All the Pygame functions that are required to implement features like graphics and sound are stored in the Pygame module and sys module. These modules must be imported into our namespace for us to access the functions inside these modules. To do this, we use the statement: import pygame, sys Note: When we import a module, we gain access to the sub-modules too. Note: There are two formats to import modules: 1. import modulename 2. from modulename import * Normally, when we use import modulename, we can refer to the functions inside by calling modulename.functionname. However, using from modulename import *, we can refer to the function simply by its name without the modulename prefix. The module pygame.locals contains many constant variables. So, to reduce the typing workload, we import pygame.locals in the second format. from pygame.locals import * pygame.init() It is a function call, that is performed before any other Pygame function call. It needs to be called first in order for many other Pygame functions to work. STEP 2: Setting the Window Size DISPLAYSURF = pygame.display.set_mode((700, 500))

The set_mode() function accepts a tuple of two integers as its argument and returns a pygame.surface object for the display window. We pass a tuple value of two integers to the function: (700, 500). This tuple tells the set_mode() function how wide and how high to make the window in pixels. (700, 500) will make a window with a width of 700 pixels and height of 500 pixels. Note: Make sure to pass a sequence, i.e., a tuple of two integer values to the set_mode() function, not two integers. STEP 3: Adding a Window Caption pygame.display.set_caption( Summer Camp on fleek ) This sets the caption text that will appear at the top of the window by calling the pygame.display.set_caption() function. The string value Summer Camp on fleek' is passed in this function call to make that text appear as the caption. STEP 4: Game Loops and Events while True: # main game loop for event in pygame.event.get(): This is a while loop that has a condition of simply the value True. This means that it never exits and the only way the program execution will ever exit the loop is if a break statement is executed or sys.exit() (which terminates the program). If a loop like this was inside a function, a return statement will also move execution out of the loop (as well as the function too). A game loop (also called a main loop) is a loop where the code does three things: 1. Handles events. 2. Updates the game state. 3. Draws the game state to the screen. A game state is just a way of referring to a set of values for all the variables in a game program. Since a game is affected by passage of time or outside events like mouse click or a key press, the program needs to be constantly checked for events and these evets are checked for using the pygame.event.get() function.

STEP 5: Program Termination The QUIT Event and pygame.quit() Function sys.exit() if event.type == QUIT: pygame.quit() This statement checks if the event type is QUIT. If yes, then it calls the pygame.quit() function and sys.exit() to terminate the program. Some Useful Pygame Functions 1. pygame.draw Pygame module to draw shapes: (pygame.draw) Function name pygame.draw.line pygame.draw.circle pygame.draw.rect pygame.draw.ellipse pygame.draw.polygon pygame.draw.arc pygame.draw.lines Functionality Draws a straight line segment Draws a circle around a point Draws a rectangle shape Draws a round shape inside a rectangle Draws a shape with any number of sides Draws a partial section of an ellipse Draws multiple line segments 2. pygame.color Define the colors used in RGB format as follows: COLOR R G B Red 255 0 0 Green 0 255 0 Blue 0 0 255 Black 0 0 0 White 255 255 255

3. pygame.time Function name clock delay get_ticks set_timer wait Functionality To track the time used by a frame Pauses for a given time (returns the number of milliseconds) Time since pygame.time was imported (in ms) Sets the timer for an event (the event then gets placed on an event queue) Pauses for a given time (like delay but less accurate) Example Program: drawstuff.py In this example program, we have the following set up in the file first: # Arup Guha # 7/12/2015 # Drawing using pygame import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((1000, 600)) pygame.display.set_caption("drawing!") black = pygame.color(0,0,0) red = pygame.color(255,0,0) green = pygame.color(0,255,0) pts = [(100,200), (200,200), (300,150), (150,100), (25, 175)] Many pygame programs utilize constant values. Though there are no constants in Python, to be consistent with other programming languages, many people define variables to store constant values. Our intention is to never change the values stored in the variables black, red, green and pts, even though, the compiler would not get mad at us if we did. When we define these constants at the top of the program, we are free to use these names later to refer to the particular objects. There are many reasons to use constants in programs, but one big reason is so the code is easier to read. We haven't seen lists yet, but a list is just a sequence of items. The list pts is a sequence of points, each of which is an ordered pair (technically a tuple).) We will use these points in the program to draw a polygon defined by the points.

This is followed by the basic game loop, which you can just copy for any program where you are drawing a static canvas: while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # Draw on canvas here As previously described, the game loop runs the whole time. The only way to get out of it is if a quit event is generated (clicking away the screen in the top right corner). In short, the while loop runs many, many times, each time, the for loop inside of it goes through each even that recently occurred. If any of these are quitting events, then pygame.quit() and sys.exit() are executed, which stop the program from continuing to run. Most times, there won't be a quit event. In this case, we follow the for loop with our drawing. Thus, what's really happening in a program of this kind is that we're drawing the same static picture over and over again, very fast, so it just looks like a painting. Now, to analyze each of the items drawn. Our first line of code (part of #Draw on canvas here) is: DISPLAYSURF.fill(black) This just initially fills the color of the whole display surface to be black. This is followed by: pygame.draw.ellipse(displaysurf, green, (500, 300, 50, 150), 10) The ellipse function's first parameter is the displaysurface which we have called DISPLAYSURF. The second parameter of this method is the color of the ellipse. This is followed by a 4-tuple that describes the ellipse. The order of the items in the 4-tuple are the x-coordinate and y-coodinate of the center of the ellipse (in pixels) followed by the length of the horizontal axis of the ellipse and the last parameter is the length of the vertical axis of the ellipse. So, this ellipse will be tall and narrow. Finally, the last parameter of the function (for this function call, 10), represents the thickness of the ellipse. The next two lines of code are: pygame.draw.line(displaysurf, red, (500, 0), (500, 550)) pygame.draw.line(displaysurf, pygame.color(255,255,255), (0, 250), (950, 250)) The line function takes in the display surface to write on as its first parameter, followed by the color to draw the line, followed by two 2-tuples, representing the end points of the corresponding segment. This example simply shows two ways of specifying a color. One uses a constant previously set up, the other hard codes in the color directly using the pygame.color function.

This is followed by the following function call that draws a rectangle. As we have in all of the other similar functions, the first two parameters are the display surface and color. The third parameter is a 4-tuple, which indicates the top left corner and bottom right corner, respectively, of the rectangle. This is followed by the width of the rectangle. pygame.draw.rect(displaysurf, pygame.color(95, 12, 183), (50, 200, 700, 50), 10) To draw an arbitrary polygon, the third parameter is simply a list of 2-tuples, where each 2-tuple represents a point on the polygon in the order of tracing the polygon. The last point on this list is connected to the first with a line segment: pygame.draw.polygon(displaysurf, red, pts) Finally, for any of this to show up, we must update the display as follows: pygame.display.update()