-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy path2_using_object_oriented_programming.py
More file actions
70 lines (51 loc) · 1.63 KB
/
2_using_object_oriented_programming.py
File metadata and controls
70 lines (51 loc) · 1.63 KB
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
# Make it all object oriented by converting the code in various classes
import pygame
from pygame.locals import *
class Snake:
def __init__(self, surface):
self.parent_screen = surface
self.block = pygame.image.load("resources/block.jpg").convert()
self.x = 100
self.y = 100
def move_left(self):
self.x -= 10
self.draw()
def move_right(self):
self.x += 10
self.draw()
def move_up(self):
self.y -= 10
self.draw()
def move_down(self):
self.y += 10
self.draw()
def draw(self):
self.parent_screen.fill((110, 110, 5))
self.parent_screen.blit(self.block, (self.x, self.y))
pygame.display.flip()
class Game:
def __init__(self):
pygame.init()
self.surface = pygame.display.set_mode((500, 500))
self.snake = Snake(self.surface)
self.snake.draw()
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_LEFT:
self.snake.move_left()
if event.key == K_RIGHT:
self.snake.move_right()
if event.key == K_UP:
self.snake.move_up()
if event.key == K_DOWN:
self.snake.move_down()
elif event.type == QUIT:
running = False
if __name__ == "__main__":
game = Game()
game.run()