My code isn't running can I have some assistance? - python

The code is isn't running, it is a Pygame code for a race game, everytime I try to run it, it says ImportError: No module named Pygame. I don't have any idea if this code has any other problems, so as far as I know it is only the Import Error. Can you help me solve the Import Error and any other problems that occur?
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
car_width = 73
gameDisplay = pygame.display.set_mode((display_width,display_height ))
pygame.display.set_caption('A bit Racey 3')
clock = pygame.time.Clock()
def carImg():
pygame.image.load('racecar.png')
def car(x,y):
gameDisplay.blit(carImg,(x,y))
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
gameExit = False
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_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
car(x, y)
if x > display_width - car_width or x < 0:
gameExit = True
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()

pygame.image.load() loads an image and returns the a Surface object. Your surface goes to nowhere:
def carImg():
pygame.image.load('racecar.png')
carImg has to be a variable rather then a function. Assign the Surface object to carImg:
carImg = pygame.image.load('racecar.png')

Related

Can someone please tell me where am I wrong in this python code?

Here's a simple pygame code where I inserted a screen, a pink rectangle and tried moving it.
The rectangle in the pygame window isn't moving.
Which means the code inside '**' isn't working.
How do I solve that?
import pygame, sys
pygame.init()
width = 800
height = 600
pink = (244,133,227)
player_pos = [400, 300]
player_size = 50
screen = pygame.display.set_mode((width,height))
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
** if event.type == pygame.KEYDOWN:
x = player_pos[0]
y = player_pos[1]
if event.type == pygame.K_LEFT:
x -= player_size
elif event.type == pygame.K_RIGHT:
x += player_size
player_pos = [x, y]
screen.fill((0,0,0)) **
pygame.draw.rect(screen, pink, (player_pos[0], player_pos[1], player_size, player_size))
pygame.display.update()
The key is stored in the key attribute, rather then the type attribute. See pygame.event:
if event.type== pygame.K_LEFT:
if event.key == pygame.K_LEFT:
See the example:
import pygame, sys
pygame.init()
width = 800
height = 600
pink = (244,133,227)
player_pos = [400, 300]
player_size = 50
screen = pygame.display.set_mode((width,height))
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
x = player_pos[0]
y = player_pos[1]
if event.key == pygame.K_LEFT:
x -= player_size
elif event.key == pygame.K_RIGHT:
x += player_size
player_pos = [x, y]
screen.fill((0,0,0))
pygame.draw.rect(screen, pink, (player_pos[0], player_pos[1], player_size, player_size))
pygame.display.update()

NameError: name 'playerMovement' is not defined

I'm here to ask what is the problem with my code? I'm making a game engine, and I thought the easiest way to sort player types would be putting them into a different script and using them there. However, I am having a slight issue doing that, and have no clue how to fix it.
Here is the error I'm getting:
Traceback (most recent call last): File "C:\Users\Harry Court\AppData\Local\Programs\Python\Python36-32\projects\Game Engine\main.py", line 48, in <module> topDownPlayerControls() NameError: name 'topDownPlayerControls' is not defined
P.S: If there is an easier way to do this, please tell me!
main.py
import pygame
from playerSelection import *
import ctypes
from ctypes.wintypes import HWND, LPWSTR, UINT
# Window Size
display_w = 1366
display_h = 768
# Initialize and Set Display
pygame.init()
gameDisplay = pygame.display.set_mode((display_w, display_h))
pygame.display.set_caption("The Joker Engine (Version Undecided) - By Harrison Court")
clock = pygame.time.Clock()
# Ctypes ID's
IDYES = 6
IDNO = 7
x = (display_w * 0.45)
y = (display_h * 0.8)
# Colours
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
running = True
gameDisplay.fill(white)
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
# Misc.
if event.key == pygame.K_ESCAPE:
quitWindow = ctypes.windll.user32.MessageBoxW(0, "Are you sure you want to quit?", "Warning!", 4)
# Confirm they want to leave.
if quitWindow == IDYES:
quit()
topDownPlayerControls()
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
playerSelection.py:
import pygame
from tkinter import Tk, Frame, Menu
import ctypes
from ctypes.wintypes import HWND, LPWSTR, UINT
x = (300)
y = (300)
playerImg = pygame.image.load('Player.png')
class playerMovement():
def player(x,y):
gameDisplay.blit(playerImg, (x,y))
def topDownPlayerControls():
if event.type == pygame.KEYDOWN:
# Left & Right
if event.key == pygame.K_LEFT:
x_change = -5
print("Left")
elif event.key == pygame.K_RIGHT:
x_change = 5
print("Right")
# Up & Down
if event.key == pygame.K_DOWN:
y_change = 5
print("Down")
elif event.key == pygame.K_UP:
y_change = -5
print("Up")
# If no keys are pressed, do this...
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0
# Player Movement
x += x_change
y += y_change
Updated Script:
main.py:
import pygame
from playerSelection import *
from gui import *
from tkinter import *
import ctypes
from ctypes.wintypes import HWND, LPWSTR, UINT
# Define stuff
player = playerMovement()
# Window Size
display_w = 1366
display_h = 768
# Initialize and Set Display
pygame.init()
gameDisplay = pygame.display.set_mode((display_w, display_h))
pygame.display.set_caption("The Joker Engine (Version Undecided) - By Harrison Court")
clock = pygame.time.Clock()
# Ctypes ID's
IDYES = 6
IDNO = 7
x = (display_w * 0.45)
y = (display_h * 0.8)
# Colours
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
running = True
gameDisplay.fill(white)
# Make sure the game isn't dying on us.
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
# Misc.
if event.key == pygame.K_ESCAPE:
quitWindow = ctypes.windll.user32.MessageBoxW(0, "Are you sure you want to quit?", "Warning!", 4)
# Confirm they want to leave.
if quitWindow == IDYES:
quit()
player.displayPlayer(x,y)
player.topDownPlayerControls
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
playerSelection.py:
import pygame
from tkinter import Tk, Frame, Menu
import ctypes
from ctypes.wintypes import HWND, LPWSTR, UINT
x = (300)
y = (300)
display_w = 1366
display_h = 768
gameDisplay = pygame.display.set_mode((display_w, display_h))
playerImg = pygame.image.load('Player.png')
class playerMovement():
def displayPlayer(self,x,y):
gameDisplay.blit(playerImg, (x,y))
def topDownPlayerControls(self):
if event.type == pygame.KEYDOWN:
# Left & Right
if event.key == pygame.K_LEFT:
x_change = -5
print("Left")
elif event.key == pygame.K_RIGHT:
x_change = 5
print("Right")
# Up & Down
if event.key == pygame.K_DOWN:
y_change = 5
print("Down")
elif event.key == pygame.K_UP:
y_change = -5
print("Up")
# If no keys are pressed, do this...
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0
# Player Movement
x += x_change
y += y_change
Your error message is saying that the function topDownPlayerControls is not defined. This is because you are trying to call it as a free function. However, this function is defined within the playerMovement class. So, you would first need to create a playerMovement object, and then call the topDownPlayerControls function on that object. It would look something like this:
player = playerMovement()
player.topDownPlayerControls()
It looks like you will have a number of other fails after that, but I'll leave that as an exercise :)

Can't figure out why my image wont move in pygame

I'm just messing around with Pygame and I can't see what I'm doing incorrectly to make the red circle move with the arrow keys. I can't tell if it's in my main loop. I also haven't been able to find very many tutorials on sprite or looping animations with Pygame. If I for example wanted to make a square oscillate for example like a moving platform how would I do that?
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player():
pygame.draw.circle(game_screen,red,(x,y),15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
dead = False
while dead != True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = -1
elif event.key == pygame.K_RIGHT:
player_x = +1
if event.key == pygame.K_UP:
player_y = +1
elif event.key == pygame.K_DOWN:
player_y = -1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT:
player_x = 0
if event.key == pygame.K_UP or pygame.K_DOWN:
player_y = 0
game_screen.fill(black)
player()
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()
quit()
Your indendation is all messed up.
Your code won't do anything unless the event is QUIT... which then makes it quit.
Your boolean logic is wrong.
This is not proper syntax event.key == pygame.K_UP or pygame.K_DOWN. The order of precedence here is as follows (event.key == pygame.K_UP) or (K_DOWN). Since K_DOWN is truthy, it is always true and thus this entire statement is always true.
I think you mean: event.key == pygame.K_UP or event.key == pygame.K_DOWN
Lastly, it wont' keep moving as you say you want.
It will only move when there is an event in the queue. You can make it keep moving by generating events. Perhaps with an event timer.
Here is a fixed version, hope this helps:
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player(game_screen, red, point): # Use parameters not globals
pygame.draw.circle(game_screen, red, point, 15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
pygame.time.set_timer(pygame.USEREVENT, 1) # 1 per second
dead = False
while not dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
elif event.type == pygame.USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 1) # Set another timer for another 1 second
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = +10
elif event.key == pygame.K_RIGHT:
player_x = -10
elif event.key == pygame.K_UP:
player_y = +10
elif event.key == pygame.K_DOWN:
player_y = -10
elif event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
player_x = 0
elif event.key in [pygame.K_UP, pygame.K_DOWN]:
player_y = 0
game_screen.fill(black)
player(game_screen,red,(x,y))
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()

why is my image getting covered?

I started watching a youtube video series on learning pygame by sentdex.
I have been following all his steps and i got to the point where i had a car(the image) and it was on a white screen. But, when i put in the functions to be able to move the car. Next time i ran it I could not see my car. I noticed that I could see it for a split second when i closed the screen.I have tried searching this question every way that i could think of. It is probably a small stupid mistake on my part. Thank you in advance
import pygame
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
carImg = pygame.image.load('racecar.png')
def car(x, y):
gameDisplay.blit(carImg,(x,y))
x = (display_width * 0.45)
y = (display_height * 0.6)
x_change = 0
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
car(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
Your indentation is messed up. Everything from for event in pygame.event.get(): to clock.tick(60) should be indented to show that it fits inside the while not crashed: loop. Also, crashed = True should be indented to show that it is inside the if event.type == pygame.QUIT: statement. In addition, the pygame.KEYDOWN and pygame.KEYUP comparisons should be inside your for event in pygame.event.get(): loop. Finally, you can improve speed by changing some of the ifs to elifs. This is the corrected version of the last section of your code:
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
car(x, y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()

How can you add movement to shapes in pygame?

I am using python 2.7 an tried to make a simple game using the pygame module. In the program it makes a rectangle, and what I am having trouble doing is getting it to move upon keys being pressed. I believe the problem is with the 'player.move' part in my code, but the documentation was poor for it on pygames website. Any help is appreciated.
import pygame
import random
import time
pygame.init()
white = (255,255,255)
black = (0,0,0)
displayWidth = 800
displayHeight = 800
FPS = 30
clock = pygame.time.Clock()
blockWidth = 50
blockHeight = 50
pygame.display.set_caption('Test Game')
screen = pygame.display.set_mode([displayWidth, displayHeight])
background = pygame.Surface(screen.get_size())
background.fill((white))
background = background.convert()
screen.blit(background, (0,0))
global xStart, yStart
xStart = 400
yStart = 400
global player
player = pygame.draw.rect(screen, black, ([xStart,yStart,blockWidth,blockHeight]))
pygame.display.update()
def mainloop():
global x, y
x = xStart
y = yStart
mainloop = True
pygame.display.update()
while mainloop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
if event.key == pygame.K_UP:
player.move(x, y + 10)
pygame.display.update()
if event.key == pygame.K_DOWN:
player.move(x, y - 10)
pygame.display.update()
if event.key == pygame.K_LEFT:
player.move(x - 10, y)
pygame.display.update()
if event.key == pygame.K_RIGHT:
player.move(x + 10, y)
pygame.display.update()
clock.tick(FPS)
pygame.display.flip()
mainloop()
pygame.quit()
Find tutorial (ie, Program Arcade Games With Python And Pygame) because you have many things to change.
PyGame is low-level library and you have to do everything on your own. In while loop you have to clear screen or draw background and draw player - again and again.
Here your code after modifications.
You have to learn pygame.Rect, pygame.Surface, (pygame.Sprite), events, etc.
import pygame
import random
import time
# --- constants --- (UPPER_CASE names)
WHITE = (255, 255, 255)
BLACK = (0 , 0, 0)
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 800
FPS = 30
BLOCK_WIDTH = 50
BLOCK_HEIGHT = 50
# --- functions --- (lower_case names)
def run():
mainloop = True
speed_x = 0
speed_y = 0
while mainloop:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
# - start moving -
elif event.key == pygame.K_UP:
speed_y = -10
elif event.key == pygame.K_DOWN:
speed_y = 10
elif event.key == pygame.K_LEFT:
speed_x = -10
elif event.key == pygame.K_RIGHT:
speed_x = 10
#elif event.type == pygame.KEYUP:
# # - stop moving -
# if event.key == pygame.K_UP:
# speed_y = 0
# elif event.key == pygame.K_DOWN:
# speed_y = 0
# elif event.key == pygame.K_LEFT:
# speed_x = 0
# elif event.key == pygame.K_RIGHT:
# speed_x = 0
# --- updates ---
player_rect.move_ip(speed_x, speed_y)
# --- draws ---
screen.blit(background, background_rect)
screen.blit(player, player_rect)
pygame.display.flip()
clock.tick(FPS)
# --- main ---
pygame.init()
pygame.display.set_caption('Test Game')
screen = pygame.display.set_mode( (DISPLAY_WIDTH, DISPLAY_HEIGHT) )
screen_rect = screen.get_rect()
background_rect = screen_rect
background = pygame.Surface(background_rect.size)
background.fill(WHITE)
background = background.convert()
player_rect = pygame.Rect(400, 400, BLOCK_WIDTH, BLOCK_HEIGHT)
player = pygame.Surface(player_rect.size)
player.fill(BLACK)
clock = pygame.time.Clock()
run()
pygame.quit()

Categories