2014年8月30日 星期六

SundayClass001

7:30~9:00

Chapter 4: Functions
In this chapter you are going to:
• learn about functions
• write your own functions
• create a number guessing game.
Chapter 5: MyEtchASketch
In this chapter you are going to:
• learn how to use the tkinter library
• make your own MyEtchASketch game
• learn how to put an application in its own window
• learn how to attach functions to keyboard presses.





# myEtchASketch application from Coding Club: Python Basics
# Note: the argument 'self' (in early editions of Python Basics) has been replaced by 'event'.  

from tkinter import *

##### Set variables:
canvas_height = 400
canvas_width = 600
canvas_colour = "black"
p1_x=canvas_width/2
p1_y=canvas_height
p1_colour="green"
line_width=5
line_length=5

##### Functions:

# player controls
def p1_move_N(event):
    global p1_y
    canvas.create_line(p1_x, p1_y, p1_x, (p1_y-line_length), width=line_width, fill=p1_colour)
    p1_y = p1_y - line_length

def p1_move_S(event):
    global p1_y
    canvas.create_line(p1_x, p1_y, p1_x, p1_y+line_length, width=line_width, fill=p1_colour)
    p1_y = p1_y + line_length

def p1_move_E(event):
    global p1_x
    canvas.create_line(p1_x, p1_y, p1_x + line_length, p1_y, width=line_width, fill=p1_colour)
    p1_x = p1_x + line_length

def p1_move_W(event):
    global p1_x
    canvas.create_line(p1_x, p1_y, p1_x - line_length, p1_y, width=line_width, fill=p1_colour)
    p1_x = p1_x - line_length

def erase_all(event):
    canvas.delete(ALL)

##### main:
window = Tk()
window.title("MyEtchaSketch")
canvas = Canvas(bg=canvas_colour, height=canvas_height, width=canvas_width, highlightthickness=0)
canvas.pack()

# bind movement to key presses
window.bind("<Up>", p1_move_N)
window.bind("<Down>", p1_move_S)
window.bind("<Left>", p1_move_W)
window.bind("<Right>", p1_move_E)
window.bind("u", erase_all)

window.mainloop()

################################################
################################################
################################################




'''
ryTurtleMouseKeyboard001.py

turtle 之 滑鼠、鍵盤控制。
'''
import random
from turtle import *

s= Screen()
t= Turtle()


def 點s(x,y):
    print('點s()',x,y)
    t.goto(x,y)

def 點t(x,y):
    print('點t()',x,y)
    
def 拖t(x,y):
    print('拖t()',x,y)
    t.goto(x,y)

    
s.onclick(點s)
t.onclick(點t)

#t.ondrag(拖t) # 這行有時會當掉,還有待解決!


def 按a():
    print('按a()')
    t.clear()


def 按b():
    print('按b()')


def 按c():
    print('按c()')


def 按d():
    print('按d()')

    
s.onkeypress(按a,'a')
s.onkeypress(按b,'b')
s.onkeypress(按c,'c')
s.onkeypress(按d,'d')


def 按上():
    t.forward(100)

def 按下():
    t.back(100)

def 按左():
    t.left(90)

def 按右():
    t.right(90)
    
s.onkeypress(按上,'Up')
s.onkeypress(按下,'Down')
s.onkeypress(按左,'Left')
s.onkeypress(按右,'Right')

s.listen()

s.mainloop()

沒有留言:

張貼留言