Booza
Booza

Reputation: 126

Make an Image move one space with arrow keys in python / pygame

I am trying to create a game where "player_one.png" is controlled by the arrow keys to move around and dodge a bunch of randomly placed "player_two.png" that can move around on their own in random directions on a football field.

I have created a program that displays the field and the two images. I am having difficulty getting "player_two.png" display multiple copies on the field and cannot get them to move.

I also cannot get the "player_one.png" image to move based on the arrow key. I found a program using Sprites that moves a red block in the same way I want my player to move but cannot switch out the sprite with my image.

Here is my initial set-up which displays the field and the two images facing each other.

import pygame
import random
pygame.init()

#colors
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 100, 0)
red = (255, 0, 0)


size = [1000, 500]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Tony's newest game attempt")


#boolean for while loop
done = False

#create clock 
clock = pygame.time.Clock()

#declare font
font = pygame.font.Font(None, 25)

player_one = pygame.image.load("player_one.png").convert()
player_one.set_colorkey(white)

player_two = pygame.image.load("player_two.png").convert()
player_two.set_colorkey(white)

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


    screen.fill(green)

    for x in range(60,940,35):
        pygame.draw.line(screen, white, [x, 0], [x, 500], 1)


    score = 0
    text = font.render("Score:" +str(score), True, black)

    screen.blit(text, [0, 0])
    screen.blit(player_one, [940, 240])

    screen.blit(player_two, [60, 240])


    pygame.display.flip()

    clock.tick(20)

pygame.quit()

The sprite program that uses a class (something I could not get to work with images) moves the Player sprite using this code: (Please note this is not the entire program).

class Player(pygame.sprite.Sprite):
    # Constructor function
    def __init__(self, color, x, y):
        # Call the parent's constructor
        pygame.sprite.Sprite.__init__(self)

        # Set height, width
        self.image = pygame.Surface([35, 35])
        self.image.fill(color)

        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.x = 930
        self.rect.y = 250

    def reset_player(self):
        self.rect.x = 930
        self.rect.y = 250

    # Find a new position for the player
    def update(self):
        self.rect.x += self.change_y
        self.rect.y += self.change_x

while done == False:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.rect.x -= player.rect.width
            elif event.key == pygame.K_RIGHT:
                player.rect.x += player.rect.width
            elif event.key == pygame.K_UP:
                player.rect.y -= player.rect.height
            elif event.key == pygame.K_DOWN:
                player.rect.y += player.rect.height


    # -- Draw everything
    # Clear screen
    screen.fill(green)

    for x in range(60,940,35):
        pygame.draw.line(screen, white, [x, 0], [x, 500], 1)


    # Draw sprites  
    all_sprites_list.draw(screen)

    text = font.render("Score: "+str(score), True, black)
    screen.blit(text, [10, 10])


    # Flip screen   
    pygame.display.flip()

    # Pause
    clock.tick(20)  

pygame.quit()

Can someone please help me figure out how to get my image to move the way the sprite does. Or help me display "player_two.png" all over the field and move in random directions. It would be best if the "player_two.png" moved every once every 3 times I hit an arrow key. If this is vague please email me and I can send my code. I need to finish this game in 2 weeks!

Upvotes: 1

Views: 8002

Answers (2)

Ayush Gudipati
Ayush Gudipati

Reputation: 63

I think you have the right idea but aren't executing it well.

Try going to your game loop and when displaying an image, display like so:

gameDisplay.blit(player1, (player1X,player1Y))

This way, you can use a if statement to change playerX and player1Y. Insert the following code under the code that quits pygame:

elif e.type == pygame.KEYDOWN:
    if e.key == pygame.K_LEFT:
        player1X -= 5
        pygame.display.update()
     elif e.key == pygame.K_RIGHT:
        player1X += 5
        pygame.display.update()

The reason this works is because the variable that is defining X and Y are not staic. You can also do the same thing for up and down using:

elif e.key == pygame.K_UP:

or

elif e.key == pygame.K_DOWN:

Upvotes: 0

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13372

Multiple comments on the game -

  1. I don't see where self.change_y is defined. Also, shouldn't the update function be like - self.rect.x += self.change_x instead of self.rect.x += self.change_y?

  2. Also, the main loop should be something like this

    while not done:
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done=True
    
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    if player.rect.x > 0:
                        player.rect.x -= player.rect.width
                elif event.key == pygame.K_RIGHT:
                    if player.rect.x < screen_width: # the screen/game width
                        player.rect.x += player.rect.width
                # Something similar for the up & down keys
    

I would recommend you to look at this question.

Upvotes: 3

Related Questions