Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import pygame
- pygame.init()
- screen_width = 640
- screen_height = 480
- screen = pygame.display.set_mode((screen_width, screen_height))
- screen_rect = screen.get_rect()
- clock = pygame.time.Clock()
- fps = 30
- class Character(object):
- def __init__(self, surface, accel, gravity):
- self.surface = surface
- self.accel = accel
- self.gravity = gravity
- self.vel = (0, 0)
- self.pos = ((screen_width / 2),(screen_height / 2))
- self.size = (10, 10)
- def move_right(self):
- self.vel = (self.vel[0] + self.accel, self.vel[1])
- self.pos = (self.pos[0] + self.vel[0],self.pos[1])
- def move_left(self):
- self.vel = (self.vel[0] - self.accel, self.vel[1])
- self.pos = (self.pos[0] + self.vel[0],self.pos[1])
- def move_up(self):
- self.vel = (self.vel[0], self.vel[1] - self.accel)
- self.pos = (self.pos[0],self.pos[1] + self.vel[1])
- def move_down(self):
- self.vel = (self.vel[0], self.vel[1] + self.accel)
- self.pos = (self.pos[0],self.pos[1] + self.vel[1])
- def move(self):
- keys = pygame.key.get_pressed()
- if keys[pygame.K_w]:
- self.move_up()
- if keys[pygame.K_a]:
- self.move_left()
- if keys[pygame.K_s]:
- self.move_down()
- if keys[pygame.K_d]:
- self.move_right()
- if self.pos[0] <= 0 or self.pos[0] >= screen_width:
- self.vel = (self.vel[0] * -1, self.vel[1])
- if self.pos[1] <= 0 or self.pos[1] >= screen_height:
- self.vel = (self.vel[0], self.vel[1] * -1)
- self.character = pygame.Rect((self.pos[0], self.pos[1]), self.size)
- self.character.clamp_ip(screen_rect)
- def display(self):
- pygame.draw.rect(self.surface, (255, 255, 255), self.character)
- def reset(self):
- (x_pos, y_pos) = pygame.mouse.get_pos()
- self.pos = (x_pos, self.pos[1])
- self.pos = (self.pos[0], y_pos)
- self.x_vel = 0
- self.y_vel = 0
- class Gravity(Character):
- def __init__(self, accel_due_to_grav):
- self.accel_due_to_grav = accel_due_to_grav
- def active(self):
- timestep = 1/fps # or something else to your liking
- self.vel = (self.vel[0], self.vel[1] + self.accel_due_to_grav * timestep)
- self.pos = (self[0], self.vel[1] * timestep)
- self.pos = (self.pos[0], self.pos[1] + 0.5* self.accel_due_to_grav * timestep**2)
- def main():
- player1 = Character(screen, 10, .5)
- while True:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- sys.exit()
- elif event.type == pygame.MOUSEBUTTONDOWN:
- player1.reset()
- player1.move()
- screen.fill((0, 0, 0))
- player1.display()
- pygame.display.update(screen_rect)
- clock.tick(fps)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement