Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/my2_arcanoid_2lesson.py
5918 views
1
##
2
3
from tkinter import *
4
import time
5
import random
6
7
tk = Tk()
8
tk.title("Игра Арканоид")
9
tk.resizable(0,0)
10
tk.wm_attributes("-topmost",1)
11
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
12
canvas.pack()
13
tk.update()
14
15
class Board:
16
def __init__(self, canvas, color):
17
self.canvas = canvas
18
self.board_width = 150
19
self.id = canvas.create_rectangle(0,0,self.board_width,15,fill=color)
20
21
self.canvas_height = self.canvas.winfo_height()
22
self.canvas_width = self.canvas.winfo_width()
23
24
self.x = 0
25
self.speed_x = 5
26
27
self.xx = self.canvas_width / 2 - self.board_width /2
28
self.yy = self.canvas_height - 40
29
self.canvas.move(self.id, self.xx, self.yy)
30
def move_left(self, event):
31
if self.xx + (-1)*self.speed_x >= 0:
32
self.x = (-1)*self.speed_x
33
self.xx = self.xx + self.x
34
self.draw()
35
#print("left pressed")
36
def move_right(self, event):
37
if self.xx+self.speed_x <= self.canvas_width - self.board_width:
38
self.x = self.speed_x
39
self.xx = self.xx + self.x
40
self.draw()
41
#print("right pressed")
42
def draw(self):
43
self.canvas.move(self.id, self.x, 0)
44
45
class Ball:
46
def __init__(self, canvas, color):
47
self.canvas = canvas
48
self.id = canvas.create_oval(10,10,25,25,fill=color)
49
self.canvas.move(self.id, 250, 150)
50
start = [-3,-2,-1,1,2,3]
51
random.shuffle(start)
52
self.x = start[0]
53
self.y = start[1]
54
self.canvas_height = self.canvas.winfo_height()
55
self.canvas_width = self.canvas.winfo_width()
56
def draw(self):
57
self.canvas.move(self.id, self.x, self.y)
58
pos = self.canvas.coords(self.id)
59
#print(pos)
60
# x1 y1 x2 y2
61
#print(pos[0], pos[1], pos[2], pos[3])
62
63
if pos[1]<=0:
64
#self.y = 1
65
self.y = self.y * (-1)
66
if pos[3]>=self.canvas_height:
67
#self.y = -1
68
self.y = self.y * (-1)
69
70
if pos[0]<=0:
71
#self.x = 1
72
self.x = self.x * (-1)
73
if pos[2]>=self.canvas_width:
74
#self.x = -1
75
self.x = self.x * (-1)
76
77
ball = Ball(canvas, "red")
78
board = Board(canvas, "blue")
79
canvas.bind_all("<KeyPress-Left>",board.move_left)
80
canvas.bind_all("<KeyPress-Right>",board.move_right)
81
82
while 1:
83
ball.draw()
84
tk.update_idletasks()
85
tk.update()
86
time.sleep(0.005)
87
88