it always prints "2", please help me
this is my codes:
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
if 10 < computer <= 18:
computer = 1
elif computer <= 10:
computer = 2
this is all my code:
import pygame
from random import randint
def draw_floor():
screen.blit(floor, (floorrunning, 453))
screen.blit(floor, (floorrunning + 800, 453))
pygame.init()
bg = pygame.image.load("background.png")
screen = pygame.display.set_mode((800,500))
GREY = (120, 120, 120)
WHITE = (255, 255, 255)
floor = pygame.image.load("quangcaobanthan.png")
floorrunning = 0
xucxac1 = pygame.image.load("nan1.png")
xucxac2 = pygame.image.load("nan1_2.png")
xucxac3 = pygame.image.load("nan1_3.png")
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
youlose = pygame.image.load("youlose.png")
youlose_rect = youlose.get_rect(center = (400, 250))
youwin = pygame.image.load("youwin.png")
youwin_rect = youwin.get_rect(center = (400, 250))
running = True
replay = True
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
if 10 < computer <= 18:
computer = 1
elif computer <= 10:
computer = 2
game_font = pygame.font.SysFont("04B_19.ttf", 40)
player = 0
def ketqua():
ketqua1_infor = game_font.render(str(ketqua1), True, (0,0,0))
ketqua1_rect = (190, 334)
screen.blit(ketqua1_infor, ketqua1_rect)
ketqua2_infor = game_font.render(str(ketqua2), True, (0,0,0))
ketqua2_rect = (390, 334)
screen.blit(ketqua2_infor, ketqua2_rect)
ketqua3_infor = game_font.render(str(ketqua3), True, (0,0,0))
ketqua3_rect = (590, 334)
screen.blit(ketqua3_infor, ketqua3_rect)
while running:
screen.blit(bg,(0,0))
mouse_x, mouse_y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and replay == False:
replay = True
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (100 < mouse_x < 300) and (100 < mouse_y < 221):
player = 1
if (500 < mouse_x < 700) and (100 < mouse_y < 211):
player = 2
if xucxac1_rect == (41, 300) and xucxac2_rect == (241, 300) and xucxac3_rect == (441, 300):
screen.blit(youwin, youwin_rect)
screen.blit(youlose, youlose_rect)
pygame.draw.rect(screen, WHITE, (100, 100, 200, 121))
pygame.draw.rect(screen, WHITE, (500, 100, 200, 111))
pygame.draw.rect(screen, WHITE, (277, 0, 240, 100))
screen.blit(pygame.image.load("tai.png"), (100,100))
screen.blit(pygame.image.load("xiu.png"), (500,100))
screen.blit(pygame.image.load("start.png"), (275, -60))
print(computer)
draw_floor()
floorrunning -= 0.5
if floorrunning <= -800:
floorrunning = 0
if replay == False:
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
if replay:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (141 < mouse_x < 241) and (300 < mouse_y < 400):
xucxac1_rect = (41, 300)
if (341 < mouse_x < 441) and (300 < mouse_y < 400):
xucxac2_rect = (241, 300)
if (541 < mouse_x < 641) and (300 < mouse_y < 400):
xucxac3_rect = (441, 300)
if (277 < mouse_x < 527) and (0 < mouse_y < 79):
replay = False
pygame.draw.rect(screen, GREY, (50, 290, 700, 120))
pygame.draw.circle(screen, GREY, (195, 350), 48)
pygame.draw.circle(screen, GREY, (395, 350), 48)
pygame.draw.circle(screen , GREY,(595, 350), 48)
screen.blit(xucxac1, xucxac1_rect)
screen.blit(xucxac2, xucxac2_rect)
screen.blit(xucxac3, xucxac3_rect)
ketqua()
pygame.display.flip()
pygame.quit()
Your code runs randomly.
That means there is a change that you get 1 day, one week, one month the same answer.
Assuming that you have from random import randint
Then you could thy this:
def execute():
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
if 10 < computer <= 18:
computer = 1
elif computer <= 10:
computer = 2
return computer
histogram = [0,0,0]
for _ in range(100):
c = execute()
histogram[c] += 1
print("Times we got computer==1: {}".format(histogram[1]))
print("Times we got computer==2: {}".format(histogram[2]))
You should have something like this:
Times we got computer==1: 49
Times we got computer==2: 51
So randint is being used well...
Related
I want to make squer move with keyboard input but its realy wierd. When i try to move it, it needs 2,5 seconds to actualy go, it has random speed ups, and if I click A so it goes left then I can click ANY key and it will go left like R or P, and controls can switch if I try to go up and left.
Code for player controlls is more down.
Code:
import pygame
from pygame.locals import *
pygame.init()
pygame.display.set_caption("Clicker")
# VALUES
clock = pygame.time.Clock()
coins: int = 0
running: bool = True
printed_s: bool = False
printed_sp: bool = False
printed_str: bool = False
f11: bool = False
stamina: int = 0
speed: int = 0
strength: int = 0
playerX: int = 650
playerY: int = 500
playerX_change: int = 0
playerY_change: int = 0
fps: int = 60
# UI/fonts
font_one = pygame.font.Font(None, 150)
surface_one = font_one.render('You beat the game', True, 'Green')
# MAIN LOOP
while running:
clock.tick(fps)
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN, RESIZABLE)
screen.fill((130, 30, 90))
pygame.draw.rect(screen, (255, 0, 0), (playerX, playerY, 20, 20))
# FONTS
coin_font = pygame.font.Font(None, 30)
notification_font = pygame.font.Font(None, 50)
# SURFACE
coin_surface = coin_font.render(f'You have: {coins}', True, 'Green')
speed_surface = coin_font.render(f'Speed level: {speed}', True, 'Green')
stamina_surface = coin_font.render(f'Stamina level: {stamina}', True, 'Green')
strength_surface = coin_font.render(f'Strength level: {strength}', True, 'Green')
notification_surface = notification_font.render('Notifications', True, 'Green')
# BLIT
screen.blit(coin_surface, (0, 0))
screen.blit(speed_surface, (0, 630))
screen.blit(stamina_surface, (0, 680))
screen.blit(strength_surface, (0, 730))
screen.blit(notification_surface, (1130, 0))
# KEYS
for event in pygame.event.get():
# KEY DOWN
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_1 and coins >= 5:
coins -= 5
speed += 1
elif event.key == pygame.K_1 and coins < 5:
print("You need more coins")
if event.key == pygame.K_2 and coins >= 10:
coins -= 10
strength += 1
elif event.key == pygame.K_2 and coins < 10:
print("You need more coins")
if event.key == pygame.K_3 and coins >= 15:
coins -= 15
stamina += 1
elif event.key == pygame.K_3 and coins < 15:
print("You need more coins")
# PLAYER PART WHERE I NEED HELP
if event.key == pygame.K_a:
playerX_change -= 3
else:
playerX_change -= 0
if event.key == pygame.K_d:
playerX_change += 3
else:
playerX_change -= 0
if event.key == pygame.K_s:
playerY_change += 3
else:
playerY_change -= 0
if event.key == pygame.K_w:
playerY_change -= 3
else:
playerY_change -= 0
playerX += playerX_change
playerY += playerY_change
# MOUSE BUTTON DOWN
if event.type == pygame.MOUSEBUTTONDOWN:
pressed_keys = pygame.mouse.get_pressed()
if pressed_keys[0]:
coins += 1
# SHOP
if stamina == 30 and not printed_s:
print("You maxed stamina")
printed_s = True
if speed == 30 and not printed_sp:
print("You maxed speed")
printed_sp = True
if strength == 30 and not printed_str:
print("You maxed strength")
printed_str = True
# DRAW
pygame.draw.line(screen, 'Green', (1100, 0), (1100, 200), 5)
pygame.draw.line(screen, 'Green', (1100, 200), (1400, 200), 5)
pygame.draw.line(screen, 'White', (200, 250), (200, 700), 5)
pygame.draw.line(screen, 'White', (200, 700), (1100, 700), 5)
pygame.draw.line(screen, 'White', (1100, 700), (1100, 250), 5)
pygame.draw.line(screen, 'White', (200, 250), (1100, 250), 5)
# END
if strength == 30 and speed == 30 and stamina == 30:
screen.blit(surface_one, (250, 250))
pygame.display.update()
This question already has answers here:
Pygame mouse clicking detection
(4 answers)
How do I detect collision in pygame?
(5 answers)
Closed 12 months ago.
I run the codes below. The computer always print "win" if (500 < mouse_x < 700) and (100 < mouse_y < 211) (player = 2) and "lose" if (100 < mouse_x < 300) and (100 < mouse_y < 221) (player = 1). I had checked the "player" and it works fine, but the "computer" always print value "2". If I change "if computer <= 10" to "else": "computer" always print value "1"
This is my codes:
import pygame
from random import randint
def draw_floor():
screen.blit(floor, (floorrunning, 453))
screen.blit(floor, (floorrunning + 800, 453))
pygame.init()
bg = pygame.image.load("background.png")
screen = pygame.display.set_mode((800,500))
GREY = (120, 120, 120)
WHITE = (255, 255, 255)
BLANK = (0, 0, 0)
floor = pygame.image.load("quangcaobanthan.png")
floorrunning = 0
xucxac1 = pygame.image.load("nan1.png")
xucxac2 = pygame.image.load("nan1_2.png")
xucxac3 = pygame.image.load("nan1_3.png")
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
youlose = pygame.image.load("youlose.png")
youlose_rect = youlose.get_rect(center = (400, 250))
youwin = pygame.image.load("youwin.png")
youwin_rect = youwin.get_rect(center = (400, 250))
running = True
replay = True
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
computer = ketqua1 + ketqua2 + ketqua3
game_font = pygame.font.SysFont("04B_19.ttf", 40)
player = 0
def ketqua():
ketqua1_infor = game_font.render(str(ketqua1), True, (0,0,0))
ketqua1_rect = (190, 334)
screen.blit(ketqua1_infor, ketqua1_rect)
ketqua2_infor = game_font.render(str(ketqua2), True, (0,0,0))
ketqua2_rect = (390, 334)
screen.blit(ketqua2_infor, ketqua2_rect)
ketqua3_infor = game_font.render(str(ketqua3), True, (0,0,0))
ketqua3_rect = (590, 334)
screen.blit(ketqua3_infor, ketqua3_rect)
while running:
screen.blit(bg,(0,0))
mouse_x, mouse_y = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and replay == False:
replay = True
xucxac1_rect = (141, 300)
xucxac2_rect = (341, 300)
xucxac3_rect = (541, 300)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (100 < mouse_x < 300) and (100 < mouse_y < 221):
player = 1
if (500 < mouse_x < 700) and (100 < mouse_y < 211):
player = 2
if 10 < computer <= 18:
computer = 1
if computer <= 10:
computer = 2
if xucxac1_rect == (41, 300) and xucxac2_rect == (241, 300) and xucxac3_rect == (441, 300):
if computer == player:
print("win")
else:
print("lose")
pygame.draw.rect(screen, WHITE, (100, 100, 200, 121))
pygame.draw.rect(screen, WHITE, (500, 100, 200, 111))
pygame.draw.rect(screen, WHITE, (277, 0, 240, 100))
screen.blit(pygame.image.load("tai.png"), (100,100))
screen.blit(pygame.image.load("xiu.png"), (500,100))
screen.blit(pygame.image.load("start.png"), (275, -60))
draw_floor()
floorrunning -= 0.5
if floorrunning <= -800:
floorrunning = 0
if replay == False:
ketqua1 = randint(1,6)
ketqua2 = randint(1,6)
ketqua3 = randint(1,6)
if replay:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if (141 < mouse_x < 241) and (300 < mouse_y < 400):
xucxac1_rect = (41, 300)
if (341 < mouse_x < 441) and (300 < mouse_y < 400):
xucxac2_rect = (241, 300)
if (541 < mouse_x < 641) and (300 < mouse_y < 400):
xucxac3_rect = (441, 300)
if (277 < mouse_x < 527) and (0 < mouse_y < 79):
replay = False
pygame.draw.rect(screen, GREY, (50, 290, 700, 120))
pygame.draw.circle(screen, GREY, (195, 350), 48)
pygame.draw.circle(screen, GREY, (395, 350), 48)
pygame.draw.circle(screen , GREY,(595, 350), 48)
screen.blit(xucxac1, xucxac1_rect)
screen.blit(xucxac2, xucxac2_rect)
screen.blit(xucxac3, xucxac3_rect)
else:
pygame.draw.rect(screen, BLANK, (50, 290, 700, 120))
ketqua()
pygame.display.flip()
pygame.quit()
So I have this code that's my main game:
def game():
running = True
import pygame, sys
import random
import math as m
mainClock = pygame.time.Clock()
pygame.init()
pygame.font.init
pygame.display.set_caption('Ping Pong')
SCREEN = width, height = 900,600
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0,0,0)
speed = [4,4]
font = pygame.font.Font('freesansbold.ttf', 32)
score = 0
score = str(score)
font.size(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen = pygame.display.set_mode(SCREEN, 0,32)
height1 = height/4
score = int(score)
ball = pygame.Rect(width/2, height/2, 50,50)
player = pygame.Rect(0,(height/2),25,height1)
player_1 = pygame.Rect(width - 25,(height/2),25,height1)
font1 = pygame.font.Font('freesansbold.ttf', 32)
score1 = 0
score1 = str(score)
font1.size(score1)
font1.set_bold(True)
text1 = font1.render(score1, True, white)
score1 = int(score1)
textRect1 = text1.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
up = False
down = False
up_1 = False
down_1 = False
RED = (255,0,0)
particles = []
while running:
color = (192,192,192)
# clear display #
screen.fill((0,0,0))
screen.blit(text, textRect)
screen.blit(text1, textRect1)
bx = ball.centerx
by = ball.centery
particles.append([[bx, by],[random.randint(0,20) / 10 - 1, -1], random.randint(4,6)])
for particle in particles:
particle[0][0] += particle[1][0]
particle[0][1] += particle[1][1]
particle[2] -= 0.1
particle[1][1] += 0.1
pygame.draw.circle(screen, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
if particle[2] <= 0:
particles.remove(particle)
if up == True:
player.y -= 5
if down == True:
player.y += 5
if up_1 == True:
player_1.y -= 5
if down_1 == True:
player_1.y += 5
if player.top < 0 :
player.y = 0
if player.bottom > height:
player.bottom = height
if player_1.top < 0 :
player_1.y = 0
if player_1.bottom > height :
player_1.bottom = height
for i in range(-90,(height + 130), 120):
rectangle = pygame.Rect((width/2), i, 13, 60)
pygame.draw.rect(screen, (255,255,255), rectangle)
pygame.draw.rect(screen,(191, 224, 255),player)
pygame.draw.rect(screen,(191, 224, 255),player_1)
color = (192,192,192)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
pygame.draw.rect(screen,color,ball, 3)
import time
ball.x += speed[0]
ball.y += speed[1]
if ball.top < 0 or ball.bottom > height:
speed[1] = -speed[1]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
pygame.draw.circle(screen, (r,b,g), [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
dab = random.randint(0,1)
if ball.left < 0 :
font = pygame.font.Font('freesansbold.ttf', 32)
score1 = int(score1)
score1 += 1
score1 = str(score1)
font.set_bold(True)
text1 = font.render(score1, True, white)
textRect1 = text.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
screen.blit(text1, textRect1)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
if ball.right > width:
font = pygame.font.Font('freesansbold.ttf', 32)
score = int(score)
score += 1
score = str(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen.blit(text, textRect)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
# event handling #
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_s:
down = True
if event.key == K_w:
up = True
if event.key == K_UP:
up_1 =True
if event.key == K_ESCAPE:
running = False
if event.key == K_DOWN:
down_1 = True
if event.type == KEYUP:
if event.key == K_s:
down = False
if event.key == K_w:
up = False
if event.key == K_UP:
up_1 = False
if event.key == K_DOWN:
down_1 = False
if ball.colliderect(player_1):
dab = random.randint(0,1)
if dab == 1:
speed[1] = -speed[1]
speed[0] = -speed[0]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
if ball.colliderect(player):
speed[0] = -speed[0]
speed[0] = random.randint(4,6)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
# update display #
pygame.display.update()
mainClock.tick(60)
and I have a menu screen that displays some options. Only button_1 works.:
def main_menu():
while True:
white = (255,255,255)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
screen.fill((0,0,0))
button_1 = pygame.Rect(width/2, (height/2), width/2, 50)
button_1.centerx = width/2
button_2 = pygame.Rect(width/2, height/1.5, width/2, 50)
button_2.centerx = width/2
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
#draw_text('Start!', font, (255, 255, 255), screen, button_1.centerx, button_1.centery)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
text1 = font.render('Start!', True, white)
textRect1 = text1.get_rect()
textRect1.center = (button_1.centerx, button_1.centery)
screen.blit(text1, textRect1)
mx, my = pygame.mouse.get_pos()
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
options()
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
clock.tick(60)
How do I make it so that after button_1 is pressed, there's a 3,2,1 countdown on the screen, and then the game starts?
In order to do the countdown, you import the time module:
import time
...then you need a for loop, with a step -1, counting down from 3 to 1. Inside the for loop, print the numbers and sleep one second, using the time module:
for a in range(3,0,-1):
print(a)
time.sleep(1)
After this for loop, you put the rest of your code.
I have made a little game with your player being a car and a car coming at you. I want there to be two cars coming at you but i'm not sure how to start this. I know I need another surface and Rect value for it as it needs to be able to check collision. Also, is there anyway I could get two cars coming at once from one side or is this not possible?
import time, pygame, random
import math
pygame.init()
#First Variables
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (100, 255, 100)
ORANGE = (255, 140, 0)
YELLOW = (155, 135, 12)
white = (255, 255, 255)
GOLD = (255, 215, 0)
screenwidth = 500
screenheight = 500
Lines = True
Space = True
color = random.sample(range(250), 3)
doris = []
i = []
x = 247
y = - 20
y1 = 40
y2 = 100
y3 = 160
y4 = 220
y5 = 280
y6 = 340
y7 = 400
y8 = 460
#Display and caption
win = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption('Lil cary')
clock = pygame.time.Clock()
#Load in images
bkg = pygame.image.load('BG.jpg')
#Actual player class
class player():
def __init__(self):
self.color = (12, 124, 134)
self.vel = 5
self.grassdamage = 0
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(center = (200, 390))
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
self.damage5 = False
self.damage6 = False
self.damage7 = False
self.damage8 = False
self.dead = False
def draw (self, win):
#pygame.draw.rect(win, (self.color), (self.x, self.y, self.width, self.height))
win.blit(self.image, self.rect.topleft)
def moveback(self):
if self.rect.y < 390 and self.rect.y >= 0:
self.rect.y += 10
def grass(self):
if self.rect.x > -10 and self.rect.x < 150:
self.grassdamage += 1
self.vel = 3
elif self.rect.x > 300 and self.rect.x < 500:
self.vel =3
self.grassdamage += 1
else:
self.vel = 5
def grasshealth(self):
if self.grassdamage == 100:
self.damage1 = True
elif self.grassdamage == 200:
self.damage2 = True
elif self.grassdamage == 300:
self.damage3 = True
elif self.grassdamage == 400:
self.damage4 = True
elif self.grassdamage == 500:
self.damage5 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 700:
self.damage7 = True
elif self.grassdamage == 800:
self.damage8 = True
self.dead = True
def death(self):
if self.dead == True:
exit()
#Text Setup
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
#Drawing damage bar
def drawbar ():
if player.damage1 == True and car.damage1 == False or car.damage1 == True:
pygame.draw.rect(win, (GOLD), (50, 50, 25, 25))
if player.damage2 == True and car.damage1 == False or car.damage1 == True:
pygame.draw.rect(win, (GOLD), (50, 75, 25, 25))
if car.damage1 == True and player.grassdamage <= 200:
player.grassdamage = 201
if player.damage3 == True and car.damage2 == False or car.damage2 == True:
pygame.draw.rect(win, (GOLD), (50, 100, 25, 25))
if player.damage4 == True and car.damage2 == False or car.damage2 == True:
pygame.draw.rect(win, (GOLD), (50, 125, 25, 25))
if car.damage2 == True and player.grassdamage <= 400:
player.grassdamage = 401
if player.damage5 == True and car.damage3 == False or car.damage3 == True:
pygame.draw.rect(win, (GOLD), (50, 150, 25, 25))
if player.damage6 == True and car.damage3 == False or car.damage3 == True:
pygame.draw.rect(win, (GOLD), (50, 175, 25, 25))
if car.damage3 == True and player.grassdamage <= 600:
player.grassdamage = 601
if player.damage7 == True and car.damage4 == False or car.damage4 == True:
pygame.draw.rect(win, (GOLD), (50, 200, 25, 25))
if player.damage8 == True and car.damage4 == False or car.damage4 == True:
pygame.draw.rect(win, (GOLD), (50, 225, 25, 25))
raise SystemExit ('YOU LOST')
if car.damage4 == True and player.grassdamage <= 800:
player.grassdamage = 800
pygame.draw.rect(win, (0,0,0), (50, 50, 25, 200), 3)
Text = pygame.font.Font('freesansbold.ttf', 20)
TextSurf, TextRect = text_objects("Damage", Text)
TextRect.center = ((65), (30))
win.blit(TextSurf, TextRect)
class car():
def __init__(self):
self.color = random.sample(range(250), 3)
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(topleft = (175, -100))
self.carvel = random.randrange(5, 10)
self.damage = 0
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
def draw(self, win):
#pygame.draw.rect(win,(self.color),self.rect)
win.blit(self.image, self.rect.topleft)
def move(self):
if self.rect.y < 530:
self.rect.y += self.carvel
else:
self.rect.y = -100
self.color = random.sample(range(250), 3)
self.carvel = random.randrange(8, 10)
def collision_check(self, another_object):
if self.rect.colliderect(another_object):
print('collison')
self.rect.y = -100
self.damage += 1
def cardamage(self):
if self.damage == 1:
self.damage1 = True
player.damage1 = True
player.damage2 = True
if self.damage == 2:
self.damage2 = True
player.damage3 = True
player.damage4 = True
if self.damage == 3:
self.damage3 = True
player.damage5 = True
player.damage6 = True
if self.damage == 4:
self.damage4 = True
player.damage7 = True
player.damage8 = True
#Putting variables to the classes
player = player()
car = car()
#Main drawing function
def redrawgamewindow():
win.blit(bkg, (0, 0))
pygame.draw.rect(win, (0, 0, 0), (150, 0, 200, 500))
pygame.draw.rect(win, (255, 255, 255), (x, (y), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y1), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y2), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y3), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y4), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y5), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y6), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y7), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y8), 10, 30))
player.draw(win)
car.draw(win)
player.grasshealth()
car.cardamage()
player.grass()
player.death()
car.collision_check(player.rect)
car.move()
drawbar()
pygame.display.update()
#MAINLOOP
run = True
while run:
#Making background and FPS
clock.tick(80)
#Quiting Funciton
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
#Scrolling the lines
if Lines:
y += player.vel
y1 += player.vel
y2 += player.vel
y3 += player.vel
y4 += player.vel
y5 += player.vel
y6 += player.vel
y7 += player.vel
y8 += player.vel
if Lines:
if y >= 500:
y = -40
if y1 >= 500:
y1 = -40
if y2 >= 500:
y2 = -40
if y3 >= 500:
y3 = -40
if y4 >= 500:
y4 = -40
if y5 >= 500:
y5 = -40
if y6 >= 500:
y6 = -40
if y7 >= 500:
y7 = -40
if y8 >= 500:
y8 = -40
#User input
keys = pygame.key.get_pressed()
#Boost controller
if keys[pygame.K_SPACE]:
start_time = time.time()
if player.rect.y > 200:
player.rect.y -= 9
Space = True
else:
player.moveback()
end_time = time.time()
#Left movement
if keys[pygame.K_LEFT] and player.rect.x > 150:
player.rect.x -= 5
if keys [pygame.K_LEFT] and player.rect.x <= 150:
if player.rect.x > 0:
player.rect.x -=5
#Right movement
if keys[pygame.K_RIGHT] and player.rect.x < 300:
player.rect.x += 5
if keys[pygame.K_RIGHT]and player.rect.x >= 300:
if player.rect.x < 500 - player.rect.width:
player.rect.x += 5
#Grass and grass damage
#MAIN DRAW RECALL
redrawgamewindow()
Your code is pretty-much there already. Instead of just creating one Car, make a list of Cars. Where the car is draw, collided, etc., now do that for every car in the list. After some event, say 3 seconds pass, add another car to the list.
For example:
car = Car()
car_list = [ car ] # start with one car
car_add_time = 0
Now it's easy to add more cars:
while run:
#Making background and FPS
clock.tick(80)
### Add another car after 3 seconds
time_now = pygame.time.get_ticks()
if ( time_now - car_add_time > 3000 ):
new_car = Car()
car_list.append( new_car )
car_add_time = time_now
Re-drawing the car list:
def redrawgamewindow():
# ...
for car in car_list:
car.draw(win)
player.grasshealth()
for car in car_list:
car.cardamage()
player.grass()
player.death()
for car in car_list:
car.collision_check(player.rect)
car.move()
One other thing you need to do, is change the Car class to start the car in a random x-position (but still within the road (... or not)). Since the code just recycles the car back to -100 when it collides or moves off-screen, it also needs to be re-positioned here too.
For example:
class Car():
ROAD_LEFT = 150 # this is a rough guess on the correct spot
ROAD_RIGHT = 300
def __init__(self):
# ...
x_pos = random.randrange( Car.ROAD_LEFT, Car.ROAD_RIGHT )
self.rect = self.image.get_rect(topleft = ( x_pos, -100) )
I'm making a game with pygame, Space Invaders, and now I'm doing the collisions between the shoot of the eneimies and the player (those are images), but it doesn't work all time and I'd like to know why, and what's the solution.
Thanks for attention!
Here's the code:
# -*- coding: cp1252 -*-
import sys
import random
import pygame
import time
print pygame.init()
x_player, y_player = 650, 440
screen = pygame.display.set_mode((700, 500))
pygame.display.set_caption("Space Invaders v1.0.0")
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders- my_own\\space-invaders.jpeg").convert_alpha()
player = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\28006.png").convert_alpha()
mother_ship = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\mother_ship.png").convert_alpha()
lifes = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\28007.png").convert_alpha()
shoot_enemie = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\shots_and_bombs2.png").convert_alpha()
shoot = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\shots_and_bombs2.png").convert_alpha()
pygame.font.init()
clock = pygame.time.Clock()
move_x = 0
x_invaders, y_invaders = 60, 60
lifes_list = [lifes, lifes, lifes]
x_mother = 0
invaders_matrix = [[invaders] * 11] * 5
existe_nave = False
start = True
tru = False
tru3= True
x_shoot = x_player
y_shoot = 0
tru2 = True
shoot_enemie1, shoot_enemie2, shoot_enemie3 = shoot_enemie, shoot_enemie, shoot_enemie
shoot_list = [shoot_enemie1, shoot_enemie2, shoot_enemie]
tiros = {
"se1" : [0, 0],
"se2" : [0, 0],
"se3" : [0, 0]
}
cont = 0
while True:
invaders_matrix = [[invaders] * 11] * 5
if len(lifes_list) > 0:
clock.tick(40)
screen.fill((0, 0, 0))
screen.blit(player, ((x_player / 2), y_player))
if not tru:
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\space- invader-motif.png"
).convert_alpha()
tru = True
else:
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\space-invaders.jpeg"
).convert_alpha()
tru = False
x_invaders, y_invaders = 105, 125
for invader in range(len(invaders_matrix)):
for invad in range(len(invaders_matrix[invader])):
screen.blit(invaders_matrix[invader][invad], (x_invaders, y_invaders))
x_invaders += 45
x_invaders = 105
y_invaders += 30
if tru2:
for i in tiros.keys():
tiros[i][0] += tiros[i][0] + random.randint(0, 10) * 45 + 105
tiros[i][1] += tiros[i][1] + random.randint(0, 4) * 45 + 125
tru2 = False
elif tiros["se1"][1] >= 600 and tiros["se2"][1] >= 600 and tiros["se3"][1] >= 600:
tiros["se1"][1], tiros["se2"][1], tiros["se3"][1], \
tiros["se1"][0], tiros["se2"][0], tiros["se3"][0] = 0, 0, 0, 0, 0, 0
for i in tiros.keys():
tiros[i][0] += tiros[i][0] + random.randint(0, 10) * 45 + 105
tiros[i][1] += tiros[i][1] + random.randint(0, 4) * 45 + 125
for i in shoot_list:
for j in tiros.keys():
screen.blit(i, (tiros[j][0], tiros[j][1]))
for i in tiros.keys():
tiros[i][1] += 4
if existe_nave and (x_mother < 700):
screen.blit(mother_ship, [x_mother, 35])
x_mother += 4.5
screen.blit(mother_ship, [x_mother, 35])
elif random.randint(0, 800) == 0:
existe_nave = True
x_mother = 0
width_for_lifes = 680
for icon_lifes in lifes_list:
width_for_lifes -= 50
screen.blit(icon_lifes, (width_for_lifes, 15))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
if tru3:
if event.key == pygame.K_SPACE:
y_shoot = y_player - player.get_height()
x_shoot = x_player / 2 + 20
tru3 = False
elif not tru3:
if y_shoot <= 0 and event.key == pygame.K_SPACE:
y_shoot = y_player - player.get_height()
x_shoot = x_player / 2 + 20
if event.type == pygame.KEYUP and (event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT):
move_x = 0
if y_shoot > -50:
screen.blit(shoot, (x_shoot, y_shoot))
y_shoot -= 10
if x_player >= 1280:
x_player = 1280
if x_player <= 25:
x_player = 25
x_player += move_x
font = pygame.font.Font(None, 36)
text = font.render("Lifes", 1, (0, 255, 85))
screen.blit(text, (450, 15))
font = pygame.font.Font(None, 36)
text = font.render("Score", 1, (0, 255, 85))
screen.blit(text, (20, 15))
#Here is the problem
player_rect = pygame.Rect(x_player, y_player, player.get_height(), player.get_width())
shoot_enemie1_rect = pygame.Rect(tiros["se1"][0], tiros["se1"][1], shoot_enemie1.get_height(),
shoot_enemie1.get_width())
shoot_enemie2_rect = pygame.Rect(tiros["se2"][0], tiros["se2"][1], shoot_enemie2.get_height(),
shoot_enemie2.get_width())
shoot_enemie3_rect = pygame.Rect(tiros["se3"][0], tiros["se3"][1], shoot_enemie3.get_height(),
shoot_enemie3.get_width())
if player_rect.colliderect(shoot_enemie1_rect) or player_rect.colliderect(shoot_enemie2_rect) or \
player_rect.colliderect(shoot_enemie3_rect):
print True
print player_rect
pygame.display.update()
Here is a collision detection code that will sense if one rectangle collides with another rectangle, if the enemy's shot hits the player:
if player x < shot x + player width and player x + shot width > shot x and player y < shot y + player height and shot height + player_y > shot y:
It works by sensing if any of the edges of the bullet are touching any edges of the character. I hope this helps.