How to move a picture this pygame program? - python

I've got the code below, the image ain't moving. Please tell me what's wrong so I can fix it real quick. Also, try to keep the answers short and to the point.
I can hear the music and all, the escape button and the quit is working too, directional keys are not.
PlayerImage = pygame.image.load("ch.jpg")
Player = pygame.Rect(675, 350, 40, 4)
StretchPlayer = pygame.transform.scale(PlayerImage, (40, 40))
goLeft = False
goRight = False
goUp = False
goDown = False
Velocity = 3
EatSound = pygame.mixer.Sound("sound.wav")
pygame.mixer.music.load("X.mp3")
pygame.mixer.music.play(-1, 0.0)
musicPlaying = True
while True :
for event in pygame.event.get() :
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('A'):
goRight = False
goLeft = True
if event.key == pygame.K_RIGHT or event.key == ord('D'):
goRight = True
goLeft = False
if event.key == pygame.K_UP or event.key == ord('W'):
goUp = True
goDown = False
if event.key == pygame.K_DOWN or event.key == ord('S'):
goUp = False
goDown = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_LEFT or event.key == ord('A'):
goLeft = False
if event.key == pygame.K_RIGHT or event.key == ord('D'):
goRight = False
if event.key == pygame.K_UP or event.key == ord('W'):
goUp = False
if event.key == pygame.K_DOWN or event.key == ord('S'):
goDown = False
DisplayScreen.blit(StretchPlayer, Player)
pygame.display.update()

Just change the location of the rectangle Player dependent on goLeft, goRight, goUp and goDown, e.g. by .move:
dx = -1 if goLeft else 1 if goRight else 0
dy = -1 if goUp else 1 if goDown else 0
Player = Player.move(dx, dy)
DisplayScreen.blit(StretchPlayer, Player)

Related

name 'event' is not defined not sure why im getting this

class GameState():
def init(self):
self.state = 'main_game'
def main_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN: # this is where the error comes from
mouse_state = 1
pygame.mouse.set_pos(mouse_x,mouse_y + 1)
else:
mouse_state = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
snake.yV = 0
snake.xV = -1
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
snake.yV = 0
snake.xV = 1
if event.key == pygame.K_UP or event.key == pygame.K_w:
snake.xV = 0
snake.yV = -1
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
snake.xV = 0
snake.yV = 1
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
pygame.display.set_caption("Snake, FPS: " + str(clock.get_fps()))
screen.fill(GREY)
snake.update()
food.update()
utility.update()
bombs.update()
food.draw()
snake.draw()
utility.draw()
bombs.draw()
pygame.display.flip()
button = Button()
snake = Snake()
food = Food()
utility = Utility()
bombs = Bombs()
game_state = GameState()
while not done:
game_state.main_game()
clock.tick(50)
pygame.quit()
This is just the snippit of code i can send the rest if needed the thing i did previously i had it under a game loop but this time im making a class and object so i can make multiple levels in the game
The if event.type == pygame.MOUSEBUTTONDOWN: and if event.type == pygame.KEYDOWN: are both outside of the for loop that defines the "event" variable.
def main_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN: # this is where the error comes from
mouse_state = 1
pygame.mouse.set_pos(mouse_x,mouse_y + 1)
else:
mouse_state = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
snake.yV = 0
snake.xV = -1
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
snake.yV = 0
snake.xV = 1
if event.key == pygame.K_UP or event.key == pygame.K_w:
snake.xV = 0
snake.yV = -1
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
snake.xV = 0
snake.yV = 1
mouse_x = pygame.mouse.get_pos()[0]
mouse_y = pygame.mouse.get_pos()[1]
pygame.display.set_caption("Snake, FPS: " + str(clock.get_fps()))
screen.fill(GREY)
snake.update()
food.update()
utility.update()
bombs.update()
food.draw()
snake.draw()
utility.draw()
bombs.draw()
pygame.display.flip()
button = Button()
snake = Snake()
food = Food()
utility = Utility()
bombs = Bombs()
game_state = GameState()
Your code have indentation problems. Which makes event.MOUSEBUTTONDOWN and other events outside the loop. You code should have looks like this.

How to make game character (user) move smooth?

in my game i have set my character to move. How it is set is:
if game_over_state == False:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pause = True
game_paused()
if event.key == pygame.K_LEFT:
player_x_change = -2
if event.key == pygame.K_RIGHT:
player_x_change = 2
if event.key == pygame.K_UP:
player_y_change = -2
if event.key == pygame.K_DOWN:
player_y_change = 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT
player_x_change = 0
if event.type == pygame.KEYUP:
player_y_change = 0
Is it a way to change this to a while function or something so the character doesn't stop moving when release a arrow-key (even though another arrow-key is held down)?
the issue is the condition in event.type == pygame.KEYUP.
if event.type == pygame.KEYUP:
# [...]
if event.type == pygame.KEYUP:
player_y_change = 0
Just reset either player_x_change or player_y_change, dependent on the key that is released:
if game_over_state == False:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pause = True
game_paused()
if event.key == pygame.K_LEFT:
player_x_change = -2
if event.key == pygame.K_RIGHT:
player_x_change = 2
if event.key == pygame.K_UP:
player_y_change = -2
if event.key == pygame.K_DOWN:
player_y_change = 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT
player_x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player_y_change = 0
If you want to handle the keys simultaneously, that means you want to move the player diagonal when 2 keys are pressed and you don't want to that the player stops, when 1 key is released, then I recommend to use pygame.key.get_pressed() rather than the KEYDOWN event:
for event in in pygame.event.get():
if game_over_state == False:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pause = True
game_paused()
if game_over_state == False:
keys = pygame.key.get_pressed()
player_x_change, player_y_change = 0, 0
if keys[pygame.K_LEFT]:
player_x_change -= 2
if keys[pygame.K_RIGHT]:
player_x_change += 2
if keys[pygame.K_UP]:
player_y_change -= 2
if keys[pygame.K_DOWN]:
player_y_change += 2

I want to prevent diagonal movement in Pygame

I'm working on making a version of the game snake and I'm trying to prevent diagonal movement. Is there a way to prevent multiple KEYDOWN events
This is my helper function that detects KEYDOWN events.
def _keydown_events(self, event):
'''Responds to pressing keystrokes'''
if event.type == pg.KEYDOWN:
if event.key == pg.K_q:
pg.display.quit()
running = False
sys.exit()
elif event.key == pg.K_RIGHT:
self.snake.move_right = True
elif event.key == pg.K_LEFT:
self.snake.move_left = True
elif event.key == pg.K_UP:
self.snake.move_up = True
elif event.key == pg.K_DOWN:
self.snake.move_down = True
You have to ensure that just self.snake.move_right, self.snake.move_left, self.snake.move_up or self.snake.move_down is set, but never 2 or more states simultaneously. e.g:
def _keydown_events(self, event):
'''Responds to pressing keystrokes'''
if event.type == pg.KEYDOWN:
if event.key == pg.K_q:
pg.display.quit()
running = False
sys.exit()
elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:
self.snake.move_right = False
self.snake.move_left = False
self.snake.move_up = False
self.snake.move_down = False
if event.key == pg.K_RIGHT:
self.snake.move_right = True
elif event.key == pg.K_LEFT:
self.snake.move_left = True
elif event.key == pg.K_UP:
self.snake.move_up = True
elif event.key == pg.K_DOWN:
self.snake.move_down = True
Anyway I recommend to remove the states self.snake.move_right, self.snake.move_left, self.snake.move_up or self.snake.move_down.
Use a single state which indicates the direction of the snake. Add a state move_dir and assign pygame.key.name(event.key). The value of move_dir becomes "right", "left", "up" respectively "down" for RIGHT, LEFT, UP or DOWN. e.g:
def _keydown_events(self, event):
'''Responds to pressing keystrokes'''
if event.type == pg.KEYDOWN:
if event.key == pg.K_q:
pg.display.quit()
running = False
sys.exit()
elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:
# move_dir becomes "right", "left", "up" or "down"
self.snake.move_dir = pygame.key.name(event.key)
Of course you can state the move vector directly:
def _keydown_events(self, event):
'''Responds to pressing keystrokes'''
if event.type == pg.KEYDOWN:
if event.key == pg.K_q:
pg.display.quit()
running = False
sys.exit()
elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:
move_dirs = {pg.K_RIGHT: (1, 0), pg.K_LEFT: (-1, 0),
pg.K_UP: (0, -1), pg.K_DOWN: (0, 1)}
self.snake.move_dir = move_dirs[event.key]
You may want to turn your movement direction variables into a single delta value instead:
if event.key == pg.K_RIGHT:
self.snake.move_dir = (+1, 0)
elif event.key == pg.K_LEFT:
self.snake.move_dir = (-1, 0)
elif event.key == pg.K_UP:
self.snake.move_dir = (0, -1)
elif event.key == pg.K_DOWN:
self.snake.move_dir = (0, +1)
and wherever you move your snake,
dx, dy = self.move_dir
x += dx
y += dy

How to execute a repeated command in pygame?

I've been struggling to get my code to work. I want my image to move continuously while pressing W,A,S, or D instead of having to repeatedly tap the key, but my code keeps having problems. Right now, it says that the video system is not initialized. I don't understand why this is popping up - I already have pygame.init() in my code.
import pygame
#set up the initial pygame window
pygame.init()
screen = pygame.display.set_mode([900,600])
#set background color
background = pygame.Surface(screen.get_size())
background.fill([204,255,229])
screen.blit(background, (0,0))
#Pull in the image to the program
my_image = pygame.image.load("google_logo.png")
#copy the image pixels to the screen
left_side = 50
height = 50
screen.blit(my_image, [left_side, height])
#Display changes
pygame.display.flip()
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
#set up pygame event loop
while True:
for event in pygame.event.get():
print event
if event.type == pygame.quit():
running = False
if event.type == pygame.KEYDOWN:
# change the keyboard variables
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == pygame.KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
pygame.quit()
Thanks!
I've had a bit of a muck around with your code and have fixed some of your little errors... Hopefully you can read through my comments some of the reasoning of why I've changed a few things. Also, your code was getting the video error because of a few reasons I believe: 1. You were constantly calling pygame.quit() because it was checking if the key 'escape' was not being pressed (pygame.KEYUP) 2. You are meant to put 'pygame.display.flip()' into the game loop itself so it can update the screen not just once and that's it.
You also needed to import sys in order to use the sys.exit() call.
Although the video error is fixed, your image doesn't move... Hopefully you figure out why.. :) Happy Coding!
-Travis
import pygame
# Initialize pygame and create the window!
pygame.init()
screen = pygame.display.set_mode((800,600))
#Creating background Surface and setting the colour.
background = pygame.Surface(screen.get_size())
background.fill((255,255,0))
# Loading a few needed variables.
my_image = pygame.image.load("dogtest.png")
left_side = 50
height = 50
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
# These varibales are standard when making a game of some sort!
total_frames = 0 #How many frames have passed.
clock = pygame.time.Clock() # Use this in the main loop to set game running
# at a certain speed!
FPS = 60
running = True #The game condition (whether the loop runs or not!)
while running:
# This is constantly repeating if the user presses the 'x' to close the
# program so the program closes safely and efficiently!
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN: # This handles Key Presses!
if event.key == pygame.K_ESCAPE:
running = False
pygame.quit()
sys.exit()
if event.key == pygame.K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == pygame.K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == pygame.K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == pygame.K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == pygame.KEYUP: # This is checking if the key ISN'T being pressed!
if event.key == pygame.K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == pygame.K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == pygame.K_UP or event.key == ord('w'):
moveUp = False
if event.key == pygame.K_DOWN or event.key == ord('s'):
moveDown = False
# Blitting the Background surface and image!
screen.blit(background, (0, 0))
screen.blit(my_image, (left_side, height))
clock.tick(FPS) # Sets the speed in which the code runs, (and the game!)
total_frames += 1 # Keeps a variable storing the number of frames have passed
pygame.display.update() # Constanly updates the screen! You can also use: pygame.display.flip()
quit()

Python: Player Movement

I've been working on a school project, and I need some assistance with player movement. The problem is I have to manually tap the arrow / WASD keys for the player to move one spot at a time. The player won't move if I hold in the keys. How do I fix this issue?
Note - I'm using an outdated Python - Python 2.7.3
Code:
# Begin 'The Maze'
# Import modules
import os, sys, time, pygame
from pygame.locals import *
from pygame.time import *
# Initialise Pygame + Clock
pygame.init()
mainClock = pygame.time.Clock()
# Window Setup
WINDOWHEIGHT = 480
WINDOWWIDTH = 600
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('The Maze')
# Player Variables
player = pygame.Rect(50, 50, 50, 50)
# Colour Setup
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# Movement Variables
moveLEFT = False
moveRIGHT = False
moveUP = False
moveDOWN = False
MOVESPEED = 7
x,y = 0,0
charx,chary = 0,0
movex,movey = 0,0
# Game Loop & Events + Updates
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Change the keyboard variables
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = True
movex = -0.5
if event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = True
movex = -0.5
if event.key == K_UP or event.key == ord('w'):
moveUP = True
movey = 0.5
if event.key == K_DOWN or event.key == ord('s'):
moveDOWN = True
movey = -0.5
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = False
movex = 0
if event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = False
movex = 0
if event.key == K_UP or event.key == ord ('w'):
moveUP = False
movey = 0
if event.key == K_DOWN or event.key == ord('s'):
moveDOWN = False
movey = 0
# Background Setup
windowSurface.fill(WHITE)
# Player Setup + Updating Screen
if moveDOWN and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUP and player.top > 0:
player.top-= MOVESPEED
if moveLEFT and player.left > 0:
player.left -= MOVESPEED
if moveRIGHT and player.right < WINDOWWIDTH:
player.right += MOVESPEED
pygame.draw.rect(windowSurface, GREEN, player)
pygame.display.update()
mainClock.tick(40)
Thanks!
A simple dedent of the block of code after # Background Setup did the job.
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Change the keyboard variables
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = True
elif event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = True
elif event.key == K_UP or event.key == ord('w'):
moveUP = True
elif event.key == K_DOWN or event.key == ord('s'):
moveDOWN = True
elif event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_LEFT or event.key == ord('a'):
moveLEFT = False
elif event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = False
elif event.key == K_UP or event.key == ord ('w'):
moveUP = False
elif event.key == K_DOWN or event.key == ord('s'):
moveDOWN = False
# <-- Dedent
# Background Setup
windowSurface.fill(WHITE)
# Player Setup + Updating Screen
if moveDOWN and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUP and player.top > 0:
player.top-= MOVESPEED
if moveLEFT and player.left > 0:
player.left -= MOVESPEED
if moveRIGHT and player.right < WINDOWWIDTH:
player.right += MOVESPEED
pygame.draw.rect(windowSurface, GREEN, player)
pygame.display.update()
mainClock.tick(40)

Categories

Resources