Related
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()
Here is my code below. Every time when I try to increase the length, It does not seem to increase and when I run the game.
When I run the game, It sometimes makes the head of the snake flicker/blink certain times and when snake eats the food, still it does not increase the length instead of blinking little at certain times
I have attached code with my applied logic. Please is there any solution to this problem?
Here is my code with what I applied as the increase length logic:
Here is my logic:
import pygame
import time
import sys
import random
a = print("1) Easy")
b = print("2) Medium")
c = print("3) Hard")
while True:
difficulty = input("Enter Difficulty Level: ")
if difficulty == "1":
speed = 5
break
elif difficulty == "2":
speed = 6
break
elif difficulty == "3":
speed = 8
else:
print("Choose from Above Options Only!")
# Initialise Game
pygame.init()
clock = pygame.time.Clock()
# Screen and Window Size:
screen_width = 800
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
caption = pygame.display.set_caption("Snake Game")
icon = pygame.image.load("snake.png")
pygame.display.set_icon(icon)
# Colors
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
white = (255, 255, 255)
# Snake Editing
x1 = 350
y1 = 300
snake = pygame.Rect([x1, y1, 20, 20])
x1_change = 0
y1_change = 0
snake_size = 15
snk_list = []
snk_length = 1
# Snake Food
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
food_height = 15
food_width = 15
# Game State
game_over = True
# Game over
font = pygame.font.SysFont("freelansbold.tff", 64)
# Score Counter
score = 0
score_font = pygame.font.SysFont("chiller", 50)
# TO INCREASE SNAKE LENGTH LOGIC:
def plot_snake(gameWindow, color, snk_list, snake_size):
for x, y in snk_list:
pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size])
def game_over_text(text, color):
x = font.render(text, True, (240, 0, 0))
screen.blit(x, [screen_width//2 - 135, screen_height//2 - 25])
def score_show():
text = score_font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(text, (20, 10))
def main_loop():
global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size, snk_length
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# User Input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
x1_change = speed * -1
y1_change = 0
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
x1_change = speed
y1_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_w:
y1_change = speed * -1
x1_change = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
y1_change = speed
x1_change = 0
# Game Over Checking
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_over = False
x1 += x1_change
y1 += y1_change
if abs(x1 - food_x) < 7 and abs(y1 - food_y) < 7:
score += 1
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
speed += 0.2
snk_length += 5
# Drawing On Screen
screen.fill((0, 0, 0))
pygame.draw.rect(screen, red, [x1, y1, 15, 15])
pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
score_show()
pygame.display.flip()
#SNAKE LENGTH LOGIC
head = []
head.append(x1)
head.append(y1)
snk_list.append(head)
if len(snk_list) > snk_length:
del snk_list[0]
plot_snake(screen, red, snk_list, snake_size)
# Final Initialisation
pygame.display.flip()
clock.tick(70)
# Main Game Loop
while game_over:
main_loop()
# Game_Over
screen.fill((0, 0, 0))
game_over_text("Game Over!!!", (255, 0, 0))
pygame.display.flip()
time.sleep(2)
pygame.quit()
quit()
The moving distance of the snake must be "snake_size":
def main_loop():
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# User Input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_w:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
y1_change = snake_size
x1_change = 0
But use pygame.time.Clock to control the frames per second and thus the game speed.
def main_loop():
# [...]
clock.tick(speed)
Use pygame.Rect and collidrect to find the collision of the snake and the food. See also How to detect collisions between two rectangular objects or images in pygame. Increment snk_length, when a collision is detected:
def main_loop():
# [...]
global snk_length
# [...]
snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
if snake_rect.colliderect(food_rect):
snk_length += 1
score += 1
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
speed += 1
Follow the instructions of How do I chain the movement of a snake's body?. Put the new head position of the snake at the head of snk_list, but delete the elements at the tail:
def main_loop():
# [...]
#SNAKE LENGTH LOGIC
snk_list.insert(0, [x1, y1])
if len(snk_list) > snk_length:
del snk_list[-1]
Complete main_loop:
def main_loop():
global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size
global snk_length
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# User Input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_w:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
y1_change = snake_size
x1_change = 0
# Game Over Checking
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_over = False
x1 += x1_change
y1 += y1_change
snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
if snake_rect.colliderect(food_rect):
snk_length += 1
score += 1
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
speed += 1
# Drawing On Screen
screen.fill((0, 0, 0))
pygame.draw.rect(screen, red, [x1, y1, 15, 15])
pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
score_show()
pygame.display.flip()
#SNAKE LENGTH LOGIC
snk_list.insert(0, [x1, y1])
if len(snk_list) > snk_length:
del snk_list[-1]
plot_snake(screen, red, snk_list, snake_size)
# Final Initialisation
pygame.display.flip()
clock.tick(speed)
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 the game very close to fully working, however, when I run the program, the program complains with this error
\Dodger.py", line 180, in bullets.remove(b) ValueError: list.remove(x): x not in list
Here's the code:
import pygame, random, sys
from pygame.locals import *
TEXTCOLOR = (0, 0, 0)
FPS = 60
BADDIEMINSIZE = 8
BADDIEMAXSIZE = 70
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 12
ADDNEWBADDIERATE = 1
PLAYERMOVERATE = 3
WINDOWWIDTH = 1280
WINDOWHEIGHT = 780
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
background = pygame.image.load("background.png")
backgroundRect = background.get_rect
background_position = [0, 0]
bulletpicture = pygame.image.load("bullet.png")
bullets = []
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Dodger')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
click_sound = pygame.mixer.Sound("pistol.wav")
# set up images
playerImage = pygame.image.load('ship.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('baddie.png')
background_image = pygame.image.load("background.png") .convert()
# Copy image to screen
screen.blit(background_image, background_position)
# Set positions of graphics
background_position = [0, 0]
# show the "Start" screen
drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.key == ord('p'):
click_sound.play()
bullets.append([event.key-32, 500])
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
for b in range(len(bullets)):
bullets.remove(b)
# Move the baddies down.
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
for bullet in bullets:
if bullet[0]<0:
bullets.remove(bullet)
screen.blit(background_image, background_position)
for bullet in bullets:
screen.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0,))
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Draw each baddie
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
gameOverSound.play()
drawText('You lose', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
Just change:
for b in range(len(bullets)):
bullets.remove(b)
To:
bullets = []
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.