Issue running functions in pygame - python

import pygame
import random
import time
pygame.init()
backX = 1000
backY = 600
screen = pygame.display.set_mode((backX, backY))
score = 0
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
timespent = 0
pygame.display.set_caption('Monkey Simulator') # game name
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)
textsurface = myfont.render('Score: ' + str(score), False, (255, 255, 255))
pygame.mixer.init()
# music
sound = pygame.mixer.Sound('background1.mp3')
collection = pygame.mixer.Sound('collection.mp3')
gameover1 = pygame.mixer.Sound('gameover.mp3')
sound.play(-1)
# score indicator
text = myfont.render('Score: ' + str(score), True, white, blue)
textRect = text.get_rect() # getting the rectangle for the text object
textRect.center = (400 // 2, 400 // 2)
pre_background = pygame.image.load('background.jpeg')
background = pygame.transform.scale(pre_background, (backX, backY))
clock = pygame.time.Clock()
FPS = 60
vel = 6.5
BLACK = (0, 0, 0)
monkeyimg = pygame.image.load('monkey.png')
playerX = 410
playerY = 435
bananavelocity = 4
monkey = pygame.transform.scale(monkeyimg, (100, 120))
prebanana = pygame.image.load('banana.png')
bananaXList = []
def change():
if score>=5:
monkey = pygame.transform.scale(pre_shark, (100, 100))
banana = pygame.transform.scale(pre_meat, (50, 50))
background = pygame.transform.scale(underwater, (backX, backY))
for i in range(50):
value = random.randint(10, 980)
bananaXList.append(value)
valuenumber = random.randint(1, 30)
bananaX = bananaXList[valuenumber - 1]
bananaY = 0
banana = pygame.transform.scale(prebanana, (50, 50))
underwater = pygame.image.load('underwater.jpg')
pre_shark = pygame.image.load('shark.png')
pre_meat = pygame.image.load('meat.png')
banana_rect = banana.get_rect(topleft=(bananaX, bananaY))
monkey_rect = monkey.get_rect(topleft=(playerX, playerY))
run = True
black = (0, 0, 0)
# start screen
screen.blit(background, (0, 0))
myfont = pygame.font.SysFont("Britannic Bold", 50)
end_it = False
while not end_it:
myfont1 = pygame.font.SysFont("Britannic Bold", 35)
nlabel = myfont.render("Monkey Simulator", 1, (255, 255, 255))
info = myfont1.render("Use your right and left arrow keys to move the character.", 1, (255, 255, 255))
info2 = myfont1.render("Try to catch as many bananas as you can while the game speeds up!", 1, (255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
end_it = True
screen.blit(nlabel, (400, 150))
screen.blit(info, (100, 300))
screen.blit(info2, (100, 350))
pygame.display.flip()
while run:
clock.tick(FPS)
screen.fill(BLACK)
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
# banana animation
bananaY = bananaY + bananavelocity
timespent = int(pygame.time.get_ticks() / 1000)
bananavelocity = 4 + (timespent * 0.055)
vel = 6.5 + (timespent * 0.07)
# end game sequence
change()
if bananaY > 510:
bananaX = -50
bananaY = -50
banana
velocity = 0
gameover = pygame.image.load("gameover.jpg")
background = pygame.transform.scale(gameover, (backX, backY))
pygame.mixer.Sound.stop(sound)
gameover1.play()
# collecting coins sequence
if banana_rect.colliderect(monkey_rect):
collection.play()
valuenumber = random.randint(1, 30)
bananaX = bananaXList[valuenumber - 1]
bananaY = -25
score += 1
# moving character
if keys[pygame.K_LEFT] and playerX > 0:
playerX = playerX - vel
if keys[pygame.K_RIGHT] and playerX < 930:
playerX = playerX + vel
# adding the sprites to the screen
screen.blit(monkey, (playerX, playerY))
screen.blit(banana, (bananaX, bananaY))
banana_rect = banana.get_rect(topleft=(bananaX, bananaY))
monkey_rect = monkey.get_rect(topleft=(playerX, playerY))
pygame.draw.rect(screen, (150, 75, 0), pygame.Rect(0, 534, 1000, 20))
screen.blit(textsurface, (30, 0))
textsurface = myfont.render('Score: ' + str(score), False, (255, 255, 255))
pygame.display.update()
Right now I'm making a collection game. I want to use a function for replacing all the images once you hit a certain score. It doesn't work, though, no matter how high of a score you get. I don't understand the issue because I tested both the function and the if statement by putting print statements.

You have to use the global statement when you want to change a variable in the global namespace within a function:
def change():
global monkey, banana, background
if score>=5:
monkey = pygame.transform.scale(pre_shark, (100, 100))
banana = pygame.transform.scale(pre_meat, (50, 50))
background = pygame.transform.scale(underwater, (backX, backY))
If you don't use the global statement, the values are assigned to local variables in the scope of the function.
Another option is to return the new values from the function:
def change():
if score>=5:
return (
pygame.transform.scale(pre_shark, (100, 100)),
pygame.transform.scale(pre_meat, (50, 50)),
pygame.transform.scale(underwater, (backX, backY)) )
return monkey, banana, background
while True:
# [...]
monkey, banana, background = change()

Related

How to rotate an image to the cursor? [duplicate]

This question already has answers here:
How to rotate an image(player) to the mouse direction?
(2 answers)
Still Having Problems With Rotating Cannon's Properly Towards The Player Pygame
(1 answer)
How do I make image rotate with mouse python [duplicate]
(1 answer)
How do I make my player rotate towards mouse position?
(1 answer)
Closed 4 months ago.
I have a shotgun attached to my player. I want this shotgun to point at the cursor. Ive tried searching this up on google, but each time i tried the answer my shotgun kinda moved and rotated. How can i make it so it only rotates?
My code:
import pygame
import numpy
import math
import random
screen = pygame.display.set_mode((1280, 720))
class Player:
def __init__(self, pos: tuple, gravity: tuple, sprite: pygame.Surface, maxVel, minVel, maxVelY):
self.pos = pos
self.velocity = (0,0)
self.gravity = gravity
self.sprite = sprite
self.maxVel = maxVel
self.minVel = minVel
self.maxVelY = maxVelY
def addForce(self, force: tuple):
self.velocity = numpy.add(self.velocity, force)
def resetVelocity(self):
self.velocity = (0,0)
def update(self):
global scene, highscore, score, playerrect
self.velocity = numpy.add(self.velocity, (0, self.gravity/10))
if self.velocity[0] > self.maxVel:
self.velocity[0] = self.maxVel
elif self.velocity[0] < self.minVel:
self.velocity[0] = self.minVel
if self.velocity[1] > self.maxVelY:
self.velocity[1] = self.maxVelY
self.pos = numpy.subtract(self.pos, self.velocity)
if self.pos[1] < -50:
self.pos[1] += 770
elif self.pos[1] > 770:
scene = menu
self.pos = (self.sprite.get_rect(center=(1280/2, 720/2))[0], self.sprite.get_rect(center=(1280/2, 720/2))[1])
if highscore < score:
highscore = score
if self.pos[0] < 0:
self.pos[0] += 1330
if self.pos[0] > 1280:
self.pos[0] -= 1330
def draw(self): # Here is the problem
global shotgun
screen.blit(self.sprite, self.pos)
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - self.pos[0], mouse_y - self.pos[1]
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
rotshotgun = pygame.transform.rotate(shotgun, int(angle)) # Im thinking this doesnt work correctly
screen.blit(rotshotgun, (self.pos[0]+50, self.pos[1]+50))
class Particle:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
def draw(self):
pygame.draw.rect(screen, self.color, (self.x, self.y, 10, 10))
player = pygame.image.load("other/player.png").convert_alpha()
player = pygame.transform.scale(player, (100, 100))
player = Player((590, 310), -9.81, player, 10, -10, 20)
clock = pygame.time.Clock()
new_velocity = (0,0)
game = 0
menu = 1
scene = menu
shotgun = pygame.image.load("other/shotgun.png").convert_alpha()
shotgun = pygame.transform.scale(shotgun, (83, 66))
pygame.font.init()
font = pygame.font.Font("font/AlfaSlabOne-Regular.ttf", 150)
font2 = pygame.font.Font("font/PoorStory-Regular.ttf", 50)
font3 = pygame.font.SysFont("Arial", 350)
font4 = pygame.font.Font("font/Nunito-Black.ttf", 75)
titel = font.render("ShootShot", True, (0, 255, 0))
clicktext = font2.render("Click to start!", True, (0,0,0))
scoretext = font3.render("0", True, (0,0,0))
with open("other/highscore.txt", "r") as f:
highscore = f.read()
highscore.replace("\n", "")
highscore = int(highscore)
highscoretext = font4.render(f"Highscore: {highscore}", True, (0,0,0))
coins = []
for x in range(6):
coins.append(pygame.transform.scale(pygame.image.load(f"coin/coin{x+1}.png"), (50, 50)))
number = 0
particles = []
colors = [(255, 0, 0),
(0, 0, 255),
(255, 255, 0),
(255, 0, 255),
(0, 255, 255),
(255, 125, 0),
(125, 255, 0),
(0, 255, 125),
(0, 125, 255),
(125, 0, 255)]
r = True
scoretext.set_alpha(75)
scoretext = scoretext.convert_alpha()
coinLocation = (random.randint(0, 1280), random.randint(0, 720))
titlerect = titel.get_rect(center=(1280/2, 150))
scorerect = scoretext.get_rect(center=(1280/2, 720/2))
highscorerect = highscoretext.get_rect(center=(1280/2, 50))
number2 = 0
currentCoin = 0
coin = pygame.Rect(coinLocation[0], coinLocation[1], 50, 50)
score = 0
while r:
clock.tick(45)
screen.fill((255,255,255))
mousePos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
r = False
if event.type == pygame.MOUSEBUTTONDOWN:
if scene == game:
new_velocity = numpy.subtract(player.pos, mousePos)*-1
player.resetVelocity()
player.addForce(new_velocity/10)
else:
scene = game
score = 0
new_velocity = numpy.subtract(player.pos, mousePos) * -1
player.resetVelocity()
player.addForce(new_velocity / 10)
screen.blit(scoretext, scorerect)
player.draw()
if scene == game:
player.update()
screen.blit(coins[currentCoin], coinLocation)
number2 += 0.15
currentCoin = math.ceil(number2)
if currentCoin > 5:
currentCoin = 0
number2 = -1
playerrect = pygame.Rect(player.pos[0], player.pos[1], 50, 50)
if coin.colliderect(playerrect):
score += 1
scoretext = font3.render(str(score), True, (0, 0, 0))
scoretext.set_alpha(75)
coinLocation = (random.randint(0, 1280), random.randint(0, 720))
coin = pygame.Rect(coinLocation[0], coinLocation[1], 50, 50)
elif scene == menu:
highscoretext = font4.render(f"Highscore: {highscore}", True, (0, 0, 0))
scoretext = font3.render("0", True, (0, 0, 0))
scoretext = scoretext.convert_alpha()
scoretext.set_alpha(75)
score = 0
screen.blit(titel, titlerect)
number += 0.1
clickTextAddY = math.cos(number)*30
screen.blit(clicktext, (525, 600-clickTextAddY))
particles.append(Particle(random.randint(250, 1075), random.randint(100, 200), random.choice(colors)))
for particle in particles:
particle.draw()
if len(particles) > 70:
particles.pop(random.randint(0, len(particles)-1))
screen.blit(highscoretext, highscorerect)
pygame.display.flip()
with open("other/highscore.txt", "w") as f:
f.write(str(highscore))
pygame.quit()
I hope anyone can help me with this.
As i already said, i have tried searcing it up. The shotgun pointed to my mouse, but it also moved.

How to make a circular countdown timer in Pygame?

How can i make this kind of countdown in Pygame? (i'm looking for how could i make the circle's perimeter decrease, that's the issue, because displaying the time isn't hard )
Keep in mind that how long the perimeter of the circle is and the displayed time should be in proportion with each other.
Just use pygame.draw.arc and specify the stop_angle argument depending on the counter:
percentage = counter/100
end_angle = 2 * math.pi * percentage
pygame.draw.arc(window, (255, 0, 0), arc_rect, 0, end_angle, 10)
Minimal example:
import pygame
import math
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
counter = 100
text = font.render(str(counter), True, (0, 128, 0))
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 1000)
def drawArc(surf, color, center, radius, width, end_angle):
arc_rect = pygame.Rect(0, 0, radius*2, radius*2)
arc_rect.center = center
pygame.draw.arc(surf, color, arc_rect, 0, end_angle, width)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
counter -= 1
text = font.render(str(counter), True, (0, 128, 0))
if counter == 0:
pygame.time.set_timer(timer_event, 0)
window.fill((255, 255, 255))
text_rect = text.get_rect(center = window.get_rect().center)
window.blit(text, text_rect)
drawArc(window, (255, 0, 0), (100, 100), 90, 10, 2*math.pi*counter/100)
pygame.display.flip()
pygame.quit()
exit()
Sadly the quality of pygame.draw.arc with a width > 1 is poor. However this can be improved, using cv2 and cv2.ellipse:
import pygame
import cv2
import numpy
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
counter = 100
text = font.render(str(counter), True, (0, 128, 0))
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 1000)
def drawArcCv2(surf, color, center, radius, width, end_angle):
circle_image = numpy.zeros((radius*2+4, radius*2+4, 4), dtype = numpy.uint8)
circle_image = cv2.ellipse(circle_image, (radius+2, radius+2),
(radius-width//2, radius-width//2), 0, 0, end_angle, (*color, 255), width, lineType=cv2.LINE_AA)
circle_surface = pygame.image.frombuffer(circle_image.flatten(), (radius*2+4, radius*2+4), 'RGBA')
surf.blit(circle_surface, circle_surface.get_rect(center = center))
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
counter -= 1
text = font.render(str(counter), True, (0, 128, 0))
if counter == 0:
pygame.time.set_timer(timer_event, 0)
window.fill((255, 255, 255))
text_rect = text.get_rect(center = window.get_rect().center)
window.blit(text, text_rect)
drawArcCv2(window, (255, 0, 0), (100, 100), 90, 10, 360*counter/100)
pygame.display.flip()
pygame.quit()
exit()

How to make your player get pass the first level in pygame

My game has been created but I would really like to add a second level to it how could I go about and creating another level for my racing game? I have created the first level to it but I would want to add another level as soon as my car reaches the end of the of the finish line. How can I do that? Thank you in advance!
import pygame, random
from time import sleep
pygame.init()
# music/sounds
CarSound = pygame.mixer.Sound("image/CAR+Peels+Out.wav")
CarSound_two = pygame.mixer.Sound("image/racing01.wav")
CarSound_three = pygame.mixer.Sound("image/RACECAR.wav")
CarSound_four = pygame.mixer.Sound("image/formula+1.wav")
Crowds = pygame.mixer.Sound("image/cheer_8k.wav")
Crowds_two = pygame.mixer.Sound("image/applause7.wav")
Crowds_three = pygame.mixer.Sound("image/crowdapplause1.wav")
final_tone = pygame.mixer.Sound("image/Victory.wav")
music = pygame.mixer.music.load("image/Led Zeppelin - Rock And Roll (Alternate Mix) (Official Music Video).mp3")
pygame.mixer.music.play(-1)
bg = pygame.image.load('image/Crowds.png')
main_img = pygame.image.load("image/img4.png")
main_img2 = pygame.image.load("image/img5.png")
side_img = pygame.image.load("image/bull2.png")
side_img2 = pygame.image.load("image/fox.png")
pauseimg = pygame.image.load("image/pause2.png")
clock = pygame.time.Clock()
pause = False
# Setting up our colors that we are going to use
GREEN = (20, 255, 140)
GREY = (210, 210, 210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
BLACKWHITE = (96, 96, 96)
BLACK = (105, 105, 105)
RGREEN = (0, 66, 37)
LIGHT_RED = (200, 0, 0)
BRIGHT_GREEN = (0, 255, 0)
DARK_BLUE = (0, 0, 139)
BLUE = (0, 0, 255)
NAVY = (0, 0 , 128)
DARK_OLIVE_GREEN = (85, 107, 47)
YELLOW_AND_GREEN = (154, 205, 50)
SCREENWIDTH = 400
SCREENHEIGHT = 500
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")
Icon = pygame.image.load("image/redca_iconr.png")
pygame.display.set_icon((Icon))
# This will be a list that will contain all the sprites we intend to use in our game.
# all_sprites_list = pygame.sprite.Group()
# player
playerIMG = pygame.image.load("image/red_racecar.png")
playerX = 280
playerY = 450
playerCar_position = 0
# player2
playerIMG_two = pygame.image.load("image/greencar.png")
playerX_two = 150
playerY_two = 450
playerCar_position_two = 0
# player3
playerIMG_three = pygame.image.load("image/Orangecar.png")
playerX_three = 60
playerY_three = 450
playerCar_position_three = 0
# player4
playerIMG_four = pygame.image.load("image/yellowcar2.png")
playerX_four = 210
playerY_four = 450
playerCar_position_four = 0
# Putting cars to the screen
def player(x, y):
screen.blit(playerIMG, (x, y))
def player_two(x, y):
screen.blit(playerIMG_two, (x, y))
def player_three(x, y):
screen.blit(playerIMG_three, (x, y))
def player_four(x, y):
screen.blit(playerIMG_four, (x, y))
finish_text = ""
font2 = pygame.font.SysFont("Papyrus", 65)
players_finished = []
next_level = 0
placings = ["1st", "2nd", "3rd", "4th"]
smallfont = pygame.font.SysFont("Papyrus", 15)
normalfont = pygame.font.SysFont("arial", 25)
differntfont = pygame.font.SysFont("futura", 25)
def level(next_level):
level = normalfont.render("Level: "+ str(next_level), True, BLACK)
screen.blit(level, [250, 10])
def score(score):
text = smallfont.render("Race cars passing: " + str(score), True, RGREEN)
screen.blit(text, [145, 490])
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
def message_display(text):
largText = pygame.font.Font("Mulish-Regular.ttf", 15)
TextSurf, TextRect = text_objects(text, largText)
TextRect.center = ((SCREENWIDTH / 1), (SCREENHEIGHT / 1))
screen.blit(TextSurf, TextRect)
text_two = normalfont.render("Start new game?", 5, (0, 66, 37))
time_to_blit = None
pygame.display.flip()
def button(msg, x, y, w, h, iC, aC, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen, iC, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "Play":
game_loop()
if action == "unpause":
unpause()
elif action == "Quit":
pygame.quit()
quit()
else:
pygame.draw.rect(screen, aC, (x, y, w, h))
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects(msg, newtext)
textReact.center = ((x + (100 / 2))), (y + (h / 2))
screen.blit(textSurf, textReact)
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects("QUIT!", newtext)
textReact.center = ((260 + (100 / 2))), (40 + (50 / 2))
screen.blit(textSurf, textReact)
def unpause():
global pause
pause = False
def paused():
newtext = pygame.font.SysFont("arial", 25)
textSurf, textReact = text_objects("paused", newtext)
textReact.center = ((100 + (100 / 2))), (100 + (100 / 2))
screen.blit(textSurf, textReact)
screen.fill(WHITE)
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(pauseimg, (0, 1))
button(" Continue!?", 40, 40, 125, 50, DARK_BLUE, BLUE, "unpause")
button("QUIT!", 260, 40, 100, 50, LIGHT_RED, RED, "Quit")
pygame.display.update()
clock.tick(15)
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(BLACK)
text = normalfont.render("Super Racer!", 8, (0, 66, 37))
new_text = normalfont.render("By Rafa94", 8, (0, 66, 37))
screen.blit(text, (35 - (text.get_width() / 5), 5))
screen.blit(new_text, (300 - (text.get_width() / 5), 5))
screen.blit(main_img, (5,340))
screen.blit(main_img2, (85, 115))
screen.blit(side_img, (330, 455))
screen.blit(side_img2, (5, 445))
button("GO!", 60, 40, 100, 50, DARK_BLUE, BLUE, "Play")
button("QUIT!", 260, 40, 100, 50, LIGHT_RED, RED, "Quit")
pygame.display.update()
clock.tick(15)
# Main game loop
def game_loop():
global pause
global playerCar_position, playerCar_position_two, playerCar_position_three, playerCar_position_four
global playerY, playerY_two, playerY_three, playerY_four, playerX, playerX_two, playerX_three, playerX_four
finish_line_rect = pygame.Rect(50, 70, 235, 32)
finish_text = ""
players_finished = 0
next_level = 0
time_to_blit = 0
run = True
while run:
# Drawing on Screen
screen.fill(BLACK)
# Draw The Road
pygame.draw.rect(screen, GREY, [40, 0, 300, 500])
# Draw Line painting on the road
pygame.draw.line(screen, WHITE, [185, 0], [185, 500], 5)
# Finish line
pygame.draw.rect(screen, BLACKWHITE, [50, 50, 280, 40])
pygame.draw.line(screen, WHITE, [50, 70], [330, 70], 5)
font = pygame.font.SysFont("Impact", 20)
text = font.render("Finish line!", 2, (150, 50, 25))
screen.blit(text, (185 - (text.get_width() / 2), 45))
screen.blit(bg, (-236, -34))
screen.blit(bg, (-236, -5))
screen.blit(bg, (-235, 140))
screen.blit(bg, (-235, 240))
screen.blit(bg, (-235, 340))
screen.blit(bg, (340, -60))
screen.blit(bg, (340, -60))
screen.blit(bg, (335, 5))
screen.blit(bg, (335, 130))
screen.blit(bg, (335, 230))
screen.blit(bg, (335, 330))
screen.blit(bg, (333, 330))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Number of frames per secong e.g. 60
clock.tick(60)
keys = pygame.key.get_pressed()
if keys[pygame.K_1]:
CarSound.play()
playerCar_position = -0.5
if keys[pygame.K_q]:
playerCar_position = 0.5
if keys[pygame.K_2]:
CarSound_two.play()
playerCar_position_two = -0.5
if keys[pygame.K_w]:
playerCar_position_two = 0.5
if keys[pygame.K_3]:
CarSound_three.play()
playerCar_position_three = -0.5
if keys[pygame.K_e]:
playerCar_position_three = 0.5
if keys[pygame.K_4]:
CarSound_four.play()
playerCar_position_four = -0.5
if keys[pygame.K_r]:
playerCar_position_four = 0.5
if keys[pygame.K_SPACE]:
pause = True
paused()
# our functions
playerY += playerCar_position
playerY_two += playerCar_position_two
playerY_three += playerCar_position_three
playerY_four += playerCar_position_four
player(playerX, playerY)
player_two(playerX_two, playerY_two)
player_three(playerX_three, playerY_three)
player_four(playerX_four, playerY_four)
# Did anyone cross the line?
if (finish_line_rect.collidepoint(playerX, playerY)):
if finish_text[:8] != "Player 1": # so it doesnt do this every frame the car is intersecting
finish_text = "Player 1 is " + placings[players_finished]
players_finished += 1
print("Player (one) has crossed into finish line!")
Crowds.play()
elif (finish_line_rect.collidepoint(playerX_two, playerY_two)):
if finish_text[:8] != "Player 2":
print("Player one has crossed into finish line first other car lost!")
finish_text = "Player 2 is " + placings[players_finished]
players_finished += 1
Crowds_three.play()
elif (finish_line_rect.collidepoint(playerX_three, playerY_three)):
if finish_text[:8] != "Player 3":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 3 is " + placings[players_finished]
players_finished += 1
elif (finish_line_rect.collidepoint(playerX_four, playerY_four)):
if finish_text[:8] != "Player 4":
print("Player two has crossed into finish line first other car lost!")
finish_text = "Player 4 is " + placings[players_finished]
players_finished += 1
Crowds_two.play()
if (players_finished and finish_text):
#print("ft:", finish_text)
font = pygame.font.SysFont("Impact", 17)
textrect = font.render(finish_text, False, (0, 66, 37))
#print('x', (SCREENWIDTH - text.get_width()) / 2)
screen.blit(textrect, (65 - (text.get_width() / 5), -2))
#screen.blit(textrect, ((SCREENWIDTH - textrect.get_width()) // 2, -5))
if (finish_line_rect.collidepoint and players_finished):
#pygame.mixer.final_tone.play(-1)
final_tone.play()
pygame.mixer.music.play(0)
if (finish_text):
font = pygame.font.SysFont("Impact", 20)
text = font.render('Game Over!!!', 5, (0, 66, 37))
screen.blit(text, (250 - (text.get_width() / 5), -2))
if players_finished == 4:
time_to_blit = pygame.time.get_ticks() + 5000
if time_to_blit:
screen.blit(text_two, (100, 345))
#final_tone.play()
if pygame.time.get_ticks() >= time_to_blit:
time_to_blit = 0
if players_finished == 4:
next_level = 1
score(players_finished)
level(next_level)
pygame.display.update()
clock.tick(60)
game_intro()
pygame.quit()
Make everything you currently have for the level 1 specifically (track, soundtrack, etc) as a class of Level1. And create similar for Level2. Then in your game loop initialize level (for now it can be a global variable to look from, but it is suggested to have a Game object that has attributes like this encapsulated inside it) as Level1 while starting a new game. And when player is finished with level1 (handle the check inside Level1 class that way you can have different parameters of finishing on different levels), change the level to Level2.
What different things you need to keep in mind? Render your level based on currently selected level. Look into this answer for some more insight.

how to generate random rectangles in a pygame and make them move like flappy bird?

I am a python beginner. I want to recreate chrome dino game. the random rectangle won't stop and the loop runs forever...please help me to stop the loop and make rectangles move.
Code:
import pygame
import random
pygame.init()
win = pygame.display.set_mode((500, 500))
#red rectangle(dino)
x = 20
y = 400
width = 30
height = 42
gravity = 5
vel = 18
black = (0, 0, 0)
#ground
start_pos = [0, 470]
end_pos = [500, 470]
#cactus
x1 = 20
y1 = 30
white = (2, 200, 200)
run = True
clock = pygame.time.Clock()
while run:
clock.tick(30)
pygame.time.delay(10)
win.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#random rectangle generation
for i in range(1):
width2 = random.randint(25, 25)
height2 = random.randint(60, 60)
top = random.randint(412, 412)
left = random.randint(300, 800)
rect = pygame.draw.rect(win, white, (left, top, width2,height2))
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
y = y - vel
else:
y = min(428, y + gravity)
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.draw.line(win, white, start_pos, end_pos, 2)
pygame.display.update()
pygame.display.flip()
pygame.quit()
pygame.draw.rect() des not "generate" a rectangle, it draws a rectangle on a surface.
pygame.Rect is a rectangle object. Create an instance of pygame.Rect before the main application loop:
obstracle = pygame.Rect(500, random.randint(0, 412), 25, 60)
Change the position of the rectangle:
obstracle.x -= 3
if obstracle.right <= 0:
obstracle.y = random.randint(0, 412)
And draw the rectangle to the window surface:
pygame.draw.rect(win, white, obstracle)
Example:
import pygame
import random
pygame.init()
win = pygame.display.set_mode((500, 500))
start_pos = [0, 470]
end_pos = [500, 470]
gravity = 5
vel = 18
black = (0, 0, 0)
white = (2, 200, 200)
hit = 0
dino = pygame.Rect(20, 400, 30, 40)
obstracles = []
number = 5
for i in range(number):
ox = 500 + i * 500 // number
oy = random.randint(0, 412)
obstracles.append(pygame.Rect(ox, oy, 25, 60))
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
dino.y -= vel
else:
dino.y = min(428, dino.y + gravity)
for obstracle in obstracles:
obstracle.x -= 3
if obstracle.right <= 0:
obstracle.x = 500
obstracle.y = random.randint(0, 412)
if dino.colliderect(obstracle):
hit += 1
win.fill(black)
color = (min(hit, 255), max(255-hit, 0), 0)
pygame.draw.rect(win, color, dino)
for obstracle in obstracles:
pygame.draw.rect(win, white, obstracle)
pygame.draw.line(win, white, start_pos, end_pos, 2)
pygame.display.update()
pygame.quit()

Dolphin Animation [PYGAME]

I am trying to animate two characters in my game. I want the animation to play without any key being held down. Every tutorial I have seen requires the player to press a key for an animation to play. How would you get the dolphin to be animated, but still work with the existing code I have? Currently I have the dolphin set to frame[0] so it is visible when you run it. Any help is appreciated!
Images and Sound FX download: https://mega.nz/#F!7O5zRQDK!YQhrs_zavCvdSdAMwEXEIQ
Game I am basing off of: https://www.youtube.com/watch?v=9jjy9PjbeiA&t=3s
import pygame
import random
import time
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" %(0, 20)
pygame.init()
SIZE = W, H = 400, 700
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
# colours
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BACKGROUND = (94, 194, 222)
STRIPE = (60, 160, 190)
LANELINE = (255, 255, 255)
x1 = 30
x2 = 330
lane1 = 30
lane2 = 130
lane3 = 230
lane4 = 330
y = 530
width = 40
height = 64
toggle1 = 0
toggle2 = 0
target_x1 = 30
target_x2 = 330
vel_x = 10
def drawScene():
screen.fill(BACKGROUND)
pygame.draw.polygon(screen, STRIPE, ((200, 700), (300, 700), (400, 600), (400, 500)))
pygame.draw.polygon(screen, STRIPE, ((0, 700), (100, 700), (400, 400), (400, 300)))
pygame.draw.polygon(screen, STRIPE, ((0, 500), (0, 600), (400, 200), (400, 100)))
pygame.draw.polygon(screen, STRIPE, ((0, 300), (0, 400), (400, 0), (300, 0)))
pygame.draw.polygon(screen, STRIPE, ((0, 100), (0, 200), (200, 0), (100, 0)))
pygame.draw.line(screen, LANELINE, (100, 0), (100, 700), 2)
pygame.draw.line(screen, LANELINE, (200, 0), (200, 700), 4)
pygame.draw.line(screen, LANELINE, (300, 0), (300, 700), 2)
dolphinSheet = pygame.image.load("dolphinSheet.png").convert()
cells = []
for n in range(6):
dolphinW, dolphinH, = (31, 74)
rect = pygame.Rect(n * dolphinW, 0, dolphinW, dolphinH)
image = pygame.Surface(rect.size).convert()
image.blit(dolphinSheet, (0, 0), rect)
alpha = image.get_at((0, 0))
image.set_colorkey(alpha)
cells.append(image)
playerImg = cells[0]
# main loop
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
pygame.mixer.music.load('percussiveHit.mp3')
pygame.mixer.music.play()
toggle1 += 1
if toggle1 % 2 == 1:
target_x1 += 100
else:
target_x1 -= 100
elif event.key == pygame.K_d:
pygame.mixer.music.load('percussiveHit.mp3')
pygame.mixer.music.play()
toggle2 += 1
if toggle2 % 2 == 1:
target_x2 -= 100
else:
target_x2 += 100
if x1 < target_x1:
x1 = min(x1 + vel_x, target_x1)
else:
x1 = max(x1 - vel_x, target_x1)
if x2 < target_x2:
x2 = min(x2 + vel_x, target_x2)
else:
x2 = max(x2 - vel_x, target_x2)
pygame.draw.rect(screen, RED, (x1, y, width, height))
pygame.draw.rect(screen, RED, (x2, y, width, height))
drawScene()
# players
screen.blit(playerImg, (x1 + 4, y - 5))
screen.blit(playerImg, (x2 + 4, y - 5))
pygame.display.update()
pygame.quit()
Update the image based on a real-time millisecond value using pygame.time.get_ticks() which returns the number of milliseconds since pygame.init().
The idea is the code remembers the time the frame was changed, and then waits until X seconds have elapsed (playerImg_show_for below), before switching to the next image in the set.
...
playerImg = cells[0]
playerImg_cell = -1 # start at first cell
playerImg_shown_at = 0 # time when this frame (cell) was shown
playerImg_show_for = 200 # milliseconds
# main loop
run = True
while run:
clock.tick(60)
ms_now = pygame.time.get_ticks() # milliseconds since start
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# ... handle keys, etc. removed for the sake of brevity
pygame.draw.rect(screen, RED, (x1, y, width, height))
pygame.draw.rect(screen, RED, (x2, y, width, height))
drawScene()
# players
# If this frame of animation has been shown for long enough, then
# switch to the next frame
if ( ms_now - playerImg_shown_at > playerImg_show_for ):
playerImg_cell += 1 # find the next cell, with wrap-around
if ( playerImg_cell >= len( cells ) ):
playerImg_cell = 0
playerImg_shown_at = ms_now # use new start time
playerImg = cells[playerImg_cell] # use new animation cell
screen.blit(playerImg, (x1 + 4, y - 5))
screen.blit(playerImg, (x2 + 4, y - 5))
pygame.display.update()
pygame.quit()
Of course this would be better suited to being a PyGame sprite object, and all handled in the sprite's update() function.

Categories

Resources