Last active
October 19, 2019 23:15
-
-
Save eternaleclipse/36b2312ac8941122acac043142633b7c to your computer and use it in GitHub Desktop.
Pygame acceleration experiment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame, sys, time, numpy as np | |
from pygame.locals import * | |
BACKGROUND_COLOR = (255, 255, 255) | |
CAR_COLOR = (0, 0, 255) | |
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 | |
class Car(object): | |
def __init__(self): | |
self.velocity = np.zeros(2) | |
self.pos = np.zeros(2) | |
self.size = (100, 100) | |
def get_rect(self): | |
return (self.pos[0], self.pos[1], self.size[0], self.size[1]) | |
def update(self, world_rect=None): | |
self.pos += self.velocity | |
if world_rect: | |
min_x, min_y, max_x, max_y = world_rect | |
max_x -= self.size[0] | |
max_y -= self.size[1] | |
self.pos[0] = max(self.pos[0], min_x) | |
self.pos[0] = min(self.pos[0], max_x) | |
self.pos[1] = max(self.pos[1], min_y) | |
self.pos[1] = min(self.pos[1], max_y) | |
if (self.pos[0] == min_x and self.velocity[0] < 0) or (self.pos[0] == max_x and self.velocity[0] > 0): | |
self.velocity[0] = -self.velocity[0] | |
if (self.pos[1] == min_y and self.velocity[1] < 0) or (self.pos[1] == max_y and self.velocity[1] > 0): | |
self.velocity[1] = -self.velocity[1] | |
def main(): | |
pygame.init() | |
car = Car() | |
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) | |
while True: | |
for event in pygame.event.get(): | |
if event.type == QUIT: | |
pygame.quit() | |
sys.exit() | |
pressed = pygame.key.get_pressed() | |
if pressed[K_s]: | |
car.velocity[1] += 0.001 | |
elif pressed[K_w]: | |
car.velocity[1] -= 0.001 | |
if pressed[K_d]: | |
car.velocity[0] += 0.001 | |
elif pressed[K_a]: | |
car.velocity[0] -= 0.001 | |
car.velocity *= 0.9999 | |
car.update((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)) | |
screen.fill(BACKGROUND_COLOR) | |
pygame.draw.rect(screen, CAR_COLOR, car.get_rect()) | |
pygame.display.update() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment