Player Movement and Boundaries
# basic building blocks
# import
# set game logic
# initialize and run the game
import pygame, time, random
from pygame.locals import *
def main():
#********** game variables **********
quit = False
x = 130
y = 120
#********** start game loop **********
while not quit:
window.fill((0, 0, 0)) # reset screen to black
#********** process events **********
keyspressed = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT:
quit = True
# when player moves from right to left
if keyspressed[ord('a')]:
x = x - 50
# when player moves from left to right
if keyspressed[ord('d')]:
x = x + 50
# when player moves down to up
if keyspressed[ord('w')]:
y = y - 50
# when player moves up to down
if keyspressed[ord('s')]:
y = y + 50
# check if player is inside window boundaries
if y < 0:
y = 0
if y >= window.get_height() - 50:
y = window.get_height() - 50
# restrict player from crossing left and right boundaries
if x < 0:
x = 0
if x >= window.get_width() - 50:
x = window.get_width() - 50
#********** game logic here **********
player = Rect(x, y, 50, 50)
pygame.draw.rect(window, (204, 0, 255), player)
#********** update screen **********
pygame.display.update() # actually does the screen update
clock.tick(30) # run the game at 30 frames per second
#********** initialize & run the game **********
if __name__ == "__main__":
width, height = 800, 600 # set screen width, height
pygame.init() # start graphics system
pygame.mixer.init() # start audio system
window = pygame.display.set_mode((width, height)) # create window
clock = pygame.time.Clock() # create game clock
main()
pygame.quit()