Question

In: Computer Science

hi, can you please create me a game that is not too hard but not too...

hi, can you please create me a game that is not too hard but not too easy using pygame in python. can you also explain the codes in each line ?

Solutions

Expert Solution


"""
    Python Program for a bashing car game in Python using PyGame
"""


import pygame
import random

#   Colors used in the project
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (83, 92, 104)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
CAR_COLOR = (255, 54, 46)
TEXT_COLOR = (250, 196, 47)

#   Initialization - Game
pygame.init()

class Car:
    def __init__(self, x=0, y=0, dx=4, dy=0, width=30, height=30, color=RED):
        self.image = ""
        self.x = x
        self.y = y
        self. dx = dx
        self.dy = dy
        self.width = width
        self.height = height
        self.color = color

    def load_image(self, img):
        self.image = pygame.image.load(img).convert()
        self.image.set_colorkey(BLACK)

    def draw_image(self):
        screen.blit(self.image, [self.x, self.y])

    def move_x(self):
        self.x += self.dx

    def move_y(self):
        self.y += self.dy

    def draw_rect(self):
        pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height], 0)

    def check_out_of_screen(self):
        if self.x+self.width > 400 or self.x < 0:
            self.x -= self.dx


def check_collision(player_x, player_y, player_width, player_height, car_x, car_y, car_width, car_height):
    if (player_x+player_width > car_x) and (player_x < car_x+car_width) and (player_y < car_y+car_height) and (player_y+player_height > car_y):
        return True
    else:
        return False


#   Setting height and width of the screen [width, height]
size = (400, 700)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Street Racer")

#   Stay enabled until user closes
done = False

#   Frames Per Sec
clock = pygame.time.Clock()

#   Player's car as object
player = Car(175, 475, 0, 0, 70, 131, GREEN)
player.load_image("player.png")

collision = True

#   Variable to store the score
score = 0

#   Loading windows fonts
font_40 = pygame.font.SysFont("Century", 30, True, False)
font_30 = pygame.font.SysFont("Century", 20, True, False)
text_title = font_40.render("Street Racer", True, TEXT_COLOR)
text_ins = font_30.render("Click to Play!", True, TEXT_COLOR)


def draw_main_menu():
    screen.blit(text_title, [size[0] / 2 - 106, size[1] / 2 - 100])
    score_text = font_40.render("Score: " + str(score), True, TEXT_COLOR)
    screen.blit(score_text, [size[0] / 2 - 70, size[1] / 2 - 30])
    screen.blit(text_ins, [size[0] / 2 - 85, size[1] / 2 + 40])
    pygame.display.flip()


# Setup the enemy car boxes
cars = []
car_count = 2
for i in range(car_count):
    x = random.randrange(0, 340)
    car = Car(x, random.randrange(-150, -50), 0, random.randint(5, 10), 60, 60, CAR_COLOR)
    cars.append(car)


#   Setting stripes on road
stripes = []
stripe_count = 20
stripe_x = 185
stripe_y = -10
stripe_width = 20
stripe_height = 80
space = 20
for i in range(stripe_count):
    stripes.append([190, stripe_y])
    stripe_y += stripe_height + space

#   DRIVER PROGRAM HERE
while not done:
    #   MAIN EVENT STARTS HERE
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        #   Resetting previous objects when user starts a new game
        if collision and event.type == pygame.MOUSEBUTTONDOWN:
            collision = False
            for i in range(car_count):
                cars[i].y = random.randrange(-150, -50)
                cars[i].x = random.randrange(0, 350)
            player.x = 175
            player.dx = 0
            score = 0
            pygame.mouse.set_visible(False)

        if not collision:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    player.dx = 4
                elif event.key == pygame.K_LEFT:
                    player.dx = -4

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    player.dx = 0
                elif event.key == pygame.K_RIGHT:
                    player.dx = 0

    screen.fill(GRAY)

    #   GAME LOGIC

    #   Drawing elements on game board
    if not collision:
        # Drawing stripes
        for i in range(stripe_count):
            pygame.draw.rect(screen, WHITE, [stripes[i][0], stripes[i][1], stripe_width, stripe_height])
        # Moving the stripes
        for i in range(stripe_count):
            stripes[i][1] += 3
            if stripes[i][1] > size[1]:
                stripes[i][1] = -40 - stripe_height

        player.draw_image()
        player.move_x()
        player.check_out_of_screen()

        # Check if the enemy cars move out of the screen.
        for i in range(car_count):
            cars[i].draw_rect()
            cars[i].y += cars[i].dy
            if cars[i].y > size[1]:
                score += 10
                cars[i].y = random.randrange(-150, -50)
                cars[i].x = random.randrange(0, 340)
                cars[i].dy = random.randint(4, 9)

        # Check the collision of the player with the car
        for i in range(car_count):
            if check_collision(player.x, player.y, player.width, player.height, cars[i].x, cars[i].y, cars[i].width, cars[i].height):
                collision = True
                pygame.mouse.set_visible(True)
                break

        # Updating score
        txt_score = font_30.render("Score: "+str(score), True, WHITE)
        screen.blit(txt_score, [15, 15])

        pygame.display.flip()
    else:
        draw_main_menu()

    #   Setting 60 FPS
    clock.tick(60)

#   Close game window when quit
pygame.quit()

#   PROJECT ENDS HERE

player.png

Note: Please name the car image as "player.png". For queries, drop me a comment.


Related Solutions

Hi I'm having a hard time understand this can someone please explain it to me? Thank...
Hi I'm having a hard time understand this can someone please explain it to me? Thank you. Cholesterol is a type of fat found in the blood. It is measured as a concentration: the number of milligrams of cholesterol found per deciliter of blood (mg/dL). A high level of total cholesterol in the bloodstream increases risk for heart disease. For this problem, assume cholesterol in men and women follows a normal distribution, and that “adult man” and “adult woman” refers...
hi, can you draw me a cloud using turtle from python. please send me the codes
hi, can you draw me a cloud using turtle from python. please send me the codes
hi, can you please provide me a communication strategy of telstra company in a 500 words....
hi, can you please provide me a communication strategy of telstra company in a 500 words. i need this one. please provide me answer ASAP.
Hi, the person who answered this before did it wrong. Can you please show me the...
Hi, the person who answered this before did it wrong. Can you please show me the formulas of how to answer this. Hi-Tek Manufacturing Inc. makes two types of industrial component parts—the B300 and the T500. An absorption costing income statement for the most recent period is shown below: Hi-Tek Manufacturing Inc. Income Statement Sales $ 1,718,000 Cost of goods sold 1,220,369 Gross margin 497,631 Selling and administrative expenses 650,000 Net operating loss $ (152,369) Hi-Tek produced and sold 60,300...
Hi can anyone answer these for me before 12am tonight please! 1. Not only are you...
Hi can anyone answer these for me before 12am tonight please! 1. Not only are you a brilliant accountant, you also have a knack for technology. Over time you’ve been developing an idea for an internet search engine and email service that would make the founders of Google green with envy. You’ve begun offering this service for free to everyone, but to start earning revenues you’ve had to spend a lot of money on advertising. Because of this, you need...
can you please create the code program in PYTHON for me. i want to create array...
can you please create the code program in PYTHON for me. i want to create array matrix Nx1 (N is multiple of 4 and start from 16), and matrix has the value of elements like this: if N = 16, matrix is [ 4 4 4 4 -4 -4 -4 -4 4 4 4 4 -4 -4 -4 -4] if N = 64, matrix is [8 8 8 8 8 8 8 8 -8 -8 -8 -8 -8 -8 -8...
Hi can you assist me with this. Can you explain each of the similarities and differences...
Hi can you assist me with this. Can you explain each of the similarities and differences in maybe a short paragraph. Thank you so 3) Provide THREE ways in which Governmental entities are similar to For Profit Entities and THREE ways in which they are different (30 pts )
Computer Networks Hi guys. Please can you assist me in answering these questions. I will greatly...
Computer Networks Hi guys. Please can you assist me in answering these questions. I will greatly appreciate it. 1. Packets with sequence numbers 0, 1, 2, 3, 4 and 5 have all been sent to the receiver. The receiver has received packets with sequence numbers 0,1,3 and 4. In which protocol will packets with sequence numbers 2, 3 and 4 be resent? a. Stop and wait b. RDT3.0 c. Go-Back-N d. Selective repeat e. None of the above 2. A...
Hi, please could someone be of assistance with this assignment for me. Thank you The objective...
Hi, please could someone be of assistance with this assignment for me. Thank you The objective of this assignment is to practice the use of control objects in GUI design. You are required to create a 4- function calculator. See pic below. Calculator.png The calculator should have buttons for all 10 numbers, the decimal point, the four operations (+,-,/,*), an equal “=” button, a "main display" (TextBox or RichTextBot), a backspace button and a clear “C” button. When you create...
Can you please create me an income statement and balance sheet as the example below. Thank...
Can you please create me an income statement and balance sheet as the example below. Thank you Think about a business, movie, story, etc. that interests you and put together an Income Statement and Balance sheet for that entity. As an example I used The Three Bears from Goldilocks and .. Since we do not know what business the Bears were in, I'm going with Salmon Farming. If you remember the story, Goldilocks breaks into the bears' home, eats porridge,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT