repl.it
@ash15khng/

pygame moving character

Pygame

No description

fork
loading
Files
  • main.py
  • nohup.out
main.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
# imports
import pygame
import random

# init + variables

pygame.init()

screen_size = (800, 600)
screen = pygame.display.set_mode(screen_size)
font = pygame.font.Font(None, 20)

bgcolor = (255, 255, 255)  # white

# classes


class Player(pygame.Rect):
    size = (30, 30)
    keys = pygame.key.get_pressed()

    def __init__(self):
        self.location = [0, 0]

    def draw(self):
        pygame.draw.rect(screen, (255, 0, 0), (self.location, self.size))

    def check_move(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            player.location[0] -= 10
            print("LEFT")
        if keys[pygame.K_RIGHT]:
            player.location[0] += 10
            print("RIGHT")
        if keys[pygame.K_UP]:
            player.location[1] -= 10
            print("UP")
        if keys[pygame.K_DOWN]:
            player.location[1] += 10
            print("DOWN")
        if player.location[0] < 0:
            player.location[0] = 0
        if player.location[1] < 0:
            player.location[1] = 0
        if player.location[0] > screen_size[0]:
            player.location[0] = screen_size[0]
        if player.location[1] > screen_size[1]:
            player.location[1] = screen_size[1]

    def collided(self, enemy):
        a = abs(self.location[0] - enemy.location[0])
        b = abs(self.location[1] - enemy.location[1])
        return (a ** 2 + b ** 2) ** 0.5 > self.size[0] + enemy.size[0]


class Enemy(pygame.Rect):

    speed = 5

    def __init__(self, size):
        self.location = [screen_size[0], random.randint(1, screen_size[1])]
        self.size = size

    def draw(self):
        temp = self.location[0]-self.size[0], self.location[1]-self.size[1]
        pygame.draw.rect(screen, (0, 0, 255), (temp, self.size))

    def update_location(self):
        self.location[0] -= self.speed


player = Player()
enemies = [Enemy([30, 30]), Enemy([30, 30])]

game = True
dodged = 0

while game:
    pygame.time.delay(100)  # game runs 1000/parameter times a second
    screen.fill(bgcolor)  # fill screen (white)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break

    player.check_move()
    player.draw()

    for enemy in enemies:
        enemy.draw()
        enemy.update_location()
        if player.collided(enemy):
            print("collided")
            # game = False
        # if enemy.location[0] == 0:
        #     dodged += 1
        #     print(dodged)
        #     enemies.append(Enemy([30, 30]))

print("game over")