I'm trying to learn how to make a game using python and pygame, but I'm pretty new to this, so I can't understand the jargon that comes with the answers that are similar to my own question.
I'm following a video playlist on YouTube called Tech With Tim and I need to use some images for the character in the game, but the images simply won't load and keeps coming up with 'Couldn't open C:\GAME\R1.png'.
They're already in the same folder why is what makes this so confusing. All the images are also named correctly to the best of my understanding (i.e. they all have the names used in the code below:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 480))
pygame.display.set_caption("First Game")
walkRight = [pygame.image.load('C:\GAME\R1.png'), pygame.image.load('C:\GAME\R2.png'), pygame.image.load('C:\GAME\R3.png'),
pygame.image.load('C:\GAME\R4.png'), pygame.image.load('C:\GAME\R5.png'), pygame.image.load('C:\GAME\R6.png'),
pygame.image.load('C:\GAME\R7.png'), pygame.image.load('C:\GAME\R8.png'), pygame.image.load('C:\GAME\R9.png')]
walkLeft = [pygame.image.load('C:\GAME\L1.png'), pygame.image.load('C:\GAME\L2.png'), pygame.image.load('C:\GAME\L3.png'),
pygame.image.load('C:\GAME\L4.png'), pygame.image.load('C:\GAME\L5.png'), pygame.image.load('C:\GAME\L6.png'),
pygame.image.load('C:\GAME\L7.png'), pygame.image.load('C:\GAME\L8.png'), pygame.image.load('C:\GAME\L9.png')]
bg = pygame.image.load('C:\GAME\Bg.jpg')
char = pygame.image.load('C:\GAME\standing.png')
x = 50
y = 425
width = 64
height = 64
vel = 5
clock = pygame.time.Clock()
isJump = False
jumpCount = 10
left = False
right = False
walkCount = 0
def redrawGameWindow():
global walkCount
win.blit(bg, (0, 0))
if walkCount + 1 >= 27:
walkCount = 0
if left:
win.blit(walkLeft[walkCount // 3], (x, y))
walkCount += 1
elif right:
win.blit(walkRight[walkCount // 3], (x, y))
walkCount += 1
else:
win.blit(char, (x, y))
walkCount = 0
pygame.display.update()
run = True
while run:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
left = True
right = False
elif keys[pygame.K_RIGHT] and x < 500 - vel - width:
x += vel
left = False
right = True
else:
left = False
right = False
walkCount = 0
if not (isJump):
if keys[pygame.K_SPACE]:
isJump = True
left = False
right = False
walkCount = 0
else:
if jumpCount >= -10:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 10
isJump = False
redrawGameWindow()
pygame.quit()
I expect to see the game load and work, but instead, the error 'Couldn't open C:\GAME\R1.png' comes up.
I'd appreciate any help!
First, be sure that is the good path to your file.
Also, you should use '/' instead of '\'. Your path should be : 'C:/GAME/R1.png'
Related
I'm currently trying to make my first game. I am trying to make my character jump, but my code doesn't have errors but when my character jump it just happens to fast. I don't know which part to change. I have not been able to figure this out on my own as I am still learning. Here is my code:
import pygame
pygame.init()
screen = pygame.display.set_mode((1200, 600))
WinHeight = 600
WinWidth = 1200
# player
player = pygame.image.load("alien.png")
x = 50
y = 450
vel = 0.3
playerSize = 32
# title
pygame.display.set_caption("First Game")
# Jump
isJump = False
jumpCount = 10
running = True
while running:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > vel:
x -= vel
if keys[pygame.K_d] and x < WinWidth - vel - playerSize:
x += vel
if not (isJump):
if keys[pygame.K_w] and y > vel:
y -= vel
if keys[pygame.K_s] and y < WinHeight - vel - playerSize:
y += vel
if keys[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 10
screen.blit(player, (x, y))
pygame.display.update()
Use pygame.time.Clock to control the frames per second and thus the game speed.
The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():
This method should be called once per frame.
That means that the loop:
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
# [...]
Okay, so I was able to add walking animations to the right and the left on my main file, but when I basically copy/pasted/changed the names for adding jump, it doesn't work.
I went ahead and made a copy of my main file, just without the walking animations. I went ahead and tried just doing the jump animation, and even though I copied everything from the same tutorial as I used for the walking, it still doesn't work.
I've been trying to figure this out since last night from like 8 pm. Is there a different way for jump animations to work? See below for the code of THE COPY, so no walking animations. I get no errors, the player can walk left and right, and jump as well.
import pygame
import os
x = 90
y = 60
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x, y)
def player_jump_animation():
"""Adding collision block to each right jump animation"""
new_player = player_frames_jump[player_jump_index]
new_player_rect = new_player.get_rect(
center=(player_rect.centerx, player_rect.centery))
return new_player, new_player_rect
pygame.init()
screen = pygame.display.set_mode((1000, 1000))
clock = pygame.time.Clock()
player_movement = 720
isJump = False
jumpCount = 10
bg_surface = pygame.image.load('assets/camp_bg.png').convert()
bg_surface = pygame.transform.scale2x(bg_surface)
player_idle = pygame.transform.scale2x(pygame.image.load(
'assets/IDLE_000.png').convert_alpha())
player_jump0 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_000.png').convert_alpha())
player_jump1 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_001.png').convert_alpha())
player_jump2 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_002.png').convert_alpha())
player_jump3 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_003.png').convert_alpha())
player_jump4 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_004.png').convert_alpha())
player_jump5 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_005.png').convert_alpha())
player_jump6 = pygame.transform.scale2x(
pygame.image.load('assets/JUMP_006.png').convert_alpha())
player_frames_jump = [player_jump0, player_jump1, player_jump2,
player_jump3, player_jump4, player_jump5, player_jump6]
player_jump_index = 3
player_surface = player_frames_jump[player_jump_index]
player_rect = player_surface.get_rect(center=(300, 512))
PLAYERJUMP = pygame.USEREVENT
pygame.time.set_timer(PLAYERJUMP, 120)
run = True
while run:
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == PLAYERJUMP:
if player_jump_index < 6:
player_jump_index += 1
else:
player_jump_index = 0
# Setting jump animation
player_jump, player_rect = player_jump_animation()
if keys[pygame.K_LEFT] and player_rect.centerx > 0 + 35:
# If I speed up, player looks like sliding
player_rect.centerx -= 5
if keys[pygame.K_RIGHT] and player_rect.centerx < 1000 - 35:
# If I speed up, player looks like sliding
player_rect.centerx += 5
if not(isJump):
if keys[pygame.K_UP]:
isJump = True
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
player_movement -= (jumpCount ** 2) * 0.1 * neg
jumpCount -= 0.5
# This will execute when jump is finished
else:
# Resetting Variables
jumpCount = 10
isJump = False
pygame.display.update()
clock.tick(60)
screen.blit(bg_surface, (0, 0))
player_rect.centery = player_movement
screen.blit(player_idle, player_rect)
pygame.quit()
You have to draw the Surface referenced by player_jump, if the player is jumping:
while run:
# [...]
screen.blit(bg_surface, (0, 0))
player_rect.centery = player_movement
if isJump:
screen.blit(player_jump, player_rect)
else:
screen.blit(player_idle, player_rect)
# [...]
I am messing around with pygame, and trying to create a simple jumping function (no physics yet).
For some reason my "jumps" are not visible in the display, even though the values I am using print out and seem to be working as intended. What could I be doing wrong?
isJump = False
jumpCount = 10
fallCount = 10
if keys[pygame.K_SPACE]:
isJump = True
if isJump:
while jumpCount > 0:
y -= (jumpCount**1.5) / 3
jumpCount -= 1
print(jumpCount)
while fallCount > 0:
y += (fallCount**1.5) / 3
fallCount -= 1
print(fallCount)
else:
isJump = False
jumpCount = 10
fallCount = 10
print(jumpCount, fallCount)
win.fill((53, 81, 92))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
I shortened the amount of code, but I think this is all that is related to the problem.
You've to turn the while loops to if conditions. You don't want to do the complete jump in a single frame.
You've to do a single "step" of the jump per frame. Use the main application loop to perform the jump.
See the example:
import pygame
pygame.init()
win = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
isJump = False
jumpCount, fallCount = 10, 10
x, y, width, height = 200, 300, 20, 20
run = True
while run:
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
isJump = True
if isJump:
if jumpCount > 0:
y -= (jumpCount**1.5) / 3
jumpCount -= 1
print(jumpCount)
elif fallCount > 0:
y += (fallCount**1.5) / 3
fallCount -= 1
print(fallCount)
else:
isJump = False
jumpCount, fallCount = 10, 10
print(jumpCount, fallCount)
win.fill((53, 81, 92))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.flip()
I would like to ask your help for solving this problem of mine. I need to develop a game using only functions (NO CLASSES) in pygame.
I already manage to run the game but the animations or sprites do not update as they should. The image always stays the same when it should be changing while moving.
What am I doing wrong?
Here's the code:
import pygame
WIDTH = 800
HEIGHT= 600
pygame.display.set_caption("Nico's worst adventure")
window = pygame.display.set_mode((WIDTH, HEIGHT))
#Color #R #G #B
White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0)
Blue = (0, 0, 255)
#Position
x = 50
y = 425
imageWidth = 64
vel = 5 #Velocity of movement
isJumping = False
jumpCount = 10
left = False
right = False
walkCount = 0
#Image port
walkRight = [pygame.image.load('Nico right(1).png'), pygame.image.load('Nico right(2).png'), pygame.image.load('Nico right(3).png'), pygame.image.load('Nico right(4).png')]
walkLeft = [pygame.image.load('Nico left(1).png'), pygame.image.load('Nico left(2).png'), pygame.image.load('Nico left(3).png'), pygame.image.load('Nico left(4).png')]
still = pygame.image.load('Nico still.png')
backgorund = pygame.image.load('Fondo.png')
def drawCharacter():
global walkCount
window.blit(backgorund, (0,0))
if walkCount + 1 >= 12:
walkCount = 0
if left:
window.blit(walkLeft[walkCount//3], (x, y))
walkCount += 1
elif right:
window.blit(walkRight[walkCount//3], (x, y))
walkCount += 1
else:
window.blit(still, (x, y))
pygame.display.update()
def draw():
global imageWidth
global WIDTH
global x
global y
global vel
global jumpCount
global isJumping
clock = pygame.time.Clock()
play = True
#Main loop
while play:
clock.tick(27)
pygame.init()
for event in pygame.event.get():
if event.type == pygame.QUIT:
play = False
key = pygame.key.get_pressed()
if key[pygame.K_LEFT] and x > vel:
x -= vel
left = True
right = False
elif key[pygame.K_RIGHT] and x < WIDTH - imageWidth - vel:
x += vel
right = True
left = False
else:
right = False
left = False
walkCount = 0
if not(isJumping):
if key[pygame.K_SPACE]:
isJumping = True
right = False
left = False
walkCount = 0
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJumping = False
jumpCount = 10
drawCharacter()
pygame.display.flip()
pygame.quit()
draw()
I have already checked it and compared it to other codes but I just can't find what's the real problem.
The simple fix has already been mentioned, but I'd rather suggest getting rid of the global variables altogether and just moving them into the function with the main loop to make them local.
Also, the drawCharacter function shouldn't be responsible to update the walkCount as well as blitting the images. I'd just remove it and update the walkCount in the if key[pygame.K_LEFT]... clauses and then use it to assign the current player image to a variable (player_image) which you can blit later in the drawing section. That allows you to get rid of the left and right variables, too.
The drawCharacter function would then only consist of these two lines,
window.blit(background, (0, 0))
window.blit(player_image, (x, y))
so you could simply call them in the main loop as well instead of calling them in the function (to which you would have to pass these arguments).
By the way, call the convert or convert_alpha methods when you load the images to improve the performance.
Here's the updated code:
import pygame
pygame.init()
WIDTH = 800
HEIGHT= 600
pygame.display.set_caption("Nico's worst adventure")
window = pygame.display.set_mode((WIDTH, HEIGHT))
White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 0, 0)
Blue = (0, 0, 255)
# Images (I assume you're using pictures with a transparent background
# so I call the `convert_alpha` method).
walkRight = [
pygame.image.load('Nico right(1).png').convert_alpha(),
pygame.image.load('Nico right(2).png').convert_alpha(),
pygame.image.load('Nico right(3).png').convert_alpha(),
pygame.image.load('Nico right(4).png').convert_alpha(),
]
walkLeft = [
pygame.image.load('Nico left(1).png').convert_alpha(),
pygame.image.load('Nico left(2).png').convert_alpha(),
pygame.image.load('Nico left(3).png').convert_alpha(),
pygame.image.load('Nico left(4).png').convert_alpha(),
]
still = pygame.image.load('Nico still.png').convert_alpha()
background = pygame.image.load('Fondo.png').convert()
def game():
clock = pygame.time.Clock()
# Player related variables.
x = 50
y = 425
imageWidth = 64
vel = 5
isJumping = False
jumpCount = 10
walkCount = 0
player_image = still # Assign the current image to a variable.
play = True
while play:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
play = False
key = pygame.key.get_pressed()
if key[pygame.K_LEFT] and x > vel:
x -= vel
# Update the walkCount and image here.
walkCount += 1
player_image = walkRight[walkCount//3]
elif key[pygame.K_RIGHT] and x < WIDTH - imageWidth - vel:
x += vel
walkCount += 1
player_image = walkLeft[walkCount//3]
else:
player_image = still
walkCount = 0
if walkCount + 1 >= 12:
walkCount = 0
if not isJumping:
if key[pygame.K_SPACE]:
isJumping = True
walkCount = 0
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJumping = False
jumpCount = 10
window.blit(background, (0, 0))
window.blit(player_image, (x, y)) # Just blit the current image.
pygame.display.flip() # Only one `flip()` or `update()` call per frame.
game()
pygame.quit()
It's because left and right in the draw function are local variables, not global.
A simple fix is to add
global left
global right
at the beginning of draw.
I need to develop a game using only functions (NO CLASSES) in pygame
That's a strange requirement given that pygame itself is full of classes and you use some of them already.
I am new to this website and pygame so bear with me. I am experimenting with pygame and made a simple platformer. However, whenever I 'Jump', the block jumps frame by frame, so I have to hold down the spacebar. Any help would be greatly appreciated!
here is my code:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
x = 0
y = 490
width = 10
height = 10
vel = 5
pygame.key.set_repeat(1)
isjump = False
jumpcount = 10
while True:
pygame.time.delay(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x>vel-5:
x -= vel
if keys[pygame.K_d] and x < 500 - width:
x += vel
if not(isjump):
if keys[pygame.K_SPACE]:
isjump = True
else:
if jumpcount >= -10:
neg = 1
if jumpcount < 0:
neg = -1
y -= (jumpcount ** 2) /2 * neg
jumpcount -= 1
else:
isjump = False
jumpcount = 10
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
pygame.display.update()
pygame.quit()
You are mixing your keyboard event handling with your jump-logic. I've done two things, change the spacebar detection to trigger isjump and handle the jump logic irregardless of whether there is a key pressed or not:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
x = 0
y = 490
width = 10
height = 10
vel = 5
pygame.key.set_repeat(1)
isjump = False
jumpcount = 10
while True:
pygame.time.delay(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x>vel-5:
x -= vel
if keys[pygame.K_d] and x < 500 - width:
x += vel
# if we're not already jumping, check if space is pressed to start a jump
if not isjump and keys[pygame.K_SPACE]:
isjump = True
jumpcount = 10
# if we're supposed to jump, handle the jump logic
if isjump:
if jumpcount >= -10:
neg = 1
if jumpcount < 0:
neg = -1
y -= (jumpcount ** 2) /2 * neg
jumpcount -= 1
else:
isjump = False
jumpcount = 10
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
pygame.display.update()
pygame.quit()
The line keys = pygame.key.get_pressed() and the whole game logic and drawing code should not be in the event loop (for event in pygame.event.get():), otherwise the code gets executed once per event in the queue, and if no events are in the queue, it won't be executed at all.
You could just dedent keys = pygame.key.get_pressed() and all lines beneath.
Alternatively, you could check in the event loop if the space key was pressed (with if event.type == pygame.KEYDOWN:) and then set isjump to True (that means the player will only jump once per keypress).
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
x = 0
y = 490
width = 10
height = 10
vel = 5
isjump = False
jumpcount = 10
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
isjump = True
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > vel - 5:
x -= vel
elif keys[pygame.K_d] and x < 500 - width:
x += vel
if isjump:
if jumpcount >= -10:
neg = 1
if jumpcount < 0:
neg = -1
y -= jumpcount**2 / 2 * neg
jumpcount -= 1
else:
isjump = False
jumpcount = 10
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
pygame.display.update()
clock.tick(30)
pygame.quit()
I also recommend adding a pygame.time.Clock instance and call clock.tick(FPS) to regulate the frame rate.
And I'd rather implement the jumping in this way, with a gravity constant which gets added to the y-velocity each frame.