Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_url_img_pong.py
- ### img dl param >>>
- url = r'http://i.imgur.com/ZFkQoE1.png'
- from Tkinter import *
- from PIL import Image, ImageTk
- import urllib
- import io
- root = Tk()
- root.geometry('800x600+0+0')
- imagebytes = urllib.urlopen(url).read()
- imagedata = io.BytesIO(imagebytes)
- imagePIL = Image.open(imagedata)
- img = ImageTk.PhotoImage(imagePIL)
- import time
- import random
- width = 800
- height = 600
- radius = 19
- root.title("Pong")
- vel = [0, 0]
- ballvel = [16, 6]
- maxscore = 0
- score = 0
- canvas = Canvas(root, width=800, height=600)
- canvas.pack()
- ball = canvas.create_image(400, 300, image=img)
- paddle1 = canvas.create_line(0, 0, 0, 100, width=20)
- mid_paddle = int((canvas.coords(paddle1)[3]-canvas.coords(paddle1)[1])/2)
- ms = canvas.create_text(530, 20, text='Highest score = %s' % maxscore)
- s = canvas.create_text(265, 20, text='Score = %s' % score)
- def keypress(event):
- global vel
- acc = 15
- if event.keysym == "Up":
- vel[1] = -acc
- if event.keysym == "Down":
- vel[1] = acc
- def keyrelease(event):
- global vel
- if event.keysym == "Up":
- vel[1] = 0
- if event.keysym == "Down":
- vel[1] = 0
- if event.char == "q":
- vel = False ### to exit
- def new_game():
- canvas.update()
- time.sleep(2)
- global ball, ballvel, score, maxscore
- if maxscore < score:
- maxscore = score
- score = 0
- canvas.delete(ball)
- ball = canvas.create_image(400, 300, image=img)
- ballvel = [16, 6]
- root.bind("<Key>", keypress)
- root.bind("<KeyRelease>", keyrelease)
- while vel:
- time.sleep(0.025)
- canvas.move(ball, ballvel[0], ballvel[1])
- canvas.move(paddle1, vel[0], vel[1])
- if canvas.coords(paddle1)[1] <= 0:
- canvas.coords(paddle1, 0, 0, 0, 100)
- if canvas.coords(paddle1)[3] >= height:
- canvas.coords(paddle1, 0, height - 100, 0, height)
- if canvas.coords(ball)[0] <= radius:
- if canvas.coords(ball)[1] < canvas.coords(paddle1)[1] or canvas.coords(ball)[1] > canvas.coords(paddle1)[3]:
- new_game()
- else:
- umph = random.randrange(2,9)
- redirect = int(((canvas.coords(paddle1)[1]+mid_paddle)-canvas.coords(ball)[1])/umph)*-1
- if redirect < -2 or redirect > 2:
- ballvel[1] = redirect
- ballvel[0] = -ballvel[0]
- if ballvel[0] < 60:
- if ballvel[0] == abs(ballvel[0]):
- ballvel[0] += 1
- else:
- ballvel[0] -= 1
- score += 1
- if canvas.coords(ball)[0] >= width - radius:
- ballvel[0] = -ballvel[0]
- if canvas.coords(ball)[1] <= radius or canvas.coords(ball)[1] >= height - radius:
- ballvel[1] = -ballvel[1]
- canvas.itemconfig(ms, text='Highest score = %s' % maxscore)
- canvas.itemconfig(s, text='Score = %s' % score)
- canvas.update()
- root.destroy()
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement