im new to pygame and i tried to make a simple pong game from scratch, and i cant manage to make the game restartabel. I Tried to do a while loop in a while loop.
When you loose it jumps to the lose loop and shows what its supposed to show, and everything works fine there are no error messages but the restar just doesnt seem to work.
import pygame
from pygame import rect
from pygame.constants import KEYDOWN, KEYUP
import random
def drawText(t, x, y):
text = font.render(t, True, YELLOW, GREY)
text_rectangle = text.get_rect()
text_rectangle.topleft = (x,y)
screen.blit(text, text_rectangle)
# constant Variables
WIDTH = 800
HEIGHT = 600
FPS = 60
GREY = (89, 88, 78)
YELLOW = (232, 219, 93)
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
icon = pygame.image.load("pong.png")
clock = pygame.time.Clock()
# Init
pygame.init()
# Create the Window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
pygame.display.set_icon(icon)
font = pygame.font.Font(pygame.font.get_default_font(), 24)
playerOneY = 200
playerTwoY = 200
ballY = HEIGHT / 2
ballX = WIDTH / 2
up1 = False
up2 = False
down1 = False
down2 = False
ballY = 300
ballX = 400
ballDx = 4
ballDy = 4
score = 0
lose = False
running = True
# game loop
while running:
clock.tick(FPS)
# QUIT
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == pygame.K_w:
up1 = True
if event.key == pygame.K_s:
down1 = True
if event.key == pygame.K_UP:
up2 = True
if event.key == pygame.K_DOWN:
down2 = True
elif event.type == KEYUP:
if event.key == pygame.K_w:
up1 = False
if event.key == pygame.K_s:
down1 = False
if event.key == pygame.K_UP:
up2 = False
if event.key == pygame.K_DOWN:
down2 = False
player1 = pygame.Rect(10, playerOneY, 20, 200)
player2 = pygame.Rect(770, playerTwoY, 20, 200)
ball = pygame.Rect(ballX, ballY, 20, 20)
# input
# Ball Collition
ballX += ballDx
ballY += ballDy
if (ball.colliderect(player1)):
ballDx = abs(ballDx)
score += 1
print(score / 3)
elif (ball.colliderect(player2)):
ballDx = abs(ballDx) * -1
score += 1
print(score / 3)
elif(ballY <= 0):
ballDy = abs(ballDy)
elif(ballY >= HEIGHT):
ballDy = abs(ballDy) * -1
elif(ballX >= WIDTH):
running = False
lose = True
elif(ballX <= 0):
running = False
lose = True
# Player Movement
if up1 == True:
playerOneY -= 5
if up2 == True:
playerTwoY -= 5
if down1 == True:
playerOneY += 5
if down2 == True:
playerTwoY += 5
# Boundaries
if playerOneY < 0:
playerOneY = 0
if playerOneY > 400:
playerOneY = 400
if playerTwoY < 0:
playerTwoY = 0
if playerTwoY > 400:
playerTwoY = 400
# Draw
# Player 1
screen.fill(BLACK)
# Score
drawText(str(score), 400, 50)
pygame.draw.rect(screen, WHITE, player1)
# Player 2
pygame.draw.rect(screen, WHITE, player2)
# Ball
pygame.draw.rect(screen, WHITE, ball)
# update
pygame.display.flip()
while lose:
for event in pygame.event.get():
if event.type == pygame.QUIT:
lose = False
if event.type == KEYDOWN:
if event.key == pygame.K_q:
lose = False
if event.key == pygame.K_r:
lose = False
if event.type == KEYUP:
if event.key == pygame.K_r:
running = True
screen.fill(BLACK)
drawText("You Lost!", 350, 200)
drawText("You had", 355, 250)
drawText(str(score), 400, 300)
drawText("Points", 370, 350)
drawText("Press Q to QUIT or R to Restart", 250, 400)
pygame.display.flip()
# quit
pygame.quit()
You have to put almost all in another while-loop and use correct values for lose, running, repeate
import pygame
from pygame import rect
from pygame.constants import KEYDOWN, KEYUP
import random
# --- constants ---
# constant Variables
WIDTH = 800
HEIGHT = 600
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GREY = (89, 88, 78)
YELLOW = (232, 219, 93)
# --- functions ---
def drawText(t, x, y):
text = font.render(t, True, YELLOW, GREY)
text_rectangle = text.get_rect()
text_rectangle.topleft = (x,y)
screen.blit(text, text_rectangle)
# --- main ---
# Init
pygame.init()
#icon = pygame.image.load("pong.png")
# Create the Window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
#pygame.display.set_icon(icon)
font = pygame.font.Font(pygame.font.get_default_font(), 24)
restart = True
while restart:
playerOneY = 200
playerTwoY = 200
ballY = HEIGHT / 2
ballX = WIDTH / 2
up1 = False
up2 = False
down1 = False
down2 = False
ballY = 300
ballX = 400
ballDx = 4
ballDy = 4
score = 0
# - mainloop -
clock = pygame.time.Clock()
lose = False
running = True
# game loop
while running:
clock.tick(FPS)
# QUIT
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == pygame.K_w:
up1 = True
if event.key == pygame.K_s:
down1 = True
if event.key == pygame.K_UP:
up2 = True
if event.key == pygame.K_DOWN:
down2 = True
elif event.type == KEYUP:
if event.key == pygame.K_w:
up1 = False
if event.key == pygame.K_s:
down1 = False
if event.key == pygame.K_UP:
up2 = False
if event.key == pygame.K_DOWN:
down2 = False
player1 = pygame.Rect(10, playerOneY, 20, 200)
player2 = pygame.Rect(770, playerTwoY, 20, 200)
ball = pygame.Rect(ballX, ballY, 20, 20)
# input
# Ball Collition
ballX += ballDx
ballY += ballDy
if ball.colliderect(player1):
ballDx = abs(ballDx)
score += 1
print(score / 3)
elif ball.colliderect(player2):
ballDx = abs(ballDx) * -1
score += 1
print(score / 3)
elif ballY <= 0:
ballDy = abs(ballDy)
elif ballY >= HEIGHT:
ballDy = abs(ballDy) * -1
elif ballX >= WIDTH:
running = False
lose = True
elif ballX <= 0:
running = False
lose = True
# Player Movement
if up1 == True:
playerOneY -= 5
if up2 == True:
playerTwoY -= 5
if down1 == True:
playerOneY += 5
if down2 == True:
playerTwoY += 5
# Boundaries
if playerOneY < 0:
playerOneY = 0
if playerOneY > 400:
playerOneY = 400
if playerTwoY < 0:
playerTwoY = 0
if playerTwoY > 400:
playerTwoY = 400
# Draw
# Player 1
screen.fill(BLACK)
# Score
drawText(str(score), 400, 50)
pygame.draw.rect(screen, WHITE, player1)
# Player 2
pygame.draw.rect(screen, WHITE, player2)
# Ball
pygame.draw.rect(screen, WHITE, ball)
# update
pygame.display.flip()
while lose:
for event in pygame.event.get():
if event.type == pygame.QUIT:
lose = False
running = False
restart = False
if event.type == KEYDOWN:
if event.key == pygame.K_q:
lose = False
running = False
restart = False
if event.key == pygame.K_r:
lose = False
running = False
screen.fill(BLACK)
drawText("You Lost!", 350, 200)
drawText("You had", 355, 250)
drawText(str(score), 400, 300)
drawText("Points", 370, 350)
drawText("Press Q to QUIT or R to Restart", 250, 400)
pygame.display.flip()
# quit
pygame.quit()
Related
EDIT: I've now flipped the sprite, but when the animation plays on the flipped sprite, it has a black background instead of blending in with the major background. Just updated my code to the current situation. (2/8/2021)
I'm trying to flip a sprite in pygame, for example, I don't want them running left but looking right, which is what is happening right now.
The part that is giving me issues is the second comment that says ISSUES.
Here is my code (spritesheet is a class that transforms the image into a surface):
import pygame
import os
import sys
import random
from pygame.locals import *
import spritesheet
import time
pygame.init()
clock = pygame.time.Clock()
FPS = 60
prev_time = time.time()
pygame.display.set_caption('Platformer')
BG_COLOR = (50, 50, 50)
BLACK = (0, 0, 0)
WIN_SIZE = [1920,1080]
WIN = pygame.display.set_mode((WIN_SIZE[0], WIN_SIZE[1]), 0, 32)
# CONFIGURING Animations
IDLE_INDEX = 0
RUN_INDEX = 0
moving_right = False
moving_left = False
lookingRight = True
speed = 4
animation_tick = 8
player_location = [50, 50]
player_y_momentum = 0
player_rect = pygame.Rect(player_location[0] + 155, player_location[1] + 140, 70, 133)
def retrieve_list(animType, image):
if animType == "idle":
IDLE_FRAMES = []
IDLE_STEPS = 9
sprite_sheet = spritesheet.SpriteSheet(image)
for step in range(IDLE_STEPS):
newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
IDLE_FRAMES.append(newFRAME)
return IDLE_FRAMES
if animType == "run":
RUN_FRAMES = []
RUN_STEPS = 9
sprite_sheet = spritesheet.SpriteSheet(image)
for step in range(RUN_STEPS):
newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
RUN_FRAMES.append(newFRAME)
return RUN_FRAMES
sprite_sheet_img_IDLE = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Idle.png')
sprite_sheet_img_RUN = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Run.png')
IDLE_FRAMES = retrieve_list("idle", sprite_sheet_img_IDLE)
RUN_FRAMES = retrieve_list("run", sprite_sheet_img_RUN)
currentANIMATION = "idle"
playingAnim = None
while True:
clock.tick(FPS)
now = time.time()
dt = now - prev_time
prev_time = now
WIN.fill(BG_COLOR)
if currentANIMATION == "idle":
if player_location[1] > WIN_SIZE[1] - IDLE_FRAMES[IDLE_INDEX].get_height():
player_y_momentum = -player_y_momentum
else:
player_y_momentum += 0.2
player_location[1] += player_y_momentum
elif currentANIMATION == "run":
if player_location[1] > WIN_SIZE[1] - RUN_FRAMES[RUN_INDEX].get_height():
player_y_momentum = -player_y_momentum
else:
player_y_momentum += 0.2
player_location[1] += player_y_momentum
if moving_right:
currentANIMATION = "run"
if not lookingRight:
lookingRight = True
WIN.fill(BG_COLOR)
playingAnim = WIN.blit(RUN_FRAMES[RUN_INDEX], (player_location[0], player_location[1]))
player_location[0] += speed
if moving_left:
currentANIMATION = "run"
if lookingRight:
lookingRight = False
leftFrame = pygame.transform.flip(RUN_FRAMES[RUN_INDEX], True, False)
WIN.fill(BG_COLOR)
playingAnim = WIN.blit(leftFrame, (player_location[0], player_location[1]))
player_location[0] -= speed
elif moving_right != True and moving_left != True:
currentANIMATION = "idle"
WIN.fill(BG_COLOR)
playingAnim = WIN.blit(IDLE_FRAMES[IDLE_INDEX], (player_location[0], player_location[1]))
player_rect.x = player_location[0] + 155
player_rect.y = player_location[1] + 140
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
moving_right = True
if event.key == K_LEFT or event.key == ord('a'):
moving_left = True
if event.type == KEYUP:
if event.key == K_RIGHT or event.key == ord('d'):
moving_right = False
if event.key == K_LEFT or event.key == ord('a'):
moving_left = False
pygame.display.update()
if animation_tick == 8: # change 20 to how ever many ticks in between animation frames
if currentANIMATION == "idle":
if IDLE_INDEX < 8:
IDLE_INDEX += 1
else:
IDLE_INDEX = 0
if currentANIMATION == "run":
if RUN_INDEX < 8:
RUN_INDEX += 1
else:
RUN_INDEX = 0
animation_tick = 0 # reset tick back to 0 after changing frame
else:
animation_tick += 1 # add 1 each iteration of the while loop
Here are the spritesheets if you want to replicate my situation:
running spritesheet:
idle spritesheet:
I've tried flipping the original surface, but then the image gets messed up with black around it, and it doesn't play the animation.
pygame.transform.flip does not flip the image in place, but returns a new image that is flipped:
flipped_image = pygame.transform.flip(image, True, False)
Forgot to add .convert_alpha() when I was flipping the image. Apparently when the image is flipped it recreates the black rectangle.
This is a game for teens.
The main guy is displayed well, the time, sound and the background are showing too.
But the bad guys and the key to press to move the bad guy are not working.
# 1 - Importing library
import pygame
from pygame.locals import *
import math
import random
# 2 - Initializing the game
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = {True, False, False, False}
playerpos =[100,100]
acc = [0,0]
arrows = []
badtimer = 100
badtimer1 = 0
badguys = [[300,100]]
healthvalue = 194
pygame.mixer.init()
# 3 - Loading images
player = pygame.image.load("resources/images/dude.png")
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")
arrow = pygame.image.load("resources/images/bullet.png")
badguyimg1 = pygame.image.load("resources/images/badguy.png")
badguyimg = badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 3.1 - Load audio
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('resources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
# 4 - keep looping through
running = 1
exitcode = 0
# 5 - clearing the screen before drawing it again
screen.fill(0)
while running:
badtimer -= 1
for x in range(int(width / grass.get_width() + 1)):
for y in range(int(height / grass.get_height() + 1)):
screen.blit(grass, (x * 100, y * 100))
screen.blit(castle, (0, 30))
screen.blit(castle, (0, 135))
screen.blit(castle, (0, 240))
screen.blit(castle, (0, 345))
# 6.1 - Seting player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1] - (playerpos[1] + 32), position[0] - (playerpos[0] + 26))
playerrot = pygame.transform.rotate(player, 360 - angle * 57.29)
playerpos1 = (playerpos[0] - playerrot.get_rect().width / 10, playerpos[1] - playerrot.get_rect().height / 2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index = 0
velx = math.cos(bullet[0]) * 10
vely = math.sin(bullet[0]) * 10
bullet[1] += velx
bullet[2] += vely
if bullet[1] < -64 or bullet[1] > 640 or bullet[2] < -64 or bullet[2] > 480:
arrows.pop(index)
# 6.3.1 - Attack castle
for bullet in arrows:
bullrect = pygame.Rect(arrow.get_rect())
bullrect.left = bullet[1]
bullrect.top = bullet[2]
if badrect.colliderect(bullrect):
acc[0] += 1
badguys.pop(index)
arrows.pop(index1)
index1 += 1
badrect = pygame.Rect(badguyimg.get_rect())
badrect.top = badguy[1]
badrect.left = badguy[0]
if badrect.left < 64:
healthvalue -= random.randint(5, 20)
badguys.pop(index)
# section 6.3.1 after if badrect.left<64:
hit.play()
# section 6.3.2 after if badrect.colliderect(bullrect):
enemy.play()
# 6.3.2 - Check for collisions
index1 = 0
# section 8, after if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
# 6.3.3 - Next bad guy
index += 1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360 - projectile[0] * 57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer == 0:
badguys.append([640, random.randint(50, 430)])
badtimer = 100 - (badtimer1 * 2)
if badtimer1 >= 35:
badtimer1 = 35
else:
badtimer1 += 5
index = 0
for badguy in badguys:
if badguy[0] < -64:
badguys.pop(index)
badguy[0] -= 7
index += 1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks()))+":"+str((pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - updating the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
exit(0)
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
You have wrong indentations.
You check keys inside if event.type == pygame.QUIT: so they are checked only when you close window.
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
# the same indentation like for other event.type
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
# the same indentation like for other event.type
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
# the same indentation like for other event.type
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# it should be outside `for event` loop
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
Similar problem is with drawing badguy.
BTW: instead of all thess settings and checkings of keys you could use pygame.key.get_pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
playerpos[1] -= 5
elif keys[pygame.K_a]:
playerpos[1] += 5
if keys[pygame.K_s]:
playerpos[0] -= 5
elif keys[pygame.K_d]:
playerpos[0] += 5
This question already has answers here:
How can you rotate the sprite and shoot the bullets towards the mouse position?
(1 answer)
calculating direction of the player to shoot pygame
(1 answer)
Shooting a bullet in pygame in the direction of mouse
(2 answers)
How to make my rectangle rotate with a rotating sprite
(1 answer)
Closed 2 years ago.
I am trying to fire a bullet from my tank
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
cannon_ball_move_change = 1
cannon_ball_move += cannon_ball_move_change
pos_x,pos_y is the position of the main character
mouse_x,mouse_y is the position of the mouse
mouse_x,mouse_y=pygame.mouse.get_pos()
mouse_radians = math.radians(-180) + math.atan2((pos_y-mouse_y),(pos_x-mouse_x))
function that moves the gun I am pointing at:
def player_gun(pos_x,pos_y,mouse_radians):
pygame.draw.line(screen,green,[pos_x,pos_y],[pos_x+20*math.cos(mouse_radians),pos_y+20*math.sin(mouse_radians)],5)
#'pygame.draw.line' draws a line(gun) that connects from the player and the direction of where the mouse is pointing at
pygame.draw.circle(screen,green,[pos_x,pos_y],5)
#this is the gun's body part
function that shoots cannonballs(bullets):
def player_cannonball(mouse_radians,cannon_ball_move,pos_x,pos_y):
cannonball_x = int(cannon_ball_move*(math.cos(mouse_radians))+pos_x)
cannonball_y = int(cannon_ball_move*(math.sin(mouse_radians))+pos_y)
pygame.draw.circle(screen,red,[cannonball_x,cannonball_y],5)
print(cannonball_x,cannonball_y)
calling the function
player_cannonball(mouse_radians,cannon_ball_move,pos_x,pos_y)
player_gun(pos_x,pos_y,mouse_radians)
Is this the right way to fire a bullet in pygame?
problem 1: When I click where I want to shoot nothing comes out of my tank
(solved by user2588654)
problem 2: After I click to shoot and I move the mouse the bullet movement is affected by the movement of my mouse
(solved by user2588654)
This is my whole code down below but you don't have to see it
The pictures:
enemy
player
background
(some variables are different from above)
pos_x+360 is pos_x
pos_y+740 is pos_y
mouse_radians is radians_pt
ball_move is cannonball_move
import pygame,math,random
pygame.init()
display_width = 1200
display_height = 800
white = (255,255,255)
black = (0,0,0)
red = (200,0,0)
yellow = (150,150,0)
green=(0,170,0)
light_yellow = (255,255,0)
light_red = (255,0,0)
role_model = car_image = pygame.image.load('player1.png')
enemy = pygame.image.load('enemy.png')
background = pygame.image.load('background.png')
clock = pygame.time.Clock()
FPS = 30
screen = pygame.display.set_mode([display_width,display_height])
screen_rect = screen.get_rect()
car_width = 16
car_height = 28
smallfont =pygame.font.SysFont('comicsansms',25)
medfont =pygame.font.SysFont('comicsansms',50)
largefont =pygame.font.SysFont('comicsansms',80)
def player_car(car_image,rect,angle,pos_x,pos_y):
rot_image,rot_rect=rotate(car_image,rect,angle)
rot_rect.centerx +=pos_x
rot_rect.centery += pos_y
screen.blit(rot_image,rot_rect)
print(rot_rect)
def player_turret(pos_x,pos_y,radians_pt):
pygame.draw.line(screen,green,[pos_x+360,pos_y+740],[pos_x+360+20*math.cos(radians_pt),pos_y+740+20*math.sin(radians_pt)],5)
pygame.draw.circle(screen,green,[pos_x+360,pos_y+740],5)
def player_cannonball(radians_pt,ball_move,pos_x,pos_y):
#cannonball_count = 0
ball_x = int(ball_move*(math.cos(radians_pt))+pos_x+360)
ball_y = int(ball_move*(math.sin(radians_pt))+pos_y+740)
pygame.draw.circle(screen,red,[ball_x,ball_y],5)
print(ball_x,ball_y)
def enemy_car(enemy,rect,angle_e,pos_x_e,pos_y_e):
rot_image_e,rot_rect_e=rotate(enemy,rect,angle_e)
rot_rect_e.centerx +=pos_x_e
rot_rect_e.centery += pos_y_e
screen.blit(rot_image_e,rot_rect_e)
def death_move(pos_x,pos_y):
color_list=[light_yellow,light_red]
for i in range(40):
a=color_list[random.randrange(0,2)]
pygame.draw.circle(screen,a,[random.randint((pos_x+360)-25,(pos_x+360)+25),random.randint((pos_y+740)-25,(pos_y+740)+25)],3)
pygame.display.update()
clock.tick(FPS)
def death():
msg_to_screen('YOU ARE DEAD',red,0,size='large')
msg_to_screen('press c to continue or q to quit',black,50)
pygame.display.update()
death = True
while death:
for event in pygame.event.get():
if event.type == pygame.QUIT:
death = False
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
gameloop()
death = False
elif event.key == pygame.K_q:
death = False
pygame.quit()
quit()
clock.tick(15)
def game_pause():
game_pause = True
msg_to_screen('PAUSED',black,0,'large')
msg_to_screen('press c to continue or q to quit',red,40)
pygame.display.update()
while game_pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
## controls = False
## gameintro = False
## running = False
## game_pause = False
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_pause = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
clock.tick(15)
def game_intro():
gameintro = True
while gameintro == True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
gameloop()
gameintro = False
if event.key == pygame.K_c:
controls()
gameintro = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(white)
msg_to_screen('CAR RACING',black,y_displace=-50,size = 'large')
msg_to_screen('press p to play and c for controls menu',red,y_displace=20)
msg_to_screen('by yeonjekim',yellow,y_displace=80)
pygame.display.update()
clock.tick(15)
def text_objects(text,color,size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def turret(pos_x_t,pos_y_t):
pygame.draw.circle(screen,black,[pos_x_t,pos_y_t],30)
def msg_to_screen(msg,color, y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg,color, size)
textRect.center = (display_width / 2), (display_height / 2)+y_displace
screen.blit(textSurf, textRect)
def controls():
controls = True
while controls == True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_b:
controls = False
game_intro()
elif event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(white)
msg_to_screen('CONTROLS',black,y_displace=-100,size = 'large')
msg_to_screen('K_LEFT: go left',green,y_displace = -40)
msg_to_screen('K_RIGHT: go right',green,y_displace = 0)
msg_to_screen('K_UP: go up',green,y_displace = 40)
msg_to_screen('K_DOWN: go down',green,y_displace = 80)
msg_to_screen('K_SPACE: break',green,y_displace = 120)
msg_to_screen('K_p: pause',green,y_displace = 160)
msg_to_screen('press b to go back to the main menu',red,y_displace = 200)
pygame.display.update()
clock.tick(15)
def rotate(image, rect, angle):
rot_image = pygame.transform.rotate(image, angle)
rot_rect = rot_image.get_rect(center=rect.center)
return rot_image,rot_rect
def carRotationPos(angle):
x=1*math.cos(math.radians(angle-90))
y=1*math.sin(math.radians(angle-90))
return x,y
def gameloop():
gameintro = False
running = True
angle = -90
radians_pt = 0
radians_pt_change = 0
angle_change = 0
changeX = 0
changeY=0
max_speed = 25
x=0
y=0
pos_x=0
pos_y=0
pos_x_e= 120
pos_y_e=-30
speed = 0
speed_change = 0
change_1=0
count = 0
count_e = 0
change_2 = 0
max_speed_e = 15
slowingdown=0
angle_e=-90
mouse_x=0
mouse_y=0
cannonball_max_count = 5
ball_move =0
ball_move_change=0
moving_up = False
moving_down = False
slowdown_up = False
slowdown_down = False
rect = role_model.get_rect(center = (360,740))#center = screen_rect.center)
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
controls = False
gameintro = False
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
game_pause()
elif event.key == pygame.K_LEFT:
angle_change = 5
elif event.key == pygame.K_RIGHT:
angle_change = -5
elif event.key == pygame.K_UP:
slowdown_up = False
slowdown_down = False
changeX=-x
changeY=y
speed_change = ((1/2)*speed_change**2 - (1/2)*speed_change+ 1)*0.2
moving_up = True
#start of my problem
elif event.key == pygame.K_DOWN:
slowdown_down = False
slowdown_up = False
changeX=x
changeY=-y
speed_change = ((1/2)*speed_change**2 - (1/2)*speed_change+ 1)*0.2
moving_down = True
elif event.key == pygame.K_SPACE:
change_1 =2
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
angle_change = 0
elif event.key == pygame.K_RIGHT:
angle_change = 0
elif event.key == pygame.K_UP:
moving_up = False
slowdown_up = True
elif event.key == pygame.K_DOWN:
moving_down = False
slowdown_down = True
elif event.key == pygame.K_SPACE:
slowingdown = 0
change_1 = 0
max_speed = 25
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]:
ball_move_change=1
ball_move += ball_move_change
mouse_x,mouse_y=pygame.mouse.get_pos()
mouse_gradient=math.atan2((pos_y+740-mouse_y),(pos_x+360-mouse_x))
radians_pt = mouse_gradient+math.radians(-180)
print(radians_pt)
player_cannonball(radians_pt,ball_move,pos_x,pos_y)
slowingdown+=change_1
if moving_up == True:
max_speed-=slowingdown
elif moving_down == True:
max_speed-=slowingdown
if changeX or changeY:
pos_x+=changeX
pos_y+=changeY
if angle == -360 or angle == 360:
angle = 0
if angle_change:
angle +=angle_change
if speed_change:
speed+=speed_change
if speed > max_speed:
speed = max_speed
screen.blit(background,(0,0))
x,y=carRotationPos(angle)
x=round(x*speed)
y=round(y*speed)
if slowdown_up == True:
changeX = -x
changeY = y
speed =speed- 1
if speed <=0:
speed = 0
if slowdown_down == True:
changeX = x
changeY = -y
speed =speed- 1
if speed <=0:
speed = 0
if moving_up:
changeX = -x
changeY = y
if moving_down:
changeX = x
changeY = -y
#collision detection
if pos_x<-341:
death_move(pos_x,pos_y)
death()
## pos_x = -341
## pos_x+=2
if pos_y<-720:
death_move(pos_x,pos_y)
death()
## pos_y=-720
## pos_y+=2
if pos_y>43:
death_move(pos_x,pos_y)
death()
## pos_y = 43
## pos_y-=2
if pos_x>820:
death_move(pos_x,pos_y)
death()
## pos_x = 820
## pos_x-=2
#enemy collision detection
#grass collison
if not(-308<pos_x<782 and -686<pos_y<13):
if count>20:
count = 20
count +=1
max_speed = 25-count
if slowingdown>4-change_1:
slowingdown = 4-change_1
if slowingdown<0:
slowingdown = 0
elif -228<pos_x<718 and -625<pos_y<-50:
if count>20:
count = 20
count +=1
max_speed = 25-count
if slowingdown>4-change_1:
slowingdown = 4-change_1
if slowingdown<0:
slowingdown = 0
else:
count = 0
max_speed = 25
if slowingdown>25-change_1:
slowingdown = 25-change_1
if slowingdown<0:
slowingdown = 0
#enemy grass collision
## if not(-308<pos_x_e<782 and -686<pos_y_e<13):
## if count_e>20:
## count_e = 20
## count_e +=1
##
## max_speed_e = 25-count_e
## if slowingdown>4-change_1:
## slowingdown = 4-change_1
## if slowingdown<0:
## slowingdown = 0
## elif -228<pos_x_e<718 and -625<pos_y_e<-50:
## if count_e>20:
## count_e = 20
## count_e +=1
## max_speed_e = 25-count #max_speed_e
## if slowingdown>4-change_1:
## slowingdown = 4-change_1
## if slowingdown<0:
## slowingdown = 0
## else:
## count_e = 0
## max_speed_e = 25
## if slowingdown>25-change_1:
## slowingdown = 25-change_1
## if slowingdown<0:
## slowingdown = 0
#end of the collision detection
#enemy car code
if angle_e == 270:
angle_e = -90
if -260<=pos_x_e<730 and pos_y_e == -30:
pos_x_e+=10#((1/2)*speed_change**2 - (1/2)*speed_change+ 1)*0.2
elif -90<=angle_e<0:
angle_e += 5
elif angle_e==0 and -657<pos_y_e<=-30:
pos_y_e -= 10
elif 0<=angle_e <90 and pos_y_e == -660:
angle_e +=5
elif pos_y_e == -660 and -260<pos_x_e<=730:
pos_x_e -=10
elif pos_y_e == -660 and pos_x_e == -260 and 90<=angle_e<180:
angle_e +=5
elif -660<=pos_y_e<-40 and pos_x_e == -260 and angle_e == 180:
pos_y_e += 10
elif -40<=pos_y_e<-30 and 180<=angle_e<270:
pos_y_e +=10/18
angle_e +=5
if pos_y_e ==-29.99999999999997:
pos_y_e = round(pos_y_e)
#pos_x_t = random.randint(30,600)
#pos_y_t = random.randint(30,600)
#turret(pos_x_t,pos_y_t)
#if enemy team reaches the yellow line enemy team earns a turret
#the enemy can shoot
#you can get items if you reach the yellow line, the item could be a gun for removing enemy turrets
player_car(car_image,rect,angle,pos_x,pos_y)
player_turret(pos_x,pos_y,radians_pt)
enemy_car(enemy,rect,angle_e,pos_x_e,pos_y_e)
msg_to_screen('speed = '+str(round(speed*5,1))+'km/h',black, y_displace=-375, size = "small")
pygame.display.update()
clock.tick(FPS)
game_intro()
pygame.quit()
i have a snake game i made in python and i want to add him boulders that will appear every 10 "apples" he gets, so can you help me please? this is the code right now
import pygame
import random
__author__ = 'Kfir_Kahanov'
init = pygame.init()
def quit_game():
"""
this function will quit the game
:return:
"""
pygame.quit()
quit()
# this will set a nice sound when the player gets an apple
BLOP = pygame.mixer.Sound("Blop.wav")
pygame.mixer.Sound.set_volume(BLOP, 1.0)
volume = pygame.mixer.Sound.get_volume(BLOP)
# making colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 155, 0)
BLUE = (0, 0, 255)
YELLOW = (217, 217, 0)
SNAKE_RED = (152, 2, 2)
def display_fill():
"""
this will fill the screen with a color of my choice
:return:
"""
game_display.fill(GREEN)
def mute():
"""
this will mute the game or unmute it
:return:
"""
if volume == 1.0:
pygame.mixer.Sound.set_volume(BLOP, 0.0)
else:
pygame.mixer.Sound.set_volume(BLOP, 10.0)
# all the pygame stuff for the display
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
game_display = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("The hungry Cobra")
ICON = pygame.image.load("apple_icon.png")
pygame.display.set_icon(ICON)
pygame.display.update()
# deciding on FPS, the size of the snake, apples, and making the fonts for the text
CLOCK = pygame.time.Clock()
BLOCK_SIZE = 20
APPLE_THICKNESS = 30
fps = 15
# BOULDER_THICKNESS = 30
direction = "right" # deciding the starting direction
tiny_font = pygame.font.SysFont("comicsansms", 10)
small_font = pygame.font.SysFont("comicsansms", 25)
med_font = pygame.font.SysFont("comicsansms", 50)
large_font = pygame.font.SysFont("comicsansms", 80)
def text_objects(text, color, size):
"""
defining the text
:param text:
:param color:
:param size:
:return:
"""
global text_surface
if size == "tiny":
text_surface = tiny_font.render(text, True, color)
if size == "small":
text_surface = small_font.render(text, True, color)
if size == "medium":
text_surface = med_font.render(text, True, color)
if size == "large":
text_surface = large_font.render(text, True, color)
return text_surface, text_surface.get_rect()
# loading apple and snake img
IMG = pygame.image.load("snake_head.png")
APPLE_IMG = pygame.image.load("apple_icon.png")
# BOULDER_IMG = pygame.image.load("boulder.png")
def rand_apple_gen():
"""
making apple function
:return:
"""
rand_apple_x = round(random.randrange(10, DISPLAY_WIDTH - APPLE_THICKNESS)) # / 10.0 * 10.0
rand_apple_y = round(random.randrange(10, DISPLAY_HEIGHT - APPLE_THICKNESS)) # / 10.0 * 10.0
return rand_apple_x, rand_apple_y
"""
def rand_boulder_gen():
making the boulder parameters
:return:
rand_boulder_x = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
rand_boulder_y = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
return rand_boulder_x, rand_boulder_y
"""
def message(msg, color, y_displace=0, size="small"):
"""
making a function for the making of the text
:param msg:
:param color:
:param y_displace:
:param size:
:return:
"""
text_surf, text_rect = text_objects(msg, color, size)
text_rect.center = ((DISPLAY_WIDTH / 2), (DISPLAY_HEIGHT / 2) + y_displace)
game_display.blit(text_surf, text_rect)
def intro_message():
"""
making the intro
:return:
"""
intro = True
while intro:
display_fill()
message("Welcome to ", BLACK, -200, "large")
message("The hungry Cobra!", BLACK, -100, "large")
message("Eat apples to grow, but be care full", BLACK)
message("if you run into yourself or outside the screen", BLACK, 30)
message("you gonna have a bad time", BLACK, 60)
message("Press S to start or E to exit", BLACK, 90)
message("Created by Kfir Kahanov", BLACK, 200, "tiny")
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
display_fill()
pygame.display.update()
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_s:
intro = False
if event.key == pygame.K_e:
display_fill()
pygame.display.update()
quit_game()
score_edit = 0
def score_f(score):
"""
making a score_f on the top left
:param score:
:return:
"""
text = small_font.render("Score:" + str(score + score_edit), True, YELLOW)
game_display.blit(text, [0, 0])
def pause_f():
"""
making a pause_f screen
:return:
"""
pause = True
if pause:
message("Paused", RED, -50, "large")
message("Press R to start over, E to exit or C to continue", BLACK)
pygame.display.update()
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
display_fill()
pygame.display.update()
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_c or pygame.K_ESCAPE or pygame.K_p:
pause = False
if event.key == pygame.K_r:
global score_edit, direction, cheat1, cheat4, cheat3, cheat2
direction = "right"
score_edit = 0
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
game_loop()
if event.key == pygame.K_e:
display_fill()
pygame.display.update()
quit_game()
CLOCK.tick(5)
# making cheats
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
def snake(snake_list):
"""
defining the snake head
:param snake_list:
:return:
"""
global head
if direction == "right":
head = pygame.transform.rotate(IMG, 270)
elif direction == "left":
head = pygame.transform.rotate(IMG, 90)
elif direction == "down":
head = pygame.transform.rotate(IMG, 180)
elif direction == "up":
head = IMG
game_display.blit(head, (snake_list[-1][0], snake_list[-1][1]))
for x_n_y in snake_list[:-1]:
pygame.draw.rect(game_display, SNAKE_RED, [x_n_y[0], x_n_y[1], BLOCK_SIZE, BLOCK_SIZE])
def game_loop():
"""
this will be the game itself
:return:
"""
global cheat1
global cheat2
global cheat3
global cheat4
global direction
global fps
game_exit = False
game_over = False
global score_edit
lead_x = DISPLAY_WIDTH / 2
lead_y = DISPLAY_HEIGHT / 2
# rand_boulder_x, rand_boulder_y = -50, -50
lead_x_change = 10
lead_y_change = 0
snake_list = []
snake_length = 1
rand_apple_x, rand_apple_y = rand_apple_gen()
while not game_exit:
if game_over:
message("Game over!", RED, -50, "large")
message("Press E to exit or R to retry.", BLACK, 20, "medium")
pygame.display.update()
while game_over:
fps = 15
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
game_over = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_e:
game_exit = True
game_over = False
if event.key == pygame.K_r:
direction = "right"
score_edit = 0
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_LEFT and lead_x_change is not BLOCK_SIZE and direction is not "right":
lead_x_change = -BLOCK_SIZE
lead_y_change = 0
direction = "left"
elif event.key == pygame.K_RIGHT and lead_x_change is not -BLOCK_SIZE and direction is not "left":
lead_x_change = BLOCK_SIZE
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP and lead_y_change is not BLOCK_SIZE and direction is not "down":
lead_y_change = -BLOCK_SIZE
lead_x_change = 0
direction = "up"
elif event.key == pygame.K_DOWN and lead_y_change is not -BLOCK_SIZE and direction is not "up":
lead_y_change = BLOCK_SIZE
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_p:
pause_f()
elif event.key == pygame.K_ESCAPE:
pause_f()
elif event.key == pygame.K_k: # the cheat
cheat1 = 0
elif event.key == pygame.K_f:
cheat2 = 4
elif event.key == pygame.K_i:
cheat3 = 0
elif event.key == pygame.K_r:
cheat4 = 3
elif cheat1 == 0 and cheat2 == 4 and cheat3 == 0 and cheat4 == 3:
score_edit = 10000
if lead_x >= DISPLAY_WIDTH or lead_x < 0 or lead_y >= DISPLAY_HEIGHT or lead_y < 0:
game_over = True
lead_x += lead_x_change
lead_y += lead_y_change
display_fill()
game_display.blit(APPLE_IMG, (rand_apple_x, rand_apple_y))
snake_head = [lead_x, lead_y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for eachSegment in snake_list[:-1]:
if eachSegment == snake_head:
game_over = True
snake(snake_list)
score_f(snake_length * 10 - 10)
pygame.display.update()
if rand_apple_x < lead_x < rand_apple_x + APPLE_THICKNESS or rand_apple_x < lead_x + BLOCK_SIZE < rand_apple_x \
+ APPLE_THICKNESS:
if rand_apple_y < lead_y < rand_apple_y + APPLE_THICKNESS or rand_apple_y < lead_y + BLOCK_SIZE < \
rand_apple_y + APPLE_THICKNESS:
pygame.mixer.Sound.play(BLOP)
rand_apple_x, rand_apple_y = rand_apple_gen()
snake_length += 1
fps += 0.15
"""
if snake_length * 10 - 10 == 20:
rand_boulder_x, rand_boulder_y = rand_boulder_gen()
game_display.blit(BOULDER_IMG, (rand_boulder_x, rand_boulder_y))
elif rand_boulder_x < lead_x < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_x < lead_x + BLOCK_SIZE < \
rand_boulder_x + BOULDER_THICKNESS:
if rand_boulder_x < lead_y < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_y < lead_y + BLOCK_SIZE < \
rand_boulder_y + BOULDER_THICKNESS:
game_over = True
"""
CLOCK.tick(fps)
display_fill()
pygame.display.update()
quit_game()
intro_message()
game_loop()
Maybe try explaining what you have tried and why it isn't working. You would get better help that way.
From what I can see from your code though....
You seem to be on the right track in your commented out code. Evaluating the snake length or score variable during your game loop, then generating a random boulder to the screen. The next step is just handling the collision logic for all the boulders, which I see two ways of doing. First way is creating a lists of the boulder attributes like the x,y positions, similar to how you did the snake list. The second way would be to create a class for boulders, then when the score, or snake length, reaches 10, create a new boulder object. Using a class may make the collision logic much easier to handle.
I am following a youtube tutorial series, and I came across this problem with my pygame game. I made a function called messagetoscreen, and it works fine in the video, but it doesn't work for me.
Here is my code:
#Imports
import pygame
pygame.init()
pygame.font.init()
import sys
import random
import cx_Freeze
import time
#Variables
playerhealth = 100
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0 ,255, 0)
windowtitle = "Climber"
sizex = 1000
sizey = 700
rect1x = 500
rect1y = 350
rect1sizex = 50
rect1sizey = 50
rect1xchange = 0
rect1ychange = 0
clock = pygame.time.Clock()
fps = 600
font = pygame.font.SysFont(None, 25)
#Functions
def messagetoscreen (msg,color):
screentext = font.render(msg, True, color)
gamedisplay.blit(screentext , [sizex / 2, sizey / 2])
#Initialization
gamedisplay = pygame.display.set_mode((sizex, sizey))
pygame.display.set_caption(windowtitle)
#Game Loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
rect1ychange -= 1
elif event.key == pygame.K_a:
rect1xchange -= 1
elif event.key == pygame.K_s:
rect1ychange += 1
elif event.key == pygame.K_d:
rect1xchange += 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
rect1ychange = 0
elif event.key == pygame.K_a:
rect1xchange = 0
elif event.key == pygame.K_s:
rect1ychange = 0
elif event.key == pygame.K_d:
rect1xchange = 0
if rect1y > 650:
rect1y = 650
if rect1x > 950:
rect1x = 950
if rect1y < 0:
rect1y = 0
if rect1x < 0:
rect1x = 0
rect1x += rect1xchange
rect1y += rect1ychange
messagetoscreen("HAPPY", red)
gamedisplay.fill(white)
pygame.draw.rect(gamedisplay, green, (rect1x, rect1y, rect1sizex, rect1sizey))
pygame.display.update()
clock.tick(fps)
I would like to know how to fix my function, and anything else that could cause an error.
The answer is that I blitted the text to the screen before I filled gamedisplay with white. Remember to blit text after drawing a background.
Here is the code that draw graphics
in the while loop:
gamedisplay.fill(white)
pygame.draw.rect(gamedisplay, green, (rect1x, rect1y, rect1sizex, rect1sizey))
messagetoscreen("HAPPY", red)