This repository has been archived by the owner on May 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
136 lines (117 loc) · 2.93 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
from tkinter import *
import math
import random
w = 800
h = 600
r = x1 = y1 = w / 4
x2 = y2 = h / 4
p1x1 = p1y1 = 20
p1x2 = 30
p1y2 = 200
p1_color = "brown"
p2x1 = w - 30
p2y1 = 20
p2x2 = w - 20
p2y2 = 200
p2_color = "green"
dx = math.cos(60)
dy = math.sin(60)
v = 30
score = {1: 0, 2: 0}
def collision(coords, obj2):
if obj2 in Canevas.find_overlapping(*coords):
return True
else:
return False
def add_score(player, x):
global score
score[player] += 1
if score[1] > score[2]:
label_score.config(
text="Left: %s VS Right: %s" % (score[1], score[2]), fg=p1_color
)
elif score[2] > score[1]:
label_score.config(
text="Left: %s VS Right: %s" % (score[1], score[2]), fg=p2_color
)
else:
pass
def move(event):
global p1x1, p1y1, p1x2, p1y2
global p2x1, p2y1, p2x2, p2y2
global v
key = event.keysym.upper()
if key == "W" and p1y1 > 0:
p1y1 -= v
p1y2 -= v
elif key == "S" and p1y2 < h:
p1y1 += v
p1y2 += v
if key == "UP" and p2y1 > 0:
p2y1 -= v
p2y2 -= v
elif key == "DOWN" and p2y2 < h:
p2y1 += v
p2y2 += v
Canevas.coords(player1, p1x1, p1y1, p1x2, p1y2)
Canevas.coords(player2, p2x1, p2y1, p2x2, p2y2)
def anim():
global x1, x2, y1, y2, r
global dx, dy, v
global w, h
old_coords = (x1, y1, x2, y2)
if x2 + v + v >= w:
add_score(1, 1)
dx = -dx
x1 += v * dx
x2 += v * dx
elif x1 - v - v <= 0:
add_score(2, 1)
dx = -dx
x1 += v * dx
x2 += v * dx
else:
x1 += v * dx
x2 += v * dx
if y1 - v - v <= 0:
dy = -dy
y1 += v * dy
y2 += v * dy
elif y2 + v + v >= h:
dy = -dy
y1 += v * dy
y2 += v * dy
else:
y1 += v * dy
y2 += v * dy
new_coords = (x1, y1, x2, y2)
if collision(new_coords, player1):
x1, y1, x2, y2 = old_coords
dx = -dx
x1 += v * dx
x2 += v * dx
elif collision(
(new_coords[0] - v, new_coords[1], new_coords[2] - v, new_coords[3]), player2
):
x1, y1, x2, y2 = old_coords
dx = -dx
x1 += v * dx
x2 += v * dx
else:
pass
Canevas.coords(ball, x1, y1, x2, y2)
Canevas.after(50, anim)
fen = Tk()
fen.title("Ball 2D by Python Brad")
fen.resizable(False, False)
label_score = Label(text="Left: 0 VS Right: 0")
label_score.pack()
Canevas = Canvas(width=w, height=h)
Canevas.pack()
ball = Canevas.create_oval(x1, y1, x2, y2, fill="red")
player1 = Canevas.create_rectangle(p1x1, p1y1, p1x2, p1y2, fill=p1_color)
player2 = Canevas.create_rectangle(p2x1, p2y1, p2x2, p2y2, fill=p2_color)
Canevas.focus_set()
Canevas.bind("<Key>", move)
anim()
fen.mainloop()