Python做的弹球游戏

nr0728 2021-10-27 17:47:44 2021-10-27 17:50:22 3

代码:

    from random import random,choice

    from turtle import *

    import time

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

    player=[0,-140]

    ball=[0,140]

    direction=[choice([-2,-1,1,2]),choice([-2,-1])]

    gameover=False

    ###############################################
    
    def move(aim):
        player[0]+=aim

    def bounce():
        if(ball[0]<=-300 or ball[0]>=290):
            direction[0]*=-1
        elif(ball[1]>=150):
            direction[1]*=-1
        elif(ball[1]<=-140+10+5 and player[0]<=ball[0]<=player[0]+70):
            direction[1]*=-1

    def outside():
        if(ball[1]<=-140):
            return True
        else:
            return False

    def rectangle(x,y,w,h):
        up()
        goto(x,y)
        begin_fill()
        for i in range(2):
            forward(w)
            left(90)
            forward(h)
            left(90)
        end_fill()

    def draw():
        clear()
        up()
        goto(ball[0],ball[1])
        dot(10,'red')
        rectangle(player[0],player[1],70,10)
        update()

    def gameLoop():
        bounce()
        ball[0]+=direction[0]*3
        ball[1]+=direction[1]*3
        draw()
        if(outside()):
            gameover=True
            return
        ontimer(gameLoop,50)

    ###############################################
    setup(620,320,0,0)
    hideturtle()
    tracer(False)
    listen()
    onkey(lambda:move(20),'-')
    onkey(lambda:move(-20),'+')
    startTime=time.time()
    gameLoop()
    if(gameover):
        endTime=time.time()
        totalTime=int(endTime-startTime)
        time.sleep(2)
        hideturtle()
        home()
        write("GAME OVER",align="center",font=("Comic Sans MS",50,"bold"))
        goto(310,230)
        write("Time:{} seconds.".format(totalTime),align='center',font=("Comic Sans MS",50,"bold"))
        time.sleep(2)

    done()
{{ vote && vote.total.up }}