Can anyone help me modify the code so the ball starts in random directions
phamtony33 at gmail.com
phamtony33 at gmail.com
Fri Dec 11 19:51:11 EST 2015
from Tkinter import *
window = Tk()
canvas = Canvas(window, width=500, height=500, background="green")
canvas.pack()
def mouse_paddle_move(event):
mouseY = event.y
current_coords = canvas.coords("paddle")
x1 = current_coords[0]
y1 = current_coords[1]
x2 = current_coords[2]
y2 = current_coords[3]
height = (y2 - y1)
canvas.coords("paddle", x1, mouseY - (height/2), x2, mouseY + (height/2))
def move_ball(speed_x, speed_y, score):
box = canvas.bbox("ball")
x1 = box[0]
y1 = box[1]
x2 = box[2]
y2 = box[3]
#if ball hits right wall, you lose
if x2 >= 500:
canvas.create_text(250, 250, text="Game Over!")
return # exit function
# if ball hits paddle...
box = canvas.bbox("paddle")
px1 = box[0]
py1 = box[1]
px2 = box[2]
py2 = box[3]
if x2 > px1 and y2 > py1 and y1 < py2:
# bounce with 20% more speed
speed_x = -1.2 * (abs(speed_x))
speed_y = 1.2 * speed_y
# update score
score = score + 1
canvas.itemconfig("score_text", text="Score: " + str(score))
# if ball hits left wall it bounces
if x1 <= 0:
speed_x = -1 * speed_x
# if ball hits top or bottom walls it bounces
if y2 >= 500 or y1 <= 0:
speed_y = -1 * speed_y
canvas.move("ball", speed_x, speed_y)
canvas.after(30, move_ball, speed_x, speed_y, score) # repeat in 30 ms
# create ball, paddle, and score text.
canvas.create_oval(225, 225, 275, 275, fill="blue", tags="ball")
canvas.create_rectangle(450, 200, 455, 300, fill="red", tags="paddle")
canvas.create_text(250, 10, tags = "score_text", text="Score: 0")
# make the ball move 10 pixels left, 7 down, with initial score at 0
move_ball(-10, 7, 0)
# setup mouse handler
canvas.bind('<Motion>', mouse_paddle_move)
mainloop()
More information about the Python-list
mailing list