Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import *
- from random import randrange
- ### DEFS
- # directions
- def move_ball_right_down():
- global x, y, dx, dy
- x, y = x + dx, y + dy
- can.coords(ball, x-r, y-r, x+r, y+r)
- def move_ball_left_up():
- global x, y, dx, dy
- x, y = x - dx, y - dy
- can.coords(ball, x-r, y-r, x+r, y+r)
- def move_ball():
- global flag, x, y, moving
- if moving == True:
- move_ball_right_down()
- if moving == False:
- move_ball_left_up()
- if x <= 20 or y <= 20:
- moving = True
- if x >= 480 or y >= 480:
- moving = False
- if flag > 0:
- win.after(50, move_ball)
- def click_ball(event):
- global x, y, points, ball, r, dx, flag
- if flag == 1 and\
- event.x <= x + r and event.x >= x - r and\
- event.y <= y + r and event.y >= y - r:
- points = points + 1
- lab2.configure(text = "Points: " + str(points))
- r = r - 1
- dx = dx + 1
- can.coords(ball, x-r, y-r, x+r, y+r)
- pal = ["red", "green", "white", "blue", "black", "yellow", "magenta"]
- m = randrange(7)
- color = pal[m]
- can.itemconfig(ball, fill = color)
- if points == 15:
- lab2.configure(text = "Points: " + str(points) + " - You won!", fg = "green")
- flag = 0
- def start(): # start the game
- global flag
- if flag == 0 and points < 15:
- flag = 1
- move_ball()
- def pause(): # pause the game
- global flag
- flag = 0
- def restart():
- global points, r, x, y, flag, dx
- x, y = 250, 250
- r = 20
- points = 0
- dx, dy = 10, 10
- moving = True
- can.coords(ball, x-r, y-r, x+r, y+r)
- can.itemconfig(ball, fill = "red")
- lab2.configure(text = "Points: " + str(points))
- if flag == 0:
- flag = 1
- move_ball()
- ### VARS
- x, y = 250, 250
- dx, dy = 10, 10
- r = 20
- flag = 0
- moving = True
- points = 0
- ### GUI
- # create a WINDOW
- win = Tk()
- win.title("Clicky game")
- # create a CANVAS
- can = Canvas(win, height = 500, width = 500, bg = "light grey")
- can.grid(row = 3, column = 1, columnspan = 3, sticky = N)
- can.bind("<Button-1>", click_ball)
- # create LABELS
- lab = Label(win, text = "Click on the 'Start' button, than catch the ball!")
- lab.grid(row = 1, column = 2, sticky = N, pady = 2)
- lab2 = Label(win, text = "Points: 0", fg = "red")
- lab2.grid(row = 2, column = 2, sticky = N, pady = 2)
- # add a BALL
- ball = can.create_oval(x-r, y-r, x+r, y+r, fill = "red")
- # create BUTTONS
- but1 = Button(win, text = "Quit", command = win.destroy)
- but1.grid(row = 4, column = 3, sticky = E, padx = 5, pady = 5)
- but2 = Button(win, text = "Start", command = start)
- but2.grid(row = 4, column = 1, sticky = W, padx = 10, pady = 5)
- but3 = Button(win, text = "Pause", command = pause)
- but3.grid(row = 4, column = 1, sticky = E, padx = 10, pady = 5)
- but4 = Button(win, text = "Restart", command = restart)
- but4.grid(row = 4, column = 2, sticky = W, padx = 10, pady = 5)
- win.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment