adding boulders to pygame snake in python - python

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.

Related

Python Snake doesn't grow [duplicate]

This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 1 year ago.
I'm new to python and only now the basics, I'm trying to make a snake game but I can't seem to figure out how to make my snake grow 1 extra square each time it eats an apple. My reasoning is that I keep a list of all the old positions but only show the last one on the screen, and each time the snakes eats another apple it shows 1 extra old positions making the snake 1 square longer.
This is my code:
import pygame
from random import randint
WIDTH = 400
HEIGHT = 300
dis = pygame.display.set_mode((WIDTH,HEIGHT))
white = (255,255,255)
BACKGROUND = white
blue = [0,0,255]
red = [255,0,0]
class Snake:
def __init__(self):
self.image = pygame.image.load("snake.bmp")
self.rect = self.image.get_rect()
self.position = (10,10)
self.direction = [0,0]
self.positionslist = [self.position]
self.length = 1
pygame.display.set_caption('Snake ')
def draw_snake(self,screen):
screen.blit(self.image, self.position)
def update(self):
self.position = (self.position[0] + self.direction[0],self.position[1] + self.direction[1])
self.rect = (self.position[0],self.position[1],5, 5 )
self.positionslist.append(self.position)
if self.position[0]< 0 :
self.position = (WIDTH,self.position[1])
elif self.position[0] > WIDTH:
self.position = (0,self.position[1])
elif self.position[1] > HEIGHT:
self.position = (self.position[0],0)
elif self.position[1] < 0 :
self.position = (self.position[0],HEIGHT)
class Food:
def __init__(self):
self.image = pygame.image.load("appel.png")
self.rect = self.image.get_rect()
apple_width = -self.image.get_width()
apple_height = -self.image.get_height()
self.position = (randint(0,WIDTH+apple_width-50),randint(0,HEIGHT+apple_height-50))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
def draw_appel(self,screen):
screen.blit(self.image, self.position)
def eat_appel (self, snake):
if self.rect.colliderect(snake.rect) == True:
self.position = (randint(0,WIDTH),randint(0,HEIGHT))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
snake.length += 1
def main():
game_over = False
while not game_over:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
snake = Snake()
food = Food()
while True:
screen.fill(BACKGROUND)
font = pygame.font.Font('freesansbold.ttf', 12)
text = font.render(str(snake.length), True, red, white)
textRect = text.get_rect()
textRect.center = (387, 292)
screen.blit(text,textRect)
snake.update()
#snake.update_list()
snake.draw_snake(screen)
food.draw_appel(screen)
food.eat_appel(snake)
pygame.display.flip()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
snake.direction = [0,1]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.direction = [1,0]
if event.key == pygame.K_LEFT:
snake.direction = [-1,0]
if event.key == pygame.K_UP:
snake.direction = [0,-1]
if event.key == pygame.K_DOWN:
snake.direction = [0,1]
if __name__ == "__main__":
main()
This can have multiple reasons. Firstly, I saw you tried to increase the length of the snake by typing snake.length += 1, which may work (probably won't because the module pygame allows the snake to hover around, but not like the loop or conditional statements). One of my tips would be, to increase the length of the snake by using the idea of adding the score with your present snake.length every time (because once your score is 1 by eating an apple, your snake.length would be 2. And it increases with the score). This is my code (a few modifications might be needed):
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 165, 0)
width, height = 600, 400
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Mania")
clock = pygame.time.Clock()
snake_size = 10
snake_speed = 15
message_font = pygame.font.SysFont('ubuntu', 30)
score_font = pygame.font.SysFont('ubuntu', 25)
def print_score(score):
text = score_font.render("Score: " + str(score), True, orange)
game_display.blit(text, [0,0])
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])
def run_game():
game_over = False
game_close = False
x = width / 2
y = height / 2
x_speed = 0
y_speed = 0
snake_pixels = []
snake_length = 1
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
while not game_over:
while game_close:
game_display.fill(black)
game_over_message = message_font.render("Game Over!", True, red)
game_display.blit(game_over_message, [width / 3, height / 3])
print_score(snake_length - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
game_over = True
game_close = False
if event.key == pygame.K_2:
run_game()
if event.type == pygame.QUIT:
game_over = True
game_close = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_speed = -snake_size
y_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
if event.key == pygame.K_UP:
x_speed = 0
y_speed = -snake_size
if event.key == pygame.K_DOWN:
x_speed = 0
y_speed = snake_size
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
y += y_speed
game_display.fill(black)
pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])
snake_pixels.append([x, y])
if len(snake_pixels) > snake_length:
del snake_pixels[0]
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
draw_snake(snake_size, snake_pixels)
print_score(snake_length - 1)
pygame.display.update()
if x == target_x and y == target_y:
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
run_game()

Can anyone tell me how to increase the snake size in my code?

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)

Pygame malfunctioning

This is a game for teens.
The main guy is displayed well, the time, sound and the background are showing too.
But the bad guys and the key to press to move the bad guy are not working.
# 1 - Importing library
import pygame
from pygame.locals import *
import math
import random
# 2 - Initializing the game
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = {True, False, False, False}
playerpos =[100,100]
acc = [0,0]
arrows = []
badtimer = 100
badtimer1 = 0
badguys = [[300,100]]
healthvalue = 194
pygame.mixer.init()
# 3 - Loading images
player = pygame.image.load("resources/images/dude.png")
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")
arrow = pygame.image.load("resources/images/bullet.png")
badguyimg1 = pygame.image.load("resources/images/badguy.png")
badguyimg = badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 3.1 - Load audio
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('resources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
# 4 - keep looping through
running = 1
exitcode = 0
# 5 - clearing the screen before drawing it again
screen.fill(0)
while running:
badtimer -= 1
for x in range(int(width / grass.get_width() + 1)):
for y in range(int(height / grass.get_height() + 1)):
screen.blit(grass, (x * 100, y * 100))
screen.blit(castle, (0, 30))
screen.blit(castle, (0, 135))
screen.blit(castle, (0, 240))
screen.blit(castle, (0, 345))
# 6.1 - Seting player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1] - (playerpos[1] + 32), position[0] - (playerpos[0] + 26))
playerrot = pygame.transform.rotate(player, 360 - angle * 57.29)
playerpos1 = (playerpos[0] - playerrot.get_rect().width / 10, playerpos[1] - playerrot.get_rect().height / 2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index = 0
velx = math.cos(bullet[0]) * 10
vely = math.sin(bullet[0]) * 10
bullet[1] += velx
bullet[2] += vely
if bullet[1] < -64 or bullet[1] > 640 or bullet[2] < -64 or bullet[2] > 480:
arrows.pop(index)
# 6.3.1 - Attack castle
for bullet in arrows:
bullrect = pygame.Rect(arrow.get_rect())
bullrect.left = bullet[1]
bullrect.top = bullet[2]
if badrect.colliderect(bullrect):
acc[0] += 1
badguys.pop(index)
arrows.pop(index1)
index1 += 1
badrect = pygame.Rect(badguyimg.get_rect())
badrect.top = badguy[1]
badrect.left = badguy[0]
if badrect.left < 64:
healthvalue -= random.randint(5, 20)
badguys.pop(index)
# section 6.3.1 after if badrect.left<64:
hit.play()
# section 6.3.2 after if badrect.colliderect(bullrect):
enemy.play()
# 6.3.2 - Check for collisions
index1 = 0
# section 8, after if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
# 6.3.3 - Next bad guy
index += 1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360 - projectile[0] * 57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer == 0:
badguys.append([640, random.randint(50, 430)])
badtimer = 100 - (badtimer1 * 2)
if badtimer1 >= 35:
badtimer1 = 35
else:
badtimer1 += 5
index = 0
for badguy in badguys:
if badguy[0] < -64:
badguys.pop(index)
badguy[0] -= 7
index += 1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks()))+":"+str((pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - updating the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
exit(0)
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
You have wrong indentations.
You check keys inside if event.type == pygame.QUIT: so they are checked only when you close window.
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
# the same indentation like for other event.type
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
# the same indentation like for other event.type
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
# the same indentation like for other event.type
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# it should be outside `for event` loop
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
Similar problem is with drawing badguy.
BTW: instead of all thess settings and checkings of keys you could use pygame.key.get_pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
playerpos[1] -= 5
elif keys[pygame.K_a]:
playerpos[1] += 5
if keys[pygame.K_s]:
playerpos[0] -= 5
elif keys[pygame.K_d]:
playerpos[0] += 5

How do I stop my snake moving into itself (python, pygame)

this is my first game I have created using pygame, it's basically snake.
Please do not mind my hideous comments.
## William's Snake Game
import pygame
import time
import random
pygame.init()
##Global variables
# Colours
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 155, 0)
bground = (204, 204, 0)
# Display vars.
display_width = 800
display_height = 600
# Variables
gameDisplay = pygame.display.set_mode((display_width, display_height)) ##resolution, note that this is a tuple.
pygame.display.set_caption("Snake VS Apple") # Title at the top of the screen
icon = pygame.image.load('logoapple32x32.png') # Loads the icon for the top left
pygame.display.set_icon(icon) # Sets the icon for the top left
snakeHeadImg = pygame.image.load("snakeHead.png") # Loads the image for the snake head
appleImg = pygame.image.load("apple20x20.png") # Loads the image for the apple
appleThickness = 20 # Defines how thick apple will be. Note to self: This is changable
clock = pygame.time.Clock() # Starts clocking the game, used later for FPS
blockSize = 20 # Defines how big the snake will be. Changing this will mess up collision detection.
FPS = 15 # Frames per second. Called at the bottom of script
smallfont = pygame.font.SysFont("arial", 25) ## format: ("font", fontsize)
medfont = pygame.font.SysFont("arial", 40) ##
largefont = pygame.font.SysFont("arial", 80) ##
direction = "right" # Starting direction of snake, used in main gameLoop
##
def pauseGame():
gameisPaused = True
while gameisPaused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
gameisPaused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Paused",
black,
-100,
size="large")
message_to_screen("Press ESC to continue or Q to quit.",
black,
25,
size="small")
pygame.display.update()
clock.tick(5)
def text_objects(text, color, size): # Function to render text
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 message_to_screen(msg, color, y_displace=0, size="medium"): # Function to blit (draw) text to surface
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (display_width / 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
##
def score(score):
text = smallfont.render("Score: " + str(score), True, black)
gameDisplay.blit(text, [0, 0])
def randAppleGen(): # Function to generate random apples
randAppleX = round(
random.randrange(0, display_width - appleThickness)) # /10.0)*10.0 ##Create another rand X value for new apple
randAppleY = round(
random.randrange(0, display_height - appleThickness)) # /10.0)*10.0 ##Create another rand Y value for new apple
return randAppleX, randAppleY
def gameIntro(): # Function for game menu.
intro = True
while intro: # Event handling during menu
for eachEvent in pygame.event.get():
if eachEvent.type == pygame.QUIT:
pygame.quit()
quit()
if eachEvent.type == pygame.KEYDOWN:
if eachEvent.key == pygame.K_c:
gameLoop()
if eachEvent.key == pygame.K_q:
pygame.quit()
quit()
# Text displayed in menu
gameDisplay.fill(white)
message_to_screen("Welcome to Slither",
green,
-90,
"large")
message_to_screen("The more apples you eat, the longer you are",
black,
100)
message_to_screen("The objective of the game is to eat red apples",
black,
0,
"small")
message_to_screen("If you run into yourself, or the edges, you die!",
black,
30,
"small")
message_to_screen("Press C to play or Q to quit.",
black,
180)
pygame.display.update()
clock.tick(500)
def snake(blockSize, snakeList): # Function to draw snake
if direction == "right":
head = pygame.transform.rotate(snakeHeadImg,
270) # In gameLoop, right,left,up,down are used to change direction of snakeHead
elif direction == "left":
head = pygame.transform.rotate(snakeHeadImg, 90)
elif direction == "up":
head = snakeHeadImg
elif direction == "down":
head = pygame.transform.rotate(snakeHeadImg, 180)
gameDisplay.blit(head, (snakeList[-1][0], snakeList[-1][1])) ##???
for XandY in snakeList[:-1]:
pygame.draw.rect(gameDisplay, green,
[XandY[0], XandY[1], blockSize, blockSize]) ##width height, width height, drawing
##Main Game Loop
def gameLoop():
global direction ## Make direction a global var. Important
# Local variables
gameExit = False
gameOver = False
lead_x = display_width / 2
lead_y = display_height / 2
lead_x_change = 10
lead_y_change = 0
snakeList = []
snakeLength = 3
randAppleX, randAppleY = randAppleGen() # Generate apples. Calls randAppleGen()
# Main Game Loop ##eventHandler
while not gameExit:
snakeHead = [] # Creates list snakeHead
snakeHead.append(lead_x) # Appends snakeHead x value to list
snakeHead.append(lead_y) # Appends snakeHead y value to list
snakeList.append(snakeHead) # Appends coordinates of snakeHead x,y to list
while gameOver == True: # Handles game over
gameDisplay.fill(white)
message_to_screen("Game over",
red,
-50,
size="large")
message_to_screen("Press C to play again or Q to quit",
black,
50,
size="medium")
pygame.display.update()
for event in pygame.event.get(): # eventHandler for loss screen
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
direction = "right"
gameLoop()
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a: # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP or event.key == pygame.K_w:
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
# Checks if user has hit screen boundaries.
if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0: # If user hits display boundaries
gameOver = True # They lose
lead_x += lead_x_change # Ensures continous movement of the snake
lead_y += lead_y_change
# Drawing
gameDisplay.fill(bground) # Fills the display background with predefined bground colour (defined at the top)
gameDisplay.blit(appleImg,
(randAppleX, randAppleY)) ##Draws the apple using the appleImg, at random coordinates.
if len(
snakeList) > snakeLength: # If the length of the list of snake body coordinates is greater than the length
del snakeList[0] # Delete the oldest value in the list (as the snake is constantly moving)
for eachSegment in snakeList[:-1]: # For each coordinate in snakeList
if eachSegment == snakeHead: # If the segment touches the snakeHead
## gameDisplay.fill(bground)
## snake(blockSize, snakeList)
##
## pygame.display.update
time.sleep(0.3)
gameOver = True # Game over
snake(blockSize, snakeList) ##Creates snake using function snake
score(snakeLength - 3) # Displays score (it minuses 3 because the snake starts at 3)
pygame.display.update() ##Updates to screen
## COLLISION DETECTION
if lead_x + blockSize > randAppleX and lead_x < randAppleX + appleThickness:
if lead_y + blockSize > randAppleY and lead_y < randAppleY + appleThickness:
randAppleX, randAppleY = randAppleGen()
snakeLength += 1
clock.tick(FPS)
pygame.quit()
quit()
##update screen
##
gameIntro()
gameLoop()
##Code goes above.
I have a problem where if my snake is going right, and then it turns left, my snake will crash onto itself and the game will end.
I want to design this so when my snake is going right, it cannot simply turn left, crash into itself and end the game. So when it turns right, it can only turn up, down, or keep going right. So simply, I want to make it so it cannot run backwards into itself.
I have tried coding this in myself, and I have tried many methods but nothing has worked.
Please help!!
Without altering your code too much (and without testing), an easy way to get what you want is to add another condition to your key checks. If you alter the relevant code section as follows, all should be fine:
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and direction != "right": # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and direction != "left":
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif (event.key == pygame.K_UP or event.key == pygame.K_w) and direction != "down":
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and direction != "up":
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
Mind the parentheses around the or'd key checks!

how do I fire a bullet with mouse in pygame? [duplicate]

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()

Categories

Resources