I wrote this simple program on Raspberry Pi from the user guide. The problem is, that when I run it, Python says that video system not declared in line 29 (for event in pygame.event.get():). I tried initializing pygame twice, but it didn't work. Any suggestions how can I fix it?
#!/usr/bin/env python
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Raspberry Snake')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
def gameOver():
gameOveerFont = pygame.font.Font('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0,list(snakePosition))
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect (position[0], position[1], 20, 20))
pygame.draw.rect(playSurface,redColour,Rect (raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
if snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver()
fpsClock.tick(20)}
1) Have you installed PyGame correctly?
2) If so... explore around with the locals. See if there's a specific pygame.video initilization.
3) Or, try using another IDE, like IDLE
I hope I helped!
Related
This question already has an answer here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
Closed 5 months ago.
This is what is happening:
I need help avoiding this from happening, I'm using an array called snake_position where the x and y coordinates are stored, with AWSD keys I move by adding and substracting by 10 and therefore I'm moving the rect position. I'm triying to only move one rect in the screen and not have this long drawing in the screen.
My Code:
import pygame
import time
import random
WIDTH = 800
HEIGHT = 600
FPS = 30
FramePerSec = pygame.time.Clock()
snake_position = [100, 50]
snake_body = [100, 50]
pygame.init()
wn = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("SNAKE")
direction = 0
change_to = direction
white = pygame.Color(255, 255, 255)
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
change_to = 'UP'
if event.key == pygame.K_s:
change_to = 'DOWN'
if event.key == pygame.K_a:
change_to = 'LEFT'
if event.key == pygame.K_d:
change_to = 'RIGHT'
# If two keys pressed simultaneously
# we don't want snake to move into two
# directions simultaneously
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Moving the snake
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'RIGHT':
snake_position[0] += 10
if event.type == pygame.QUIT:
pygame.quit()
pygame.draw.rect(wn, white,
pygame.Rect(snake_position[0], snake_position[1], 20, 20))
pygame.display.update()
FramePerSec.tick(FPS)
You should see it in every tutorial - you have to clear screen in every loop - ie. wn.fill('black')
wn.fill('black') # <--- clear screen before new drawings
pygame.draw.rect(wn, white,
pygame.Rect(snake_position[0], snake_position[1], 20, 20))
pygame.display.update()
FramePerSec.tick(FPS)
I just wrote a snake game using pygame module.
After testing, I found that when I rapidly change the snake direction. E.g. pressing two arrow keys very fast to move snake body to next line or change to opposite direction, the snake doesn't respond accurately. Most of the time it will work, but there are few times snake doesn't move. I believe this is because of the low FPS, but if I increase it, the snake will move so fast.
Here is the code:
# snake game
import pygame, sys, random, time
# game initialization
check_errors = pygame.init()
if check_errors[1] > 0:
print('(!) Got {0} errors during initializing pygame \
exiting...'.format(check_errors[1]))
sys.exit(-1)
else:
print('(+) pygame successfully initialized.')
# game screen
screen_width = 750
screen_height = 495
game_screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Snake game')
# colors
red = pygame.Color(255, 0, 0) # game over
green = pygame.Color(0, 255, 0) # snake body
black = pygame.Color(0, 0, 0) # player score
white = pygame.Color(255, 255, 255) # game background
brown = pygame.Color(165, 42, 42) # food
# FPS controller
fps_controller = pygame.time.Clock()
# game variables
start_x = 300
start_y = 150
step = 15 # block width is 10
initial_body_length = 3
snake_head = [start_x, start_y] # snake start position [x, y]
# initialize snake body, index 0 contains the snake head
snake_body = [[start_x - i * step, start_y] for i in range(initial_body_length)]
score = 0
level = 1
food_pos = [random.randrange(2, screen_width / step - 1) * step, \
random.randrange(2, screen_height / step - 1) * step] # don't put food at the border of the screen
food_spawn = True
direction = 'RIGHT'
next_direction = direction # new direction after user hits keyboard
def draw_game_menu():
count = 3
my_font = pygame.font.SysFont('monaco', 60)
while True:
game_screen.fill(white)
start_surface = my_font.render('Start in {0} seconds.'.format(count), True, black)
start_rect = start_surface.get_rect()
start_rect.midtop = (screen_width / 2, 80)
game_screen.blit(start_surface, start_rect)
esc_surface = my_font.render('''Press Esc to exit during game.''', True, black)
esc_rect = esc_surface.get_rect()
esc_rect.midtop = (screen_width / 2, 150)
game_screen.blit(esc_surface, esc_rect)
pause_surface = my_font.render('''Press Space to pause the game.''', True, black)
pause_rect = pause_surface.get_rect()
pause_rect.midtop = (screen_width / 2, 220)
game_screen.blit(pause_surface, pause_rect)
pygame.display.flip() # update the game screen
time.sleep(1)
fps_controller.tick()
count -= 1
if count == 0: break
def draw_game_pause():
my_font = pygame.font.SysFont('monaco', 40)
while True:
pause_surface = my_font.render('Press Space to continue.', True, black)
pause_rect = pause_surface.get_rect()
pause_rect.midtop = (screen_width / 2, 150)
game_screen.blit(pause_surface, pause_rect)
pygame.display.flip()
fps_controller.tick()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: return
def show_score(game_over=False):
my_font = pygame.font.SysFont('monaco', 40)
score_surface = my_font.render('Score: {0}'.format(score), True, black)
score_rect = score_surface.get_rect()
if game_over == False:
score_rect.midtop = (75, 10)
else:
score_rect.midtop = (screen_width / 2, 130)
game_screen.blit(score_surface, score_rect)
# game over function
def draw_game_over():
my_font = pygame.font.SysFont('monaco', 60)
GO_surface = my_font.render('Game Over !', True, red)
GO_rect = GO_surface.get_rect()
GO_rect.midtop = (screen_width/2, 60)
game_screen.blit(GO_surface, GO_rect)
show_score(game_over=True)
pygame.display.flip() # update the game screen
time.sleep(4)
pygame.quit() # quit the game
sys.exit() # exit the console
def get_food(food_pos, snake_body):
for block in snake_body:
if block[0] == food_pos[0] and block[1] == food_pos[1]:
return True
return False
# game start menu
draw_game_menu()
# main logic of the game
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN: # if user press any button
if event.key == pygame.K_RIGHT or event.key == ord('d'):
next_direction = 'RIGHT'
elif event.key == pygame.K_LEFT or event.key == ord('a'):
next_direction = 'LEFT'
elif event.key == pygame.K_UP or event.key == ord('w'):
next_direction = 'UP'
elif event.key == pygame.K_DOWN or event.key == ord('s'):
next_direction = 'DOWN'
elif event.key == pygame.K_ESCAPE: # if user choose to quit the game
pygame.event.post(pygame.event.Event(pygame.QUIT))
elif event.key == pygame.K_SPACE:
draw_game_pause()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# validation of direction
if next_direction == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
elif next_direction == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif next_direction == 'DOWN' and direction != 'UP':
direction = 'DOWN'
elif next_direction == 'UP' and direction != 'DOWN':
direction = 'UP'
# move snake head
if direction == 'RIGHT':
snake_head[0] += step
elif direction == 'LEFT':
snake_head[0] -= step
elif direction == 'DOWN':
snake_head[1] += step
elif direction == 'UP':
snake_head[1] -= step
# move snake body mechanism
# 1. insert a new block at the beginning of the body
# 2. check if snake has reached a food
# 2.1 if yes, then keep the modified body
# 2.2 if not, then delete the end of the body
snake_body.insert(0, list(snake_head))
if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
food_spawn = False
score += 1
else:
snake_body.pop()
while food_spawn == False:
food_pos = [random.randrange(2, screen_width / step - 1) * step,
random.randrange(2, screen_height / step - 1) * step]
if get_food(food_pos, snake_body) == True:
food_spawn = False
else:
food_spawn = True
# fill game background
game_screen.fill(white)
# draw snake body
for pos in snake_body:
pygame.draw.rect(game_screen, green, pygame.Rect(pos[0], pos[1], step, step))
# draw food
pygame.draw.rect(game_screen, brown, pygame.Rect(food_pos[0], food_pos[1], step, step))
# check if snake hits the border
if (snake_head[0] > screen_width - step) or (snake_head[0] < 0) or \
(snake_head[1] > screen_height - step) or (snake_head[1] < 0):
draw_game_over()
# check if snake hits itself
for block in snake_body[1:]:
if snake_head[0] == block[0] and snake_head[1] == block[1]:
draw_game_over()
level = score//5 + 1
if level > 3:
level = 3
show_score(game_over=False)
pygame.display.flip()
if level == 1:
fps_controller.tick(8)
elif level == 2:
fps_controller.tick(10)
elif level == 3:
fps_controller.tick(12)
Please help to see if there is a way to improve, thanks.
First of all, you should try to use a single main loop.
While you're rendering the start or end screen, you can't interact with the window because no event loop runs. It's very annoying that you can't move or close the window during that time. Maybe take a look here for an example of how to handle this.
Second, really use a higher framerate, and don't tie the speed of your game objects to the frame rate.
There are several ways to handle this, an example is to use an event that signals when the snake should move. Here's an example I wrote for another question.
Here's a simple implementation for your current code:
MOVE_SNAKE = pygame.USEREVENT
pygame.time.set_timer(MOVE_SNAKE, 300)
# main logic of the game
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN: # if user press any button
if event.key == pygame.K_RIGHT or event.key == ord('d'):
next_direction = 'RIGHT'
elif event.key == pygame.K_LEFT or event.key == ord('a'):
next_direction = 'LEFT'
elif event.key == pygame.K_UP or event.key == ord('w'):
next_direction = 'UP'
elif event.key == pygame.K_DOWN or event.key == ord('s'):
next_direction = 'DOWN'
elif event.key == pygame.K_ESCAPE: # if user choose to quit the game
pygame.event.post(pygame.event.Event(pygame.QUIT))
elif event.key == pygame.K_SPACE:
draw_game_pause()
elif event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == MOVE_SNAKE:
# move snake head
if direction == 'RIGHT':
snake_head[0] += step
elif direction == 'LEFT':
snake_head[0] -= step
elif direction == 'DOWN':
snake_head[1] += step
elif direction == 'UP':
snake_head[1] -= step
# move snake body mechanism
# 1. insert a new block at the beginning of the body
# 2. check if snake has reached a food
# 2.1 if yes, then keep the modified body
# 2.2 if not, then delete the end of the body
snake_body.insert(0, list(snake_head))
if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
food_spawn = False
score += 1
else:
snake_body.pop()
# validation of direction
if next_direction == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
elif next_direction == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif next_direction == 'DOWN' and direction != 'UP':
direction = 'DOWN'
elif next_direction == 'UP' and direction != 'DOWN':
direction = 'UP'
while food_spawn == False:
food_pos = [random.randrange(2, screen_width / step - 1) * step,
random.randrange(2, screen_height / step - 1) * step]
if get_food(food_pos, snake_body) == True:
food_spawn = False
else:
food_spawn = True
# fill game background
game_screen.fill(white)
# draw snake body
for pos in snake_body:
pygame.draw.rect(game_screen, green, pygame.Rect(pos[0], pos[1], step, step))
# draw food
pygame.draw.rect(game_screen, brown, pygame.Rect(food_pos[0], food_pos[1], step, step))
# check if snake hits the border
if (snake_head[0] > screen_width - step) or (snake_head[0] < 0) or \
(snake_head[1] > screen_height - step) or (snake_head[1] < 0):
draw_game_over()
# check if snake hits itself
for block in snake_body[1:]:
if snake_head[0] == block[0] and snake_head[1] == block[1]:
draw_game_over()
new_level = score//5 + 1
if new_level != level:
pygame.time.set_timer(MOVE_SNAKE, 300 / new_level)
if new_level <= 3:
level = new_level
show_score(game_over=False)
pygame.display.flip()
fps_controller.tick(60)
See how easy it is now to control the speed of the snake: it moves now every 300ms.
I am attempting to build a simple game with two sprites. I can't figure out how to add code that detects if a sprite is touching the other. I am also having trouble understanding the countless tutorials on this topic. If you could try and explain this to me as simply as possible that would be amazing!
import pygame
import sys
from pygame.locals import *
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
bg = black
square = pygame.image.load('square.png')
square1 = pygame.image.load('square1.png')
screen = pygame.display.set_mode((640, 400))
UP = 'UP'
DOWN = 'DOWN'
LEFT = 'LEFT'
RIGHT = 'RIGHT'
direction = RIGHT
movex, movey, movex1, movey1 = 100, 100, 200, 200
class player1(pygame.sprite.Sprite):
"""Player 1"""
def __init__(self, xy):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('square.png')
self.rect = self.image.get_rect()
class player2(pygame.sprite.Sprite):
"""Player 2"""
def __init__(self, xy):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('square1.png')
self.rect = self.image.get_rect()
while True:
screen.fill(black)
collide = pygame.sprite.collide_mask(player1, player2)
if collide == True:
print 'collision!'
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_w:
movey -= 10
elif event.key == K_s:
movey += 10
elif event.key == K_a:
movex -= 10
elif event.key == K_d:
movex += 10
if event.key == K_UP:
movey1 -= 10
elif event.key == K_DOWN:
movey1 += 10
elif event.key == K_LEFT:
movex1 -= 10
elif event.key == K_RIGHT:
movex1 += 10
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.blit(square, (movex, movey))
screen.blit(square1, (movex1, movey1))
pygame.display.update()
Some issues first:
pygame.sprite.collide_mask never returns True. It returns a point or None. So your check collide == True will never be evaluate to True
pygame.sprite.collide_mask excepts two Sprite instances, but you call it with class objects as arguments (collide_mask(player1, player2))
You only need pygame.sprite.collide_mask when you want to do pixel perfect collision detection
You actually don't use the classes player1 and player2 in the rest of your code
If you're using the Sprite class, a simply way for collision detection is to use the Group class. But since you only have two Sprites, you can simple check for an intersection of their Rects using colliderect.
I've updated your code to make use of the Sprite class:
import pygame
import sys
from pygame.locals import *
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((640, 400))
class Player(pygame.sprite.Sprite):
def __init__(self, image, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.rect = self.image.get_rect(x=x, y=y)
player1, player2 = Player('square.png', 100, 100), Player('square1.png', 200, 200)
players = pygame.sprite.Group(player1, player2)
while True:
screen.fill(black)
if player1.rect.colliderect(player2.rect):
print 'collision!'
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_w:
player1.rect.move_ip(0, -10)
elif event.key == K_s:
player1.rect.move_ip(0, 10)
elif event.key == K_a:
player1.rect.move_ip(-10, 0)
elif event.key == K_d:
player1.rect.move_ip(10, 0)
if event.key == K_UP:
player2.rect.move_ip(0, -10)
elif event.key == K_DOWN:
player2.rect.move_ip(0, 10)
elif event.key == K_LEFT:
player2.rect.move_ip(-10, 0)
elif event.key == K_RIGHT:
player2.rect.move_ip(10, 0)
if event.type == QUIT:
pygame.quit()
sys.exit()
players.draw(screen)
pygame.display.update()
Collision detection is a broad topic, but this should get you started.
My goal for this question is to be able to achieve an answer which explains how to make it so that when my character moves around to pick up the 'baddie(s)', the baddies will then automatically re-spawn onto the screen. Keeping total amount of sprites on the screen at any one time for the player to pick up at 40.
I am having problems being able to control the way the 'pikachu.jpg' sprites spawn. I am either able to spawn the sprites solely in a group fashion by entering an integer into my program manually or i write my attempt to test it wrong and the program upholds an infinite loop of drawing baddie sprites. I had set up a system which i believed should have coped with keeping the baddies at 40 sprites solid, though it did not work. I am not very good with python yet and i would really appreciate help with this issue.
import necessary pygame modules
import sys
import random
import time
import pygame
from pygame.locals import *
# initialise pygame
pygame.init()
# define window width and height variables for ease of access
WindowWidth = 600
WindowHeight = 500
global PLAY
PLAY = False
x = 600 / 3
y = 460 / 2 - 25
# load and define image sizes
enemyImage = pygame.image.load('pikachu.jpg')
enemyStretchedImage = pygame.transform.scale(enemyImage, (40,40))
screen = pygame.display.set_mode((WindowWidth, WindowHeight))
def play(PLAY):
playerImage = pygame.image.load('player.jpg')
playerStretchedImage = pygame.transform.scale(playerImage, (40, 40))
movex,movey = 0,0
charx, chary=300, 200
enemyy, enemyx = 10, 10
moveright = False
moveleft = False
spawn = True
direction = 'down'
baddie = []
for i in range(20):
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40), random.randint(0, 0), 40, 40))
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == ord('m'):
pygame.mixer.music.stop()
music = False
if event.key == ord('n'):
pygame.mixer.music.play()
music = True
if event.key == ord('a'):
moveleft = True
if event.key == ord('d'):
moveright = True
if event.key == ord('w'):
movey = -0.5
if event.key == ord('s'):
movey = 0.5
if event.key == ord('p'):
time.sleep(5)
if event.type ==KEYUP:
if event.key == ord('a'):
moveleft = False
if moveleft == False:
movex = 0
if event.key == ord('d'):
moveright = False
if moveright == False:
movex = 0
if event.key == ord('w'):
movey = 0
if event.key == ord('s'):
movey = 0
elif event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
pygame.quit()
sys.exit()
screen.fill(pygame.Color("red"))
player = pygame.Rect(charx, chary, 40, 40)
if direction == 'down':
enemyy += 0.1
if moveright ==True:
movex = 0.5
if moveleft ==True:
movex = -0.5
if player.bottom > WindowHeight:
chary = WindowHeight - 40
movey = 0
if player.top < 0:
chary = 1
movey = 0
if player.left < 0:
charx = 1
movex = 0
if player.right > WindowWidth:
charx = WindowWidth - 40
movex = 0
for bad in baddie[:]: #Here is where my attempt of testing was.
if bad < 40:
spawn = True
if bad >= 40:
spawn = False
if spawn == True:
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40), random.randint(0,0), 40, 40))
screen.blit(playerStretchedImage, player)
charx+=movex
chary+=movey
for bad in baddie[:]:
if player.colliderect(bad):
baddie.remove(bad)
for bad in baddie:
screen.blit(enemyStretchedImage, bad)
pygame.display.update()
def presskey():
myfont = pygame.font.SysFont("monospace", 30)
label = myfont.render("press space to play!", 1, (255,125,60))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_SPACE:
PLAY = True
if PLAY == True:
play(PLAY)
return
screen.fill(pygame.Color("cyan"))
screen.blit(label, (x,y))
pygame.display.update()
presskey()
Here you're trying to fill up count of baddies up to 40, but the bad is a rectangle and you're using it as a number of buddies:
for bad in baddie[:]: #Here is where my attempt of testing was.
if bad < 40:
spawn = True
if bad >= 40:
spawn = False
if spawn == True:
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40), random.randint(0,0), 40, 40))
I suggest you to replace those lines with:
if len(baddie)<40:
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40),
You can get the number of items in your [] list using len(baddie). You should get a new baddie each game loop cycle.
My sprite image is not displaying in the pygame window. It's probably something really simple, but I don't understand why it isn't showing. I'm fairly new to programming, so it's probably why I don't understand this. Is it something I've done wrong in the class itself? Here is my code:
import pygame, sys
from pygame.locals import *
windowwidth = 600
windowheight = 600
WALLWIDTH = 30
WALLHEIGHT = 30
PLAYERWIDTH = 20
PLAYERHEIGHT = 20
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
LIMEGREEN = (50, 205, 50)
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('Green circle png.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def changespeed(self, x, y):
self.change_x = x
self.change_y = y
def update_pos(self, x, y):
old_x_pos = self.rect.x
new_x_pos = old_x_pos + self.change_x
self.rect.x = new_x_pos
old_y_pos = self.rect.y
new_y_pos = old_y_pos + self.change_y
self.rect.x = new_y_pos
def main():
pygame.init()
thescreen = pygame.display.set_mode((windowwidth, windowheight))
pygame.display.set_caption('Maze Game')
thescreen.fill((BLACK))
mainclock = pygame.time.Clock()
running = True
while running == True:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if (event.key == K_UP or event.key == K_w):
Player.changespeed = (-3, 0)
elif (event.key == K_DOWN or event.key == K_s):
Player.changespeed = (3, 0)
elif (event.key == K_LEFT or event.key == K_a):
Player.changespeed = (0, -3)
elif (event.key == K_RIGHT or event.key == K_d):
Player.changespeed = (0, 3)
if event.type == KEYUP:
if (event.key == K_UP or event.key == K_w):
Player.changespeed = (0, 0)
elif (event.key == K_DOWN or event.key == K_s):
Player.changespeed = (0, 0)
elif (event.key == K_LEFT or event.key == K_a):
Player.changespeed = (0, 0)
elif (event.key == K_RIGHT or event.key == K_d):
Player.changespeed = (0, 0)
mainclock.tick(60)
pygame.display.update()
pygame.quit()
if __name__ == '__main__':
main()
You need to draw the player on the screen. Call some code to draw it, (this is easiest to do in a render updates group but you could simply blit it as well). You probably also want to call the update function, but I won't include that in my example. Here is what you can do:
players = pygame.sprite.RenderUpdates()
players.add(Player(200,200))
def mainloop():
while running == True:
pygame.display.update(players.draw(thescreen))
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if (event.key == K_UP or event.key == K_w):
Player.changespeed = (-3, 0)
elif (event.key == K_DOWN or event.key == K_s):
Player.changespeed = (3, 0)
elif (event.key == K_LEFT or event.key == K_a):
Player.changespeed = (0, -3)
elif (event.key == K_RIGHT or event.key == K_d):
Player.changespeed = (0, 3)
if event.type == KEYUP:
if (event.key == K_UP or event.key == K_w):
Player.changespeed = (0, 0)
elif (event.key == K_DOWN or event.key == K_s):
Player.changespeed = (0, 0)
elif (event.key == K_LEFT or event.key == K_a):
Player.changespeed = (0, 0)
elif (event.key == K_RIGHT or event.key == K_d):
Player.changespeed = (0, 0)