python习题练习(八)

参考书籍:python程序设计

chapter10.

3.

#This pro let user choose a button and show the result(right or wrong).
from button import Button
from graphics import *
from random import randrange

def drawWin():
    win = GraphWin("Choose a Button", 500, 400)
    win.setBackground('white')
    win.setCoords(0, 0, 10, 9)
    return win

def main():
    #draw the window
    win = drawWin()
    #draw 3 buttons and activate
    button1 = Button(win, Point(2, 6.5), 2, 1.6, "Door1")
    button2 = Button(win, Point(5, 6.5), 2, 1.6, "Door2")
    button3 = Button(win, Point(8, 6.5), 2, 1.6, "Door3")
    button1.activate()
    button2.activate()
    button3.activate()
    #draw the label
    label = Text(Point(5, 2.5), '')
    label.setText('Choose one door.')
    label.draw(win)
    #choose a random num(1-3)
    num = randrange(1, 4)
    #click in one button
    pt = win.getMouse()
    while not(button1.clicked(pt) or button2.clicked(pt) or button3.clicked(pt)):
        pt = win.getMouse()
    #check if which is 
    if (button1.clicked(pt) and num == 1) or (button2.clicked(pt) and num == 2) or (button3.clicked(pt) and num == 3):
        #right
        label.setText("Congratulations!")
    else:
        #wrong
        label.setText("It should be Door{0}.".format(num))
    #deactivate the buttons
    button1.deactivate()
    button2.deactivate()
    button3.deactivate()
    #click to quit
    win.getMouse()
    win.close()

if __name__ == "__main__":
    main()  

4.

#This pro let user choose a button and show the result(right or wrong).
from button import Button
from graphics import *
from random import randrange

def drawWin():
    win = GraphWin("Choose a Button", 500, 400)
    win.setBackground('white')
    win.setCoords(0, 0, 10, 9)
    return win

def main():
    #draw the window
    win = drawWin()
    #draw 3 buttons and activate
    button1 = Button(win, Point(2, 6.5), 2, 1.6, "Door1")
    button2 = Button(win, Point(5, 6.5), 2, 1.6, "Door2")
    button3 = Button(win, Point(8, 6.5), 2, 1.6, "Door3")
    #draw quit button
    quitbutton = Button(win, Point(9, 2.5), 1.6, 1.2, "Quit")
    quitbutton.activate()
    #draw the label
    label = Text(Point(5, 2.5), 'Choose one door.')
    label_ = Text(Point(5, 1.5), '')
    label_win = Text(Point(2.5, 4), '')
    label_lose = Text(Point(7.5, 4), '')
    label.draw(win)
    label_.draw(win)
    label_win.draw(win)
    label_lose.draw(win)
    #count
    num_win = 0
    num_lose = 0
    while True:
        button1.activate()
        button2.activate()
        button3.activate()
        #choose a random num(1-3)
        num = randrange(1, 4)
        #click in one button
        pt = win.getMouse()
        while not (button1.clicked(pt) or button2.clicked(pt) or button3.clicked(pt) or quitbutton.clicked(pt)):
            pt = win.getMouse()
        if quitbutton.clicked(pt): break
        #check if which is 
        if (button1.clicked(pt) and num == 1) or (button2.clicked(pt) and num == 2) or (button3.clicked(pt) and num == 3):
            #right
            num_win += 1
            label_.setText("Congratulations!")
        else:
            #wrong
            num_lose += 1
            label_.setText("It should be Door{0}.".format(num))
        #show win or lose times
        label_win.setText("win: {0}".format(num_win))
        label_lose.setText("lose: {0}".format(num_lose))
        #deactivate the buttons
        button1.deactivate()
        button2.deactivate()
        button3.deactivate()
    #close the win
    win.close()

if __name__ == "__main__":
    main()

8.

#This pro deals with dieview.py
from random import random, randrange
from graphics import *
from button import Button

class DieView:
    """DieView is a widget that displays s graphical representation
    of a standard six-sided die."""

    def __init__(self, win, center, size):
        """Create a view of a die, eg:
            dl = DieView(myWin, Point(40, 50), 20)
        creates a die centered at (40, 50) having sides
        of length 20."""

        #first define some standard values
        self.win = win                  #save this for draw pips later
        self.background = "white"       #color of the dieface
        self.foreground = "black"       #color of the pips
        self.psize = 0.1 * size         #radius of each pip
        hsize = size / 2                #half the size of the die
        offset = hsize * 0.6            #distance from center to outer pips

        #create a square for the face
        cx, cy = center.getX(), center.getY()
        p1 = Point(cx - hsize, cy - hsize)
        p2 = Point(cx + hsize, cy + hsize)
        rect = Rectangle(p1, p2)
        rect.draw(win)
        rect.setFill(self.background)

        #create 7 circles for standard pip locations
        self.pip1 = self.__makePip(cx - offset, cy + offset)
        self.pip2 = self.__makePip(cx - offset, cy)
        self.pip3 = self.__makePip(cx - offset, cy - offset)
        self.pip4 = self.__makePip(cx, cy)
        self.pip5 = self.__makePip(cx + offset, cy + offset)
        self.pip6 = self.__makePip(cx + offset, cy)
        self.pip7 = self.__makePip(cx + offset, cy - offset)

        #Draw an initial value
        self.setValue(1)
        self.setColor('black')

    def __makePip(self, x, y):
        "Internal helper method to draw a pip at (x, y)"
        pip = Circle(Point(x, y), self.psize)
        pip.setFill(self.background)
        pip.setOutline(self.background)
        pip.draw(self.win)
        return pip

    def setValue(self, value):
        #set the value
        self.value = value
        #turn all pips off
        self.pip1.setFill(self.background)
        self.pip2.setFill(self.background)
        self.pip3.setFill(self.background)
        self.pip4.setFill(self.background)
        self.pip5.setFill(self.background)
        self.pip6.setFill(self.background)
        self.pip7.setFill(self.background)

    def setColor(self, color):
        #set a pip's color
        self.foreground = color

        #turn correct pips on
        if self.value == 1:
            self.pip4.setFill(self.foreground)
        elif self.value == 2:
            self.pip1.setFill(self.foreground)
            self.pip7.setFill(self.foreground)
        elif self.value == 3:
            self.pip1.setFill(self.foreground)
            self.pip4.setFill(self.foreground)
            self.pip7.setFill(self.foreground)
        elif self.value == 4:
            self.pip1.setFill(self.foreground)
            self.pip3.setFill(self.foreground)
            self.pip5.setFill(self.foreground)
            self.pip7.setFill(self.foreground)
        elif self.value == 5:
            self.pip1.setFill(self.foreground)
            self.pip3.setFill(self.foreground)
            self.pip4.setFill(self.foreground)
            self.pip5.setFill(self.foreground)
            self.pip7.setFill(self.foreground)
        elif self.value == 6:
            self.pip1.setFill(self.foreground)
            self.pip2.setFill(self.foreground)
            self.pip3.setFill(self.foreground)
            self.pip5.setFill(self.foreground)
            self.pip6.setFill(self.foreground)
            self.pip7.setFill(self.foreground)
        else:
            self.pip1.setFill(self.foreground)
            self.pip2.setFill(self.foreground)
            self.pip3.setFill(self.foreground)
            self.pip4.setFill(self.foreground)
            self.pip5.setFill(self.foreground)
            self.pip6.setFill(self.foreground)
            self.pip7.setFill(self.foreground)

def main():
    #create the application window
    win = GraphWin("Dice Roller", 500, 500)
    win.setCoords(0, 0, 10, 10)
    win.setBackground("white")

    #draw the interface widgets
    die1 = DieView(win, Point(3, 7), 2)
    dei2 = DieView(win, Point(7, 7), 2)
    rollButton = Button(win, Point(5, 4.5), 6, 1, "Roll Dice")
    rollButton.activate()
    quitButton = Button(win, Point(5, 1), 6, 1, "Quit")

    #Even loop
    pt = win.getMouse()
    while not quitButton.clicked(pt):
        r, g, b = random() * 255, random() * 255, random() * 255
        color = color_rgb(int(r), int(g), int(b))
        if rollButton.clicked(pt):
            value1 = randrange(1, 7)
            die1.setValue(value1)
            die1.setColor(color)
            value2 = randrange(1, 7)
            dei2.setValue(value2)
            dei2.setColor(color)
            quitButton.activate()
        pt = win.getMouse()

    #close up shop
    win.close()

if __name__ == "__main__":
    main()

14.

#change the faces when hit the wall
from graphics import *

class Face:

    def __init__(self, window, center, size):
        #win
        self.win = window
        #para
        self.center = center
        self.size = size
        self.eyeSize = 0.15 * self.size
        self.eyeOff = self.size / 3.0
        self.mouthSize = 0.8 * self.size
        self.mouthOff = self.size / 2.0
        p1 = self.center.clone()
        p1.move(-self.mouthSize / 2, -self.mouthOff)
        p2 = self.center.clone()
        p2.move(self.mouthSize / 2, -self.mouthOff)
        #head, eyes, and mouth
        self.head = Circle(self.center, self.size)
        self.head.draw(self.win)
        self.LeftEye = Circle(self.center, self.eyeSize)
        self.LeftEye.move(-self.eyeOff, self.eyeOff)
        self.LeftEye.draw(self.win)
        self.RightEye = Circle(self.center, self.eyeSize)
        self.RightEye.move(self.eyeOff, self.eyeOff)
        self.RightEye.draw(self.win)
        self.mouth = Line(p1, p2)
        self.mouth.draw(self.win)

    def smile(self):
        #left eye
        self.LeftEye.undraw()
        p1 = self.center.clone()
        p1.move(-self.eyeOff, self.eyeOff)
        self.LeftEye = Circle(p1, self.eyeSize)
        self.LeftEye.draw(self.win)
        #right eye
        self.RightEye.undraw()
        p2 = self.center.clone()
        p2.move(self.eyeOff, self.eyeOff)
        self.RightEye = Circle(p2, self.eyeSize)
        self.RightEye.draw(self.win)
        #mouth
        self.mouth.undraw()
        p5 = self.center.clone()
        p6 = self.center.clone()
        p5.move(-self.mouthSize / 2, -self.mouthOff)
        p6.move(self.mouthSize / 2, -self.mouthOff)
        self.mouth = Line(p5, p6)
        self.mouth.draw(self.win)

    def wink(self):
        #left eye
        self.LeftEye.undraw()
        p1 = self.center.clone()
        p2 = self.center.clone()
        p1.move(-(self.eyeOff + self.eyeSize), self.eyeOff)
        p2.move(-(self.eyeOff - self.eyeSize), self.eyeOff)
        self.LeftEye = Line(p1, p2)
        self.LeftEye.draw(self.win)
        #right eye
        self.RightEye.undraw()
        p3 = self.center.clone()
        p4 = self.center.clone()
        p3.move(self.eyeOff - self.eyeSize, self.eyeOff)
        p4.move(self.eyeOff + self.eyeSize, self.eyeOff)
        self.RightEye = Line(p3, p4)
        self.RightEye.draw(self.win)
        #mouth
        self.mouth.undraw()
        p5 = self.center.clone()
        p6 = self.center.clone()
        p5.move(-self.mouthSize / 2, -self.mouthOff)
        p6.move(self.mouthSize / 2, -self.mouthOff)
        self.mouth = Line(p5, p6)
        self.mouth.draw(self.win)

    def frown(self):
        #left eye
        self.LeftEye.undraw()
        p1 = self.center.clone()
        p2 = self.center.clone()
        p1.move(-(self.eyeOff + self.eyeSize), self.eyeOff)
        p2.move(-(self.eyeOff - self.eyeSize), self.eyeOff)
        self.LeftEye = Line(p1, p2)
        self.LeftEye.draw(self.win)
        #right eye
        self.RightEye.undraw()
        p3 = self.center.clone()
        p4 = self.center.clone()
        p3.move(self.eyeOff - self.eyeSize, self.eyeOff)
        p4.move(self.eyeOff + self.eyeSize, self.eyeOff)
        self.RightEye = Line(p3, p4)
        self.RightEye.draw(self.win)
        #mouth
        self.mouth.undraw()
        p5 = self.center.clone()
        p5.move(0, -self.mouthOff)
        self.mouth = Circle(p5, self.eyeSize)
        self.mouth.draw(self.win)

    def flinch(self):
        #left eye
        self.LeftEye.undraw()
        p1 = self.center.clone()
        p1.move(-self.eyeOff, self.eyeOff)
        self.LeftEye = Circle(p1, self.eyeSize)
        self.LeftEye.draw(self.win)
        #right eye
        self.RightEye.undraw()
        p2 = self.center.clone()
        p2.move(self.eyeOff, self.eyeOff)
        self.RightEye = Circle(p2, self.eyeSize)
        self.RightEye.draw(self.win)
        #mouth
        self.mouth.undraw()
        p5 = self.center.clone()
        p5.move(0, -self.mouthOff)
        self.mouth = Circle(p5, self.eyeSize)
        self.mouth.draw(self.win)

    def move(self, dx, dy):
        self.center.move(dx, dy)
        self.head.move(dx, dy)
        self.LeftEye.move(dx, dy)
        self.RightEye.move(dx, dy)
        self.mouth.move(dx, dy)

    def getCenter(self):
        return self.center

    def getSize(self):
        return self.size


def drawCircle(center, size):
    myCircle = Circle(center, size)
    myCircle.setOutline('black')
    myCircle.setWidth(1)
    return myCircle

def drawWin(dx, dy, ux, uy):
    win = GraphWin("Moving", 400, 400)
    win.setBackground('white')
    win.setCoords(dx, dy, ux, uy)
    return win

def main():
    #draw the win
    weight = 100
    height = 100
    win = drawWin(0, 0, weight, height)
    #draw the face
    face = Face(win, Point(50, 50), 10)
    #move the circle
    dx, dy = 1, 1
    for i in range(2000):
        face.move(dx, dy)
        poin = face.getCenter()
        #about x
        if poin.getX() + face.getSize() > weight:
            dx = -1
            face.smile()
        elif poin.getX() - face.getSize() < 0:
            dx = 1
            face.wink()
        #about y
        if poin.getY() + face.getSize() > height:
            dy = -1
            face.frown()
        elif poin.getY() - face.getSize() < 0:
            dy = 1
            face.flinch()
        #update
        update(30) #pause so rate is not more than 30 times a second.
    #click to quit
    print("Click to quit.")
    win.getMouse()
    win.close()

if __name__ == "__main__":
    main()

17.

#deal with regression problems
from graphics import *
class Regression:
    
    def __init__(self, win):
        self.win = win
        self.count = 0
        self.sum_x = 0
        self.sum_y = 0
        self.sum_xx = 0
        self.sum_xy = 0
        self.__drawDone()

    def addPoint(self, pt):
        self.__drawPoint(pt)
        x = pt.getX()
        y = pt.getY()
        self.count += 1
        self.sum_x += x
        self.sum_y += y
        self.sum_xx += x*x
        self.sum_xy += x*y

    def predict(self, x):
        ave_x = self.sum_x / self.count
        ave_y = self.sum_y / self.count
        m = (self.sum_xy - self.count * ave_x * ave_y) / (self.sum_xx - self.count * ave_x * ave_x)
        y = ave_y + m * (x - ave_x)
        return y

    def __drawDone(self):
        #draw the done rectangle
        rec = Rectangle(Point(3, 3), Point(13, 8))
        rec.setWidth(2)
        rec.setOutline('black')
        rec.setFill('white')
        rec.draw(self.win)
        #draw the "done" label
        tex = Text(Point(8, 5.5), "Done")
        tex.setTextColor('black')
        tex.draw(self.win)

    def __drawPoint(self, p):
        #draw the point on the window.
        p.setFill('black')
        p.draw(self.win)

def drawWin():
    #draw a window
    win =  GraphWin("regression line", 500, 500)
    win.setBackground("white")
    win.setCoords(0, 0, 100, 100)
    return win

def isDone(p):
    #return ture if done, otherwise false.
    ##suppose know the boundary of done rectangle.
    return 3 <= p.getX() <= 13 and 3 <= p.getY() <= 8

def drawLine(win, p1, p2):
    line = Line(p1, p2)
    line.setFill('black')
    line.setWidth(2)
    line.draw(win)

def main():
    win = drawWin()
    reg = Regression(win)
    p = win.getMouse()
    while True:
        if isDone(p): break
        reg.addPoint(p)
        p = win.getMouse()
    x0, x1 = 0, 100
    y0 = reg.predict(x0)
    y1 = reg.predict(x1)
    drawLine(win, Point(x0, y0), Point(x1, y1))
    win.getMouse()
    win.close()

if __name__ == "__main__":
    main()

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值