Search code examples
pythonpygamearrow-keys

Problems making pygame target image (scope) move with arrow keys


When we run our pygame's code, our target scope image will NOT move, but our do robots generate. We are trying to use our arrow keys to move them and I included all of our code.

Commented out under our newest trial code for moving are two other things we tried.

import pygame, sys  
from graphics import *  
import time  
import random  

pygame.init()  

level=1  
bg = pygame.image.load('bg.png')  
bg_width = 800  
pygame.display.set_caption('Robot Apocalypse')  
surfacew = 1054  
surfacel = 562  
surface = pygame.display.set_mode((surfacew,surfacel))  
black = (0, 0, 0)  
score = 0  
#player_health = 99  
alive=True  

targetImg = pygame.image.load('target.png')  
targetImg = pygame.transform.scale(targetImg, (40, 40))  
targetxy = targetImg.get_rect()  
targetx = targetxy[0]  
targety = targetxy[1]  

def move_target(targetImg):  
    pygame.event.clear()  
    while alive == True:  
        keys_pressed = pygame.key.get_pressed()  
        if keys_pressed[pygame.K_LEFT]:  
            targetx -= 5  
        if keys_pressed[pygame.K_RIGHT]:  
            targetx += 5  
        if keys_pressed[pygame.K_UP]:  
            targety -= 5  
        if keys_pressed[pygame.K_DOWN]:  
            targety += 5  
        pygame.display.update()  
    # pygame.event.clear()  
    # for event in pygame.event.get():  
    #     if event.type ==KEYDOWN:  
    #         if event.key == K_LEFT:  
    #             direction = MOVE_LEFT  
    #         elif event.key == K_RIGHT:  
    #             direction = MOVE_RIGHT  
    #     elif event.type == KEYUP:  
    #         if event.key == K_LEFT:  
    #             direction = 0  
    #         elif event.key == K_RIGHT:  
    #             direction = 0  
    # if(direction == MOVE_LEFT):  
    #     targetx-=10  
    # elif(direction == MOVE_RIGHT):  
    #     targetx+=10  

    # for event in pygame.event.get():  
    #     print(event)  
    #     if event.type==QUIT:  
    #          pygame.quit()  
    #          sys.exit()  
    #     if event.type == KEYDOWN:  
    #         if event.key == K_LEFT:  
    #             targetx-=5  
    #         elif event.key == K_RIGHT:  
    #             targetx+=5  
    #         elif event.key == K_UP:  
    #             targety-=5  
    #         elif event.key == K_DOWN:  
    #             targety+=5  
    #     pygame.display.update()  

def shoot():  
    #while True:  
    shot = False  

    pos = (targetx, targety)  
    t = screen.blit(robot, (64,64))  
    if t.collidepoint(pos):  
        shot = True  
    return shot  

def generate_robot(x,y):  
    #while displayrobot == True  
    robot=pygame.draw.rect(surface, (255,0,0), (x,y,64,64), 0)  
    for event in pygame.event.get():  
        if event.type == pygame.KEYDOWN:  
            if event.key == pygame.K_SPACE:  
                shoot()  
                if shot == True:  
                    displayrobot = False  
                    cover = surface.blit(bg, (x,y))  
                    pygame.display.update()  
    return x, y  

    #if shot == True:  

def die():  
    message("YOU DIED")  
    pygame.display.update()  

def win(level):  
    level+=1  

def text_objects(text, font):  
    textSurface = font.render(text, True, black)  
    return textSurface, textSurface.get_rect()  

def message(text):  
    largeText = pygame.font.Font('freesansbold.ttf',60)  
    TextSurf, TextRect = text_objects(text, largeText)  
    TextRect.center = ((surfacew/6),(surfacel/2))  
    surface.blit(TextSurf, TextRect)  
    pygame.display.update()  
    time.sleep(2)  

def main(alive):  
    #displayrobot = True:  
    robot=0  
    score=0  
    surface.fill(black)  
    surface.blit(bg, (0,0))  
    message("Level "+ str(level))  
    mouse = pygame.mouse.get_pos()  
    target = surface.blit(targetImg, (mouse))  
    while alive==True:  
        # robot = enemy(64, 64)  
        x=random.randint(40,760)  
        y=random.randint(40,560)  
        generate_robot(x,y)  
        pygame.display.update()  
        robot+=1  
        time.sleep(8/level)  
    if robot>50 and robot>score:  
        alive=False  
    # if pygame.mouse.get_pressed()==True:  
    #     shoot() #maybe??  
        if shot==True:  
            score+=1  
            robot-=1  
        if robot==10/(level/2): #if 10- robots on screen then...  
            die()  
        if score>25*(level/2):  
            win()  
move_target(targetImg)
main(alive)  
pygame.quit()  
quit()  

. There are no error messages, but it won't move. We've tried a ton of different things (that aren't included) and looked up a lot of websites so please help us. Thanks


Solution

  • To move object you have to not only change x,y and update screen (send buffer to video card which will display it) but also clean buffer, draw image in new place in buffer (blit()).

    This code shows only working move_target. I skiped rest of code.

    I keep position in target_rect which is pygame.Rect. You can use it to blit(img,rect) but later you can also use to check collision rect.colliderect(other_rect)

    import pygame
    
    # --- constants --- (UPPER_CASE_NAMES)
    
    BLACK = (0, 0, 0)  
    
    SURFACE_WIDTH = 1054  
    SURFACE_HEIGHT = 562  
    
    # --- functions --- (lower_case_names)
    
    def move_target(target_img, target_rect):
        alive = True  
        clock = pygame.time.Clock()
        while alive:
    
            # --- events ---
    
            for event in pygame.event.get():  
                if event.type == pygame.QUIT:  
                    alive = False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        alive = False
    
            # --- updates/changes ---
    
            keys_pressed = pygame.key.get_pressed()  
    
            if keys_pressed[pygame.K_LEFT]:  
                target_rect.x -= 5  
            if keys_pressed[pygame.K_RIGHT]:  
                target_rect.x += 5  
            if keys_pressed[pygame.K_UP]:  
                target_rect.y -= 5  
            if keys_pressed[pygame.K_DOWN]:  
                target_rect.y += 5
    
            # --- draws ---
    
            surface.fill(BLACK)
            surface.blit(target_img, target_rect)
            pygame.display.update()
    
            # the same game's speed on all computers = 60 FPS
            clock.tick(60)
    
    # --- main --- (lower_case_names)
    
    pygame.init()  
    
    pygame.display.set_caption('Robot Apocalypse')  
    surface = pygame.display.set_mode((SURFACE_WIDTH, SURFACE_HEIGHT))  
    
    target_img = pygame.image.load('target.png')  
    target_img = pygame.transform.scale(target_img, (40, 40))  
    target_rect = target_img.get_rect()  
    
    move_target(target_img, target_rect)
    
    pygame.quit()