<s>[INST] import pygame
import sys
import random

pygame.init()
screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()

class Character:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.image = pygame.Surface((50,50))
        self.image.fill((random.randint(0,255),random.randint(0,255),random.randint(0,255)))

    def draw(self,screen):
        screen.blit(self.image,(self.x,self.y))

def main():
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        screen.fill((0,0,0))
        char = Character(375,275)
        char.draw(screen)
        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()

main()

This code creates a window with a random colored square. What I want to do is allow the player to move the square with the arrow keys. Here is the modified code:

import pygame
import sys
import random

pygame.init()
screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()

class Character:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.image = pygame.Surface((50,50))
        self.image.fill((random.randint(0,255),random.randint(0,255),random.randint(0,255)))
        self.speed = 3

    def draw(self,screen):
        screen.blit(self.image,(self.x,self.y))

    def move(self,dx,dy):
        self.x += dx * self.speed
        self.y += dy * self.speed

def main():
    running = True
    char = Character(375,275)
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            char.move(0,-1)
        if keys[pygame.K_DOWN]:
            char.move(0,1)
        if keys[pygame.K_LEFT]:
            char.move(-1,0)
        if keys[pygame.K_RIGHT]:
            char.move(1,0)

        screen.fill((0,0,0))
        char.draw(screen)
        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()

main()

The problem with this code is that the square moves off the screen if you press a key for too long. How can I prevent this from happening?[/INST]