|
| 1 | +## python -m pip install pygame |
| 2 | +from math import radians, sin, cos |
| 3 | +import pygame |
| 4 | +import sys |
| 5 | + |
| 6 | +###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 7 | +class Config: |
| 8 | + W, H = 500, 500 |
| 9 | + |
| 10 | + |
| 11 | +img = pygame.image.load(sys.path[0] + "/tank.png") |
| 12 | + |
| 13 | + |
| 14 | +###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 15 | +class Player: |
| 16 | + x, y = Config.W // 2, Config.H // 2 |
| 17 | + x_movement, y_movement = 8, 8 |
| 18 | + radius = 10 |
| 19 | + color = (255, 255, 255) |
| 20 | + angle = 0 |
| 21 | + rotate_speed = 10 |
| 22 | + |
| 23 | + def move_up(self): |
| 24 | + self.y -= self.y_movement |
| 25 | + self.update_rotation(0) |
| 26 | + |
| 27 | + def move_down(self): |
| 28 | + self.y += self.y_movement |
| 29 | + self.update_rotation(180) |
| 30 | + |
| 31 | + def move_left(self): |
| 32 | + self.x -= self.x_movement |
| 33 | + self.update_rotation(90) |
| 34 | + |
| 35 | + def move_right(self): |
| 36 | + self.x += self.x_movement |
| 37 | + self.update_rotation(270) |
| 38 | + |
| 39 | + def update_rotation(self,deg): |
| 40 | + if self.angle>360: |
| 41 | + self.angle-=360 |
| 42 | + |
| 43 | + if self.angle<deg: |
| 44 | + self.angle+=self.rotate_speed |
| 45 | + elif self.angle>deg: |
| 46 | + self.angle-=self.rotate_speed |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + def draw(self, screen): |
| 51 | + tank = pygame.transform.rotate(img, self.angle) |
| 52 | + size = tank.get_rect().size |
| 53 | + screen.blit(tank, (player.x - size[0] // 2, player.y - size[1] // 2)) |
| 54 | + |
| 55 | + pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius) |
| 56 | + |
| 57 | + nx, ny = ( |
| 58 | + self.x + self.radius * sin(radians(self.angle)), |
| 59 | + self.y + self.radius * cos(radians(self.angle)), |
| 60 | + ) |
| 61 | + pygame.draw.circle(screen, self.color, (nx, ny), self.radius // 2) |
| 62 | + |
| 63 | + |
| 64 | +player = Player() |
| 65 | + |
| 66 | + |
| 67 | +###~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 68 | +screen = pygame.display.set_mode((Config.W, Config.H)) |
| 69 | +pygame.display.set_caption("Tank Game") |
| 70 | +clock = pygame.time.Clock() |
| 71 | + |
| 72 | +done = False |
| 73 | +while not done: |
| 74 | + for event in pygame.event.get(): |
| 75 | + if event.type == pygame.QUIT: |
| 76 | + done = True |
| 77 | + |
| 78 | + keys = pygame.key.get_pressed() |
| 79 | + |
| 80 | + if keys[pygame.K_LEFT]: |
| 81 | + player.move_left() |
| 82 | + |
| 83 | + if keys[pygame.K_RIGHT]: |
| 84 | + player.move_right() |
| 85 | + |
| 86 | + if keys[pygame.K_UP]: |
| 87 | + player.move_up() |
| 88 | + |
| 89 | + if keys[pygame.K_DOWN]: |
| 90 | + player.move_down() |
| 91 | + |
| 92 | + clock.tick(60) |
| 93 | + screen.fill((30, 30, 30)) |
| 94 | + player.draw(screen) |
| 95 | + pygame.display.update() |
0 commit comments