用户:
WP40查看:0 回复:1 评论:0 创建时间:2022-04-05T19:46:37
from tkinter import *
import random
import time
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.ide = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.ide, 245, 100)
starts = [-3, -2, -1, 1, 2, 3]
random.shuffle(starts)
self.x = starts[0]
self.y = -2
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
def draw(self):
self.canvas.move(self.ide, self.x, self.y)
pos = self.canvas.coords(self.ide)
if pos[1] <= 0:
self.y = 1
if pos[3] >= self.canvas_height:
self.y = -1
if pos[0] <= 0:
self.x = 2
if pos[2] >= self.canvas_width:
self.x = -2
class Papp:
def __init__(self, canvas, color):
self.canvas = canvas
self.ide = canvas.create_rectangle(0, 0, 100, 10, fill=color)
self.canvas.move(self.ide, 200, 300)
self.x = 0
self.canvas_width = self.canvas.winfo_width()
self.canvas.bind_all('<KeyPress-Left>', self.left_p)
self.canvas.bind_all('<KeyPress-Right>', self.right_p)
def draw(self):
self.canvas.move(self.ide, self.x, 0)
pos = self.canvas.coords(self.ide)
if pos[0] <= 0:
self.x = 0
elif pos[2] >= self.canvas_width:
self.x = 0
def left_p(self, evt):
self.x = -2
def right_p(self, evt):
self.x = 2
root = Tk()
root.title("game")
root.resizable(0, 0)
root.wm_attributes("-topmost", 1)
canvas = Canvas(width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
canvas.update()
paddle = Papp(canvas, 'blue')
ball = Ball(canvas, 'red')
while 1:
ball.draw()
root.update_idletasks()
root.update()
time.sleep(0.01)