Related
I want the obstacle sprite, which are asteroids, to fall from the top of the screen to the bottom. I havent added any code to mess with the collisions of the asteroids, gravity, etc. because I can't even get the sprite to appear on the screen. Here is my code below (I tried using sprite classes but for me personally it made it a lot more confusing and difficult, so I chose not to.)
from sys import exit
from random import randint
def animation_state():
global player_surface, player_index, player_rect
player_index += 0.15
if player_index >= len(player_right_walk):
player_index = 0
if LEFT == True:
player_surface = player_left_walk[int(player_index)]
elif RIGHT == True:
player_surface = player_right_walk[int(player_index)]
if LEFT == False and RIGHT == False:
player_surface = pygame.image.load('graphics/dino_idle_right.png').convert_alpha()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player_surface = pygame.image.load('graphics/dino_idle_left.png').convert_alpha()
elif event.key == pygame.K_RIGHT:
player_surface = pygame.image.load('graphics/dino_idle_right.png').convert_alpha()
screen.blit(player_surface,player_rect)
def player_control():
global LEFT, RIGHT
player_velocity = 0
player_gravity = 0
player_gravity += 3
player_rect.y += player_gravity
if player_rect.bottom >= 500:
player_rect.bottom = 500
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_velocity -= 6
LEFT = True
RIGHT = False
if player_rect.x < -50:
player_rect.x = 800
elif keys[pygame.K_RIGHT]:
player_velocity += 6
LEFT = False
RIGHT = True
if player_rect.x > 800:
player_rect.x = -50
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT:
player_velocity = 0
player_rect.x += player_velocity
def display_score():
current_time = int(pygame.time.get_ticks() / 1000) - start_time
score_surface = font.render('Score: ' + str(current_time),False,(64,64,64))
score_rect = score_surface.get_rect(center = (375, 30))
screen.blit(score_surface, score_rect)
return current_time
def game_over_screen():
player_stand = pygame.image.load('graphics/dino_stand.png').convert_alpha()
player_stand = pygame.transform.rotozoom(player_stand,0,4).convert_alpha()
player_stand_rect = player_stand.get_rect(center = (375,280))
game_name = font.render('Personal Project Game', False, (111,196,169))
game_name_rect = game_name.get_rect(center = (375,100))
game_message = font.render('Press Space to start',False, 'Black')
game_message_rect = game_message.get_rect(center = (375, 500))
screen.blit(background_surface,(0,0))
screen.blit(player_stand,player_stand_rect)
screen.blit(game_name,game_name_rect)
screen.blit(game_message,game_message_rect)
def asteroid_animation_state():
global asteroid_surface, asteroid_index, asteroid_rect
asteroid_1 = pygame.image.load('graphics/asteroid_1.png').convert_alpha()
asteroid_1 = pygame.transform.rotozoom(asteroid_1,-45,0)
asteroid_2 = pygame.image.load('graphics/asteroid_2.png').convert_alpha()
asteroid_2 = pygame.transform.rotozoom(asteroid_2,-45,0)
asteroid_frames = [asteroid_1,asteroid_2]
asteroid_index = 0
asteroid_surface = asteroid_frames[asteroid_index]
asteroid_rect = asteroid_surface.get_rect(midtop = (randint(0,751),-20))
asteroid_index += 0.1
if asteroid_index >= len(asteroid_frames):
asteroid_index = 0
asteroid_surface = asteroid_frames[int(asteroid_index)]
asteroid_rect.bottom += 10
if asteroid_rect.bottom >=600:
asteroid_rect.bottom = -20
screen.blit(asteroid_surface,asteroid_rect)
pygame.init()
pygame.display.set_caption('Escape Extinction')
screen = pygame.display.set_mode((750,563))
clock = pygame.time.Clock()
LEFT = False
RIGHT = False
start_time = 0
score = 0
font = pygame.font.Font('fonts/atari-font-full-version/atari_full.ttf', 25)
player_right_1 = pygame.image.load('graphics/dino_1_right.png').convert_alpha()
player_right_2 = pygame.image.load('graphics/dino_2_right.png').convert_alpha()
player_right_3 = pygame.image.load('graphics/dino_3_right.png').convert_alpha()
player_right_4 = pygame.image.load('graphics/dino_4_right.png').convert_alpha()
player_left_1 = pygame.image.load('graphics/dino_1_left.png').convert_alpha()
player_left_2 = pygame.image.load('graphics/dino_2_left.png').convert_alpha()
player_left_3 = pygame.image.load('graphics/dino_3_left.png').convert_alpha()
player_left_4 = pygame.image.load('graphics/dino_4_left.png').convert_alpha()
player_right_walk = [player_right_1,player_right_2,player_right_3,player_right_4]
player_left_walk = [player_left_1,player_left_2,player_left_3,player_left_4]
player_index = 0
#player_surface_right = player_right_walk[player_index]
#player_surface_left = player_left_walk[player_index]
player_surface = player_right_walk[player_index]
player_rect = player_surface.get_rect(midbottom = (375,300))
background_surface = pygame.image.load('graphics/jumperbackground.png').convert()
ground_surface = pygame.image.load('graphics/grass.png').convert()
#obstacle_timer = pygame.USEREVENT + 1
#pygame.time.set_timer(obstacle_timer,1400)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#if event.type == obstacle_timer:
# obstacle.add(Asteroid('asteroid'))
screen.blit(background_surface,(0,0))
screen.blit(ground_surface,(0,480))
player_control()
animation_state()
display_score()
asteroid_animation_state()
pygame.display.update()
clock.tick(60)
Reading the documentation on the pygame.transform.rotozoom() function :
rotozoom(surface, angle, scale) -> Surface
This is a combined scale and rotation transform. The resulting Surface will be a filtered 32-bit Surface. The scale argument is a floating point value that will be multiplied by the current resolution. The angle argument is a floating point value that represents the counterclockwise degrees to rotate. A negative rotation angle will rotate clockwise.
So your image loading code is scaling the images by a factor of 0. So the resultant surface would have a zero size.
Probably you meant this to be 1.0, which would leave them the original size.
asteroid_1 = pygame.image.load('graphics/asteroid_1.png').convert_alpha()
asteroid_1 = pygame.transform.rotozoom( asteroid_1, -45, 1.0 )
asteroid_2 = pygame.image.load('graphics/asteroid_2.png').convert_alpha()
asteroid_2 = pygame.transform.rotozoom( asteroid_2, -45, 1.0 )
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()
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.
So I'm just learning how to work with classes and getting them to work between each different class. I'm trying to design a game where the user moves around and picks up food and each time the user picks up a piece of food the size of the character increases. I've done something similar before but now that there are classes involved I seem to have a hard time finding which class this should be part of. I added within the sprite update method that if it collides with a cherry then the size of the player should increase by 5 pixels each time. using the code :
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
Each time the game runs the player size doesn't change and for some reason the game no longer ends after the player has eaten a certain amount of cherries so I was just wondering if I was using a wrong method of changing the size of the player perhaps there may be an easier way to do so? Heres the rest of the code incase it helps at all.
import pygame, glob, random, time
from pygame.locals import *
from LabelClass import *
# CONSTANTS
WIDTH = 400 # Window width
HEIGHT = 400 # Window height
BLACK = (0,0,0) # Colors
WHITE = (255,255,255)
BACKGR = BLACK # Background Color
FOREGR = WHITE # Foreground Color
FPS = 40 # Frames per second
pwidth = 40
pheight = 40
class Food:
def __init__(self,screen,centerx,centery):
self.screen = screen
self.surface = pygame.image.load('cherry.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
class Player:
def __init__(self, screen, centerx,
centery, speed, backcolor):
self.surface = pygame.image.load('player.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
self.speed = speed
self.screen = screen
self.backcolor = backcolor
self.dir = ''
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
def move(self):
if self.dir != '':
if self.dir == 'd' and self.rect.bottom < HEIGHT:
self.rect.top += self.speed
if self.dir == 'u' and self.rect.top > 0:
self.rect.top -= self.speed
if self.dir == 'l' and self.rect.left > 0:
self.rect.left -= self.speed
if self.dir == 'r' and self.rect.right < WIDTH:
self.rect.right += self.speed
def jump(self,top,left):
self.rect.top = top
self.rect.left = left
class SpritesGame:
def __init__(self,screen):
self.screen = screen
screen.fill(BLACK)
pygame.display.update()
music_file = getRandomMusic()
pygame.mixer.music.load(music_file)
pygame.mixer.music.play(-1,0.0)
self.music = True
self.Foods = [ ]
self.Eaten = 0
for i in range(20):
self.Foods.append(
Food(self.screen,
WIDTH*random.randint(1,9)//10,
HEIGHT*random.randint(1,9)//10))
for f in self.Foods:
f.draw()
self.Player = Player(screen,WIDTH//2,HEIGHT//2,6,BLACK)
self.PickUpSound = pygame.mixer.Sound('pickup.wav')
self.PlaySound = True
self.startTime = time.clock()
self.endTime = -1
self.Won = False
def update(self):
self.screen.fill(BLACK)
pickedUp = False
for f in self.Foods[:]:
if self.Player.rect.colliderect(f.rect):
self.Foods.remove(f)
self.Foods.append(Food(self.screen,WIDTH*random.randint(1,9)//10,HEIGHT*random.randint(1,9)//10))
pickedUp = True
self.Eaten += 1
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
#self.rect.center = center
print self.Eaten
if pickedUp and self.PlaySound:
self.PickUpSound.play()
for f in self.Foods:
f.draw()
if self.Eaten == 40:
self.Won = True
self.endTime = time.clock()
self.Player.move()
self.Player.draw()
pygame.display.update()
def toggleMusic(self):
self.music = not self.music
if self.music:
pygame.mixer.music.play(-1,0.0)
else:
pygame.mixer.music.stop()
def run(self):
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYDOWN: # Keeps moving as long as key down
if event.key == K_LEFT or event.key == ord('a'):
self.Player.dir = 'l'
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = 'r'
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = 'u'
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = 'd'
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
if event.key == K_ESCAPE:
stop = True
if event.key == K_LEFT or event.key == ord('a'): # End repetition.
self.Player.dir = ''
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = ''
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = ''
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = ''
if event.key == ord('x'):
top = random.randint(0,
HEIGHT - self.Player.rect.height)
left = random.randint(0,
WIDTH - self.Player.rect.width)
self.Player.jump(top,left)
if event.key == ord('m'):
self.toggleMusic()
if event.key == ord('p'):
self.PlaySound = not self.PlaySound
mainClock.tick(FPS)
self.update()
if self.Won:
stop = True # END OF WHILE
if self.Won:
self.screen.fill(BLACK)
pygame.display.update()
msg = (str((int(self.endTime)
-int(self.startTime)))
+" seconds to finish. Hit Q.")
L2 = Label(display,WIDTH//2,HEIGHT*7//8,26,msg,WHITE,BLACK)
L2.draw()
stop = False
while not stop:
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
pygame.event.get()
pygame.mixer.music.stop()
def getRandomMusic():
mfiles = glob.glob("*.wav")
mfiles.append(glob.glob("*.mid"))
r = random.randint(0,len(mfiles)-1)
return mfiles[r]
def OpeningScreen(screen):
screen.fill(BLACK)
pygame.display.update()
L1 = Label(display,WIDTH//2,HEIGHT*7//8,26,"Hit Q to Quit, P to Play.",WHITE, BLACK)
L1.draw()
# Properly initiate pygame
pygame.init()
# pygame.key.set_repeat(INT,INT)
# Set the clock up
mainClock = pygame.time.Clock()
# Initialize Display
display = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Sprites and Sounds V06')
OpeningScreen(display)
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYUP:
if event.key == ord('p'):
game = SpritesGame(display)
game.run()
OpeningScreen(display)
if event.key == ord('q'):
stop = True
pygame.quit()
Surface.get_rect() will always return a rect starting at (0,0), and you also are modifying SpritesGame.rect. I think you should change
self.rect = self.Player.surface.get_rect()
to
self.Player.rect.inflate_ip(5, 5)