Ответы
import tkinter as tk
import random
class Pong:
def __init__(self, master):
self.master = master
self.master.title("Pong")
self.master.geometry("400x300")
self.master.configure(bg='black')
self.master.resizable(False, False)
self.canvas = tk.Canvas(self.master, width=400, height=300, bg='black')
self.canvas.pack()
self.paddle1_x = 20
self.paddle1_y = 125
self.paddle2_x = 375
self.paddle2_y = 125
self.paddle_width = 10
self.paddle_height = 50
self.ball_x = 200
self.ball_y = 150
self.ball_size = 10
self.ball_speed = 5
self.ball_x_speed = random.choice([-5, 5])
self.ball_y_speed = random.choice([-5, 5])
self.paddle1 = self.canvas.create_rectangle(self.paddle1_x, self.paddle1_y,
self.paddle1_x + self.paddle_width,
self.paddle1_y + self.paddle_height,
fill='white')
self.paddle2 = self.canvas.create_rectangle(self.paddle2_x, self.paddle2_y,
self.paddle2_x + self.paddle_width,
self.paddle2_y + self.paddle_height,
fill='white')
self.ball = self.canvas.create_oval(self.ball_x, self.ball_y,
self.ball_x + self.ball_size,
self.ball_y + self.ball_size,
fill='white')
self.master.bind("<Up>", self.move_paddle1_up)
self.master.bind("<Down>", self.move_paddle1_down)
self.master.bind("<w>", self.move_paddle2_up)
self.master.bind("<s>", self.move_paddle2_down)
self.move_ball()
def move_paddle1_up(self, event):
self.paddle1_y -= 10
self.canvas.coords(self.paddle1, self.paddle1_x, self.paddle1_y,
self.paddle1_x + self.paddle_width,
self.paddle1_y + self.paddle_height)
def move_paddle1_down(self, event):
self.paddle1_y += 10
self.canvas.coords(self.paddle1, self.paddle1_x, self.paddle1_y,
self.paddle1_x + self.paddle_width,
self.paddle1_y + self.paddle_height)
def move_paddle2_up(self, event):
self.paddle2_y -= 10
self.canvas.coords(self.paddle2, self.paddle2_x, self.paddle2_y,
self.paddle2_x + self.paddle_width,
self.paddle2_y + self.paddle_height)
def move_paddle2_down(self, event):
self.paddle2_y += 10
self.canvas.coords(self.paddle2, self.paddle2_x, self.paddle2_y,
self.paddle2_x + self.paddle_width,
self.paddle2_y + self.paddle_height)
def move_ball(self):
self.ball_x += self.ball_x_speed
self.ball_y += self.ball_y_speed
self.canvas.coords(self.ball, self.ball_x, self.ball_y, self.ball_x + self.ball_size,
self.ball_y + self.ball_size)
if self.ball_x <= 0:
self.ball_x_speed = self.ball_speed
if self.ball_x >= 400 - self.ball_size:
self.ball_x_speed = -self.ball_speed
if self.ball_y <= 0:
self.ball_y_speed = self.ball_speed
if self.ball_y >= 300 - self.ball_size:
self.ball_y_speed = -self.ball_speed
if self.ball_x <= self.paddle1_x + self.paddle_width and self.ball_y in range(self.paddle1_y,
self.paddle1_y + self.paddle_height):
self.ball_x_speed = self.ball_speed
if self.ball_x >= self.paddle2_x - self.ball_size and self.ball_y in range(self.paddle2_y,
self.paddle2_y + self.paddle_height):
self.ball_x_speed = -self.ball_speed
self.master.after(20, self.move_ball)
root = tk.Tk()
game = Pong(root)
root.mainloop()