Pygame character does not show up on screen - python

I try to get my Pygame character on screen but I cannot get it to appear so I can control it for a game I am building
Here is the code:
import pygame
#turn on pygame
pygame.init()
#window, window name and icon
screen = pygame.display.set_mode((1920,1080))
pygame.display.set_caption("When The Sky Turns Grey")
icon = pygame.image.load('cat.png')
pygame.display.set_icon(icon)
#Player
playerIMG = pygame.image.load('cat.png')
playerX = 960
playerY = 1080
playerXchange = 0
def player():
screen.blit(playerIMG, (playerX, playerY))
#Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#KEYS
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
playerX_change = -5
if event.key == pygame.K_d:
playerX_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
playerXchange = 0
playerX += playerXchange
#RGB
screen.fill((0, 0, 255))
#draw player (call player function)
player()
pygame.display.update()
I cannot get it to show up at all, no matter what I change.
I am new to pygame and if anyone can help I will be grateful
Thank you!
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

There is 2 problems in this question
First your cat Y position is to much that it went under the screen, it should be like this:
playerY = 540 # Don't go over 1080 which is the screen height
Second you didn't update the display so it doesn't show anything on the screen, at the very end of the while loop put pygame.display.update after player()

Related

In Pygame, the image doesn't get erased when moved to another location on the game window

I have been trying out the Pygame game library on my Mac, and when I got to try moving around an image around the game window, for some reason, it doesn't get erased.
The code I tried to run:
import pygame
pygame.init()
# Creates the screen.
screen = pygame.display.set_mode([800, 600])
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("ufo.png")
pygame.display.set_icon(icon)
# Player sprite.
playerImg = pygame.image.load("player.png")
playerX = 350
playerY = 500
playerX_change = 0
# Function to draw the player
def player(x, y):
screen.blit(playerImg, (playerX, playerY))
# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
print("Left key is pressed!")
if event.key == pygame.K_RIGHT:
playerX_change = 0.1
print("Right key is pressed!")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
I have tried to run similar code on my PC, and it worked like intended. I have no idea what to do.
You have to clear the screen in every frame:
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# update objects
speed = 1
keys = pygame.key.get_pressed()
playerX += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
# clear screen
screen.fill(0)
# draw scene
player(playerX, playerY)
# update display
pygame.dispaly.flip()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()

Why does "Game over" text not appear?

I am currently attempting to programm a small game. An enemy is supposed to chase the player, the actual chasing is not implemented yet. I still need to figure out how to do that, but that's not the question.
I have made it so that the player returns to the start point once they collide with the enemy. In addition to that, a text 'Game over' is supposed to appear. The function for that is called at the end of the game loop and while the text appeared briefly(it actually only appeared once, I have tried it multiple times), it does not stay. I was planing on making it appear and then disappear after a few seconds so that the player can play again, but I'm not sure why it disappears instantly.
If this is the wrong place to post this, please tell me, I will delete this post. This is my code, would be amazing if somebody could help me out:
import pygame #imports pygame
import math
pygame.init()
#screen
screen = pygame.display.set_mode((800,600)) #width and height
#title and icon
pygame.display.set_caption("The Great Chase") #changes title
icon = pygame.image.load('game-controller.png')
pygame.display.set_icon(icon) #setting icon
#player
playerImg = pygame.image.load('scary-monster.png')
playerX = 370
playerY = 480
playerX_change = 0
playerY_change = 0
#enemy
enemyImg = pygame.image.load('caterpillar.png')
enemyX = 370
enemyY = 50
enemyX_change = 0
enemyY_change = 0
#GAME OVER
game_over_font = pygame.font.Font('Bubblegum.ttf',64)
def game_over_text():
game_over_text = game_over_font.render("GAME OVER", True, (255, 0, 0))
screen.blit(game_over_text, (200, 250))
def player(x, y): #function for player
screen.blit(playerImg, (x, y)) #draws image of player, blit -> means to draw
def enemy(x, y): #function for enemy
screen.blit(enemyImg,(x,y))
def isCollision(playerX, playerY, enemyX, enemyY):
distance = math.sqrt((math.pow(playerX-enemyX,2)) + (math.pow(playerY - enemyY,2)))
if distance < 25:
return True
else:
return False
def chase():
distance = math.sqrt((math.pow(playerX-enemyX,2)) + (math.pow(playerY - enemyY,2)))
#Game loop
running = True
while running:
screen.fill((255,255,0)) #0-255 RGB-> red, green & blue
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke check whether right or left or up or down
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.2
if event.key == pygame.K_RIGHT:
playerX_change = 0.2
if event.key == pygame.K_UP:
playerY_change = -0.2
if event.key == pygame.K_DOWN:
playerY_change = 0.2
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
playerX += playerX_change
playerY += playerY_change
#creating borders so that player won't leave screen
if playerX <=0:
playerX = 0
elif playerX >=768:
playerX = 768
if playerY <= 0:
playerY = 0
elif playerY >=568:
playerY = 568
#collision
collision = isCollision(playerX, playerY, enemyX, enemyY)
if collision:
playerY = 480
game_over_text()
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
The collision only occurs for a moment and the game over text is only shown when the object collides. If you want to persist the text, set a gameover variable when the collision is detected and display the text based on the state of the variable:
gameover = False
running = True
while running:
# [...]
collision = isCollision(playerX, playerY, enemyX, enemyY)
if collision:
playerY = 480
gameover = True
player(playerX, playerY)
enemy(enemyX, enemyY)
if gameover:
game_over_text()
pygame.display.update()
Note, collision is set in every frame depending on the position of the objects. However, gameover is set once when a collision occurs and then maintains its state.

How to build a propper player movement script Pygame [duplicate]

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
Closed 1 year ago.
Ok so im new to PyGame, and im making a space invader game, im currently building the movement script.
for some reason my character is infinitely moving to the right when i press the right key.. i know this must be a really simple solution i am just not seeing it lol i would appreciate an answer.
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Space Invader')
icon = pygame.image.load('pepper.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370
playerY = 480
playerX_Change = 0
def player (x, y): screen.blit(playerImg, (x, y) )
running = True
while running:
# RGB STANDS FOR RED, GREEN, BLUE THE NUMBERS GOES MAX TO 255 FOR EXAMPLE_:
screen.fill((0, 0, 30)) # this will display yellow
for event in pygame.event.get():
if event.type == pygame.QUIT: #if we click the X the program ends
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_Change = -0.1
if event.key == pygame.K_RIGHT:
playerX_Change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_Change = 0.1
playerX += playerX_Change
player(playerX, playerY)
pygame.display.update()
I suggest to use pygame.key.get_pressed() instead of the key board events.
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Space Invader')
icon = pygame.image.load('pepper.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370
playerY = 480
def player (x, y):
screen.blit(playerImg, (x, y) )
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: #if we click the X the program ends
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] :
playerX += 0.1
if keys[pygame.K_LEFT] :
playerX -= 0.1
# RGB STANDS FOR RED, GREEN, BLUE THE NUMBERS GOES MAX TO 255 FOR EXAMPLE_:
screen.fill((0, 0, 30)) # this will display yellow
player(playerX, playerY)
pygame.display.update()

Pygame dinosaur image keeps duplicating

I'm trying to make a dinosaur game in python (like the offline dino game in chrome).
I want the dino to jump when space is pressed but when I press it,not only the image of dino is duped but it also doesn't come back.
import pygame
import time
pygame.init()
displayWidth = 700
displayHeight = 350
gameDisplay = pygame.display.set_mode((displayWidth,displayHeight))
pygame.display.set_caption("Dino-Run")
black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
dinoimg = pygame.image.load("dino.png")
def dino(x,y):
gameDisplay.blit(dinoimg,(x,y))
def gameloop():
gameExit = False
x = (displayWidth * 0.005)
y = (displayHeight * 0.75)
y_change = 0
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
y_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
y_change = 0
y += y_change
dino(x,y)
pygame.display.update()
clock.tick(60)
Could someone please tell me how can I prevent the dino to dupe each time space is pressed and for the dino to come back to the ground.
You have to override everything before drawing new things to the screen.
Add this at the beginning of your loop:
gameDisplay.fill(color)

I am unable to make an object move from point A to point B without user input using python 2.7 with pygame

I am attempting to make a game where the 'player' (who spawns as the moon furthest to the right) can move around using the 'WASD' keys and enemies fall from the top of the screen in order to hit the player and end the game. I am currently doing this for an assignment and i have set up a test to see whether it is possible for me to do this and so far i have been able to create a 'player' object that is controllable by the 'WASD' keys and make a screen which requires players to press 'SPACE' to play the game. I am having trouble though with being able to have the enemies fall on the 'Y' axis down the screen smoothly. The picture moves down the screen only when the user presses or releases a key, this creates a jagged movement or when the user moves the mouse over the pygame screen, creating a very smooth movement.
#import necessary modules and pygame.
import pygame, sys, random
from pygame.locals import *
#set global variables
pygame.init()
WINDOWWIDTH = 800
WINDOWHEIGHT = 800
BACKGROUNDCOLOUR = (255,255,255)
TEXTCOLOUR = (0,0,0)
FPS = 30
ENEMYMINSIZE = 10
BOMBSAWAY = -1
ENEMYMAXSIZE = 40
ENEMYMINSPEED = 1
ENEMYMAXSPEED = 10
ADDNEWENEMYRATE = 5
PLAYERMOVERATE = 5
FSIZE = 48
BLUE = (0,0,255)
global PLAY
PLAY = False
global fpsClock
fpsClock = pygame.time.Clock()
# set up pygame and GUI
MainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
windowSurface.fill(BACKGROUNDCOLOUR)
pygame.display.set_caption('Bubble Dash')
enemy = pygame.image.load('player.jpg')
char = pygame.image.load('player.jpg')
# set up fonts
basicFont = pygame.font.SysFont(None, 48)
# set up the text
text = basicFont.render('Press any key to play!', True, (255,255,0))
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
# draw the text onto the surface
# set up x and y coordinates
# music
windowSurface.blit(text, textRect)
def playgame(PLAY):
x,y = 0,0
movex,movey = 0,0
charx=300
chary=200
direction = 'down'
enemyx= 10
enemyy=10
while PLAY:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('m'):
pygame.mixer.music.stop()
if event.key == ord('n'):
pygame.mixer.music.play()
if event.key == ord('a'):
movex = -0.5
if event.key == ord('d'):
movex = 0.5
if event.key == ord('w'):
movey = -0.5
if event.key == ord('s'):
movey = 0.5
if event.type ==KEYUP:
if event.key == ord('a'):
movex = 0
if event.key == ord('d'):
movex = 0
if event.key == ord('w'):
movey = 0
if event.key == ord('s'):
movey = 0
if direction == 'down':
enemyy += 7
windowSurface.fill(BLUE)
windowSurface.blit(char, (charx, chary))
windowSurface.blit(enemy, (enemyx, enemyy))
pygame.display.update()
charx+=movex
chary+=movey
def playertopresskey(PLAY):
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_SPACE:
PLAY = True
if PLAY == True:
playgame(PLAY)
pygame.display.update()
playertopresskey(PLAY)
I would like for the 'enemy' object to be able to fall from the top without the user either needing to keypress or to key up or to have to move the mouse on the screen, rather the 'enemy' would just fall from the top as soon as the subroutine is called.
You may need to tweak it a bit because it is set up for me at the moment but i deleted a few things that would give you bother. Hopefully someone can help me. Thanks.
The below is link to a picture similar to mine which you can download and replace in the code for both the 'char' and the 'enemy' variables to view this yourself for i cannot access the courses at the present time.
http://www.roleplaygateway.com/roleplay/the-five-elements/characters/miss-joy/image
I found your error, you would have caught it yourself if you would have divided your code into some functions. Here is the problem:
for event in pygame.event.get():
if event.type == QUIT:
...
if event.type == KEYDOWN:
...
if event.type == KEYUP:
...
if direction == 'down':
enemyy += 7
your code moving the enemy is called only when an event is waiting in the queue. Move it out of the loop, and you will be good to go.
You have to change indention for:
if direction == 'down':
enemyy += 7
Now it is inside for event in pygame.event.get():

Categories

Resources