i tried but i cant find the error pls help how do i execute it?
im new so, it would be a great help if u tell me a clean way of adding attack animation also
import pygame
import os
pygame.init
t = pygame.display.set_mode((1280,720))
pygame.display.set_caption("my first game moce")
clock = pygame.time.Clock()
FPS = 60
RED = (255,0,0)
#game variables
GRAVITY = 0.75
moving_left = False
moving_right = False
#load images
R =[pygame.image.load('img/hero/attack/0.png'),pygame.image.load('img/hero/attack/1.png'),pygame.image.load('img/hero/attack/2.png'),pygame.image.load('img/hero/attack/3.png'),pygame.image.load('img/hero/attack/4.png'),pygame.image.load('img/hero/attack/5.png'),pygame.image.load('img/hero/attack/6.png'),pygame.image.load('img/hero/attack/7.png'),pygame.image.load('img/hero/attack/8.png'),pygame.image.load('img/hero/attack/9.png')]
L =[pygame.image.load('img/hero/attack L/0.png'),pygame.image.load('img/hero/attack L/1.png'),pygame.image.load('img/hero/attack L/2.png'),pygame.image.load('img/hero/attack L/3.png'),pygame.image.load('img/hero/attack L/4.png'),pygame.image.load('img/hero/attack L/5.png'),pygame.image.load('img/hero/attack L/6.png'),pygame.image.load('img/hero/attack L/7.png'),pygame.image.load('img/hero/attack L/8.png'),pygame.image.load('img/hero/attack L/9.png')]
class soldier(pygame.sprite.Sprite):
def __init__(self, char_type,x,y,scale,speed):
pygame.sprite.Sprite.__init__(self)
self.alive = True
self.char_type = char_type
self.speed = speed
self.direction = 1
self.vel_y = 0
self.jump = False
self.in_air = True
self.flip = False
self.attacking = False
self.attack_frame = 0
self.animation_list = []
self.frame_index = 0
self.action = 0
self.update_time = pygame.time.get_ticks()
animation_types = ['idle','jump','run']
for animation in animation_types:
temp_list = []
num_of_frames = len(os.listdir(f'img/{self.char_type}/{animation}'))
for i in range(num_of_frames):
img = (pygame.image.load(f'img/{self.char_type}/{animation}/{i}.png'))
img = pygame.transform.scale(img,(int(img.get_width()*scale),int(img.get_height()*scale)))
temp_list.append(img)
self.animation_list.append(temp_list)
self.img = self.animation_list[self.action][self.frame_index]
self.rect = self.img.get_rect()
self.rect.center = (x,y)
def move(self, moving_left, moving_right):
dx = 0
dy = 0
if moving_left:
dx = -self.speed
self.flip = True
self.direction = -1
if moving_right:
dx = self.speed
self.flip = False
self.direction = 1
if self.jump == True and self.in_air == False:
self.vel_y = -11
self.jump = False
self.in_air = True
#appy gravity
self.vel_y += GRAVITY
if self.vel_y > 10:
self.vel_y
dy += self.vel_y
#check collison with floor
if self.rect.bottom +dy > 300:
dy = 300 - self.rect.bottom
self.in_air = False
self.rect.x += dx
self.rect.y += dy
def update_animation(self):
ANIMATION_COOLDOWN = 100
if pygame.time.get_ticks() - self.update_time > ANIMATION_COOLDOWN:
self.img = self.animation_list[self.action][self.frame_index]
self.update_time = pygame.time.get_ticks()
self.frame_index += 1
#if out of animation
if self.frame_index >= len(self.animation_list[self.action]):
self.frame_index = 0
def update_action(self, new_action):
if new_action != self.action:
self.action = new_action
self.frame_index = 0
self.update_time = pygame.time.get_ticks()
def attack(self):
if self.attack_frame > 10:
self.attack_frame = 0
self.attacking = False
if self.direction == 'RIGHT':
self.image = R[self.attack_frame]
elif self.direction == 'LEFT':
self.correction()
self.image = L[self.attack_frame]
self.attack_frame += 1
def correction(self):
# Function is used to correct an error
# with character position on left attack frames
if self.attack_frame == 1:
self.pos.x -= 20
if self.attack_frame == 10:
self.pos.x += 20
def draw(self):
t.blit(pygame.transform.flip(self.img,self.flip,False),self.rect)
player = soldier("hero",200,200,2,5)
width = 30
height = 60
x = 300
y = 0
jump = False
jump_count = 10
run = True
background_image = pygame.image.load("C:/Users/Owner/Desktop/q1.png").convert()
while run:
t.blit(background_image,(0,0))
clock.tick(FPS)
player.update_animation()
player.draw()
player.move(moving_left, moving_right)
if player.alive:
if player.attacking == True:
player.attack()
if player.in_air:
player.update_action(1)
elif moving_left or moving_right:
player.update_action(2)
else:
player.update_action(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
moving_left = True
if event.key == pygame.K_d:
moving_right = True
moving_left = False
if event.key == pygame.K_SPACE and player.alive:
player.jump = True
if event.key == pygame.K_ESCAPE:
run = False
if event.key == pygame.K_LSHIFT:
player.speed = 7
if event.key == pygame.K_e:
if player.attacking == False:
player.attack()
player.attacking = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
moving_left = False
if event.key == pygame.K_d:
moving_right = False
if event.key == pygame.K_SPACE:
player.jump = False
if event.key == pygame.K_LSHIFT:
player.speed = 5
if event.key == pygame.K_e:
if player.attacking == True:
player.attacking = False
pygame.display.update()
pygame.quit()
You have different options depending on the effect you want to achieve.
In your current implementation, an attack is stopped when the e button is released. I recommend to remove that code:
while run:
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYUP:
# [...]
# DELETE
# if event.key == pygame.K_e:
# if player.attacking == True:
# player.attacking = False
# self.attack_frame = 0
If you want to stop the attack when the e button is released, you must also reset self.attack_frame
while run:
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYUP:
# [...]
if event.key == pygame.K_e:
if player.attacking == True:
player.attacking = False
self.attack_frame = 0
If you want to allow continuous attacks and interrupt an attack, you need to change the implementation in the KEYDOWN event and reset self.attack_frame when e is pressed:
while run:
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYDOWN:
# [...]
if event.key == pygame.K_e:
player.attacking = True
self.attack_frame = 0
if event.type == pygame.KEYUP:
# [...]
# DELETE
# if event.key == pygame.K_e:
# if player.attacking == True:
# player.attacking = False
# self.attack_frame = 0
Related
I am trying to get my player to jump when I press the up key. I have created a jump method in the Player class that gets called in the game loop. When user presses the UP key, value of player.isJump should go from its default value of False, to True. and the code inside player.jump() should run until the jump is completed and player.isJump is set back to False. But when I press the up key, nothing happens.
import pygame
pygame.init()
screen = pygame.display.set_mode([800, 600])
pygame.display.set_caption('Stick Quest')
class Player():
def __init__(self):
self.playerImg = pygame.image.load('player.png')
self.playerX = 400
self.playerY = 300
self.playerX_change = 0
self.isJump = False
self.jumpCount = 10
def displayPlayer(self):
screen.blit(self.playerImg, (self.playerX,self.playerY))
def updateLocation(self):
self.playerX += self.playerX_change
def jump(self):
if self.isJump:
if self.jumpCount >= -10:
neg = 1
if player.jumpCount < 0:
neg = -1
self.playerY -= (self.jumpCount ** 2) * 0.5 * neg
self.jumpCount = -1
else:
self.isJump = False
self.jumpCount = 10
player = Player()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.playerX_change = -1.0
if event.key == pygame.K_RIGHT:
player.playerX_change = 1.0
if event.key == pygame.K_UP:
player.isJump == True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player.playerX_change = 0
player.updateLocation()
player.jump()
player.displayPlayer()
pygame.display.update()
screen.fill((255,255,255))
pygame.quit()
Your problem is in this line:
player.isJump == True
instead of assign the player.isJump to True, you just checked if it is true or not. nothing changed.
To fix it use the assignment sign:
player.isJump = True
I'm quite new to python and have recently started game dev with pygame. I wanted to know why my game just freezes and the exitcode -805306369 (0xCFFFFFFF) appears. Do i have errors in my programm? It looks like this:
import pygame
import random
import math
pygame.init()
window = pygame.display.set_mode((1000, 600))
caption = pygame.display.set_caption(
'Test your reaction speed. Shoot the target game!') # sets a caption for the window
run = True
PlayerImg = pygame.image.load('F:\PythonPortable\oscn.png')
PlayerX = 370
PlayerY = 420
PlayerX_change = 0
PlayerY_change = 0
def player():
window.blit(PlayerImg, (PlayerX, PlayerY))
aim_sight = pygame.image.load('F:\PythonPortable\ktarget.png')
aim_sightX = 460
aim_sightY = 300
aim_sight_changeX = 0
aim_sight_changeY = 0
def aim_sight_function(x, y):
window.blit(aim_sight, (x, y))
targetedImg = pygame.image.load('F:\PythonPortable\ktargetedperson.png')
targetedX = random.randint(0, 872)
targetedY = random.randint(0, 200)
def random_target():
window.blit(targetedImg, (targetedX, targetedY))
def iscollision(targetedX, targetedY, aim_sightX, aim_sightY):
distance = math.sqrt((math.pow(targetedX - aim_sightX, 2)) + (math.pow(targetedY - aim_sightY, 2)))
if distance < 70:
return True
else:
return False
while run:
window.fill((255, 255, 255))
random_target()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
aim_sight_changeX = -2
PlayerX_change = -2
elif event.key == pygame.K_RIGHT:
aim_sight_changeX = 2
PlayerX_change = 2
elif event.key == pygame.K_UP:
aim_sight_changeY = -2
PlayerY_change = -2
elif event.key == pygame.K_DOWN:
aim_sight_changeY = 2
PlayerY_change = 2
score = 0
while score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision and event.key == pygame.K_SPACE:
print("HIT") # Just for me to acknowledge that collision is true and space bar was pressed in the right spot
score = score + 1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
aim_sight_changeX = 0
PlayerX_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
aim_sight_changeY = 0
PlayerY_change = 0
aim_sightX += aim_sight_changeX
if aim_sightX <= 46.5:
aim_sight_changeX = 0
elif aim_sightX >= 936:
aim_sight_changeX = 0
aim_sightY += aim_sight_changeY
if aim_sightY <= 0:
aim_sight_changeY = 0
elif aim_sightY >= 400:
aim_sight_changeY = 0
PlayerX += PlayerX_change
if PlayerX <= -50:
PlayerX_change = 0
elif PlayerX >= 850:
PlayerX_change = 0
player()
aim_sight_function(aim_sightX, aim_sightY)
pygame.display.update()
I think there is a mistake in this area as my program runs well without it.
while score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision and event.key == pygame.K_SPACE:
print("HIT") # Just for me to acknowledge that collision is true and space bar was pressed in the right spot
score = score + 1
I've checked other questions but they are mostly for java and other languages.
You have an application loop. You do not need an additional loop to control the game. The loop that increments the score is an infinite loop. Change the loop to a selection (change while to if).
Furthermore, the score has to be initialized before the application loop:
score = 0
while run:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
aim_sight_changeX = -2
PlayerX_change = -2
elif event.key == pygame.K_RIGHT:
# [...]
elif event.key == pygame.K_SPACE:
if score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision:
print("HIT")
score = score + 1
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()
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)
I'm having trouble flipping a sprite in pygame (I can get it to go right but I want the img to flip on the left key),
I researched how to flip an image and found the pygame.transform.flip, but as a beginner to pygame, I'm not sure how to use it, and the tutorials aren't making sense to me.
Can anyone help me with the code below (I'm not sure if I even put the self.img1 for the flip in the right place)?
import pygame, sys, glob
from pygame import *
class Player:
def __init__(self):
self.x = 200
self.y = 300
self.ani_speed_init = 6
self.ani_speed = self.ani_speed_init
self.ani = glob.glob("walk\Pinks_w*.png")
self.ani.sort()
self.ani_pos = 0
self.ani_max = len(self.ani)-1
self.img = pygame.image.load(self.ani[0])
self.img1 = pygame.transform.flip(self.ani[0], True, False)
self.update(0)
def update(self, pos):
if pos != 0:
self.ani_speed-=1
self.x+=pos
if self.ani_speed == 0:
self.img = pygame.image.load(self.ani[self.ani_pos])
self.ani_speed = self.ani_speed_init
if self.ani_pos == self.ani_max:
self.ani_pos = 0
else:
self.ani_pos+=1
screen.blit(self.img,(self.x,self.y))
h = 400
w = 800
screen = pygame.display.set_mode((w,h))
clock = pygame.time.Clock()
player1 = Player()
pos = 0
while True:
screen.fill((0,0,0))
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN and event.key == K_RIGHT:
pos = 1
elif event.type == KEYUP and event.key == K_RIGHT:
pos = 0
elif event.type == KEYDOWN and event.key == K_LEFT:
pos = -1
elif event.type == KEYUP and event.key == K_LEFT:
pos = 0
player1.update(pos)
pygame.display.update()
To flip, you would do:
# input
if event.type == KEYDOWN:
if event.key == K_RIGHT:
flip_x = True
elif event.key == K_LEFT:
flip_x = False
elif event.key == K_UP:
flip_y = True
elif event.key == K_DOWN:
flip_y = False
# then to flip
new_image = pygame.transform.flip(original_image, flip_x, flip_y)
Your Player class is not very well readable. As, your names are not easy to understand.
In my version of your code, all I have changed is the names and I have added a check for the value of pos and applied the flip if needed. So, you may need to change the check (if condition), to get the desired results.
And Yes, you don't have a pygame.Sprite, so, the word sprite is misleading, in this case.
My version of your Player class:
class Player:
def __init__(self):
self.x = 200
self.y = 300
self.speed_init = 6
self.images = [pygame.image.load(img) for img in glob.glob("walk\Pinks_w*.png")]
self.index = 0
self.max_index = len(self.images)-1
self.speed = 0
self.img = self.images[self.index]
def update(self, pos):
if pos != 0:
self.speed -= 1
self.x += pos
if not self.speed:
self.speed = self.speed_init
if self.index < self.max_index:
self.index += 1
else:
self.index = 0
self.img = self.images[self.index]
# change True to False if needed, or change the operator.
if pos > 0:
self.img = pygame.transform.flip(self.img,True,False)
screen.blit(self.img,(self.x,self.y))
Update
There was a small problem with the update function. The problem was that since speed was always constant and not 0, the if not self.speed: did not work. So, change the update function to this:
def update(self, pos):
if pos != 0:
self.speed -= 1
self.x += pos
# no more self.speed checks
if self.index < self.max_index:
self.index += 1
else:
self.index = 0
self.img = self.images[self.index]
# change True to False if needed, or change the operator.
if pos < 0:
self.img = pygame.transform.flip(self.img,True,False)
screen.blit(self.img,(self.x,self.y))
Update 2
It seems that there is some kind of typo in your code,
Here's (my version of) the Code, The whole thing.
import pygame, sys, glob
from pygame import *
class Player:
def __init__(self):
self.x = 200
self.y = 300
self.speed_init = 6
self.images = [pygame.image.load(img) for img in glob.glob("walk\Pinks_w*.png")]
self.index = 0
self.max_index = len(self.images)-1
self.speed = 0
self.img = self.images[self.index]
print self.max_index
def update(self, pos):
if pos != 0:
self.speed -= 1
self.x += pos
print self.index, self.max_index
if self.index < self.max_index:
self.index += 1
else:
self.index = 0
self.img = self.images[self.index]
# change True to False if needed, or change the operator.
if pos < 0:
self.img = pygame.transform.flip(self.img,True,False)
screen.blit(self.img,(self.x,self.y))
h = 400
w = 800
screen = pygame.display.set_mode((w,h))
clock = pygame.time.Clock()
player1 = Player()
pos = 0
while True:
screen.fill((0,0,0))
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN and event.key == K_RIGHT:
pos = 2
elif event.type == KEYUP and event.key == K_RIGHT:
pos = 0
elif event.type == KEYDOWN and event.key == K_LEFT:
pos = -2
elif event.type == KEYUP and event.key == K_LEFT:
pos = 0
player1.update(pos)
pygame.display.update()