I'm trying to update my self.health string every time the player collides with the cat enemy in Ursina, how do I do that? - ursina

The way I want to do that is draw a ray from Player() to the cat which is meow.Meow, and then update the text on screen every time the player collides with the cat.
class Player(Entity):
def __init__(self):
super().__init__(collider="box")
self.position = (0, 5, 0)
self.collider = 'box'
self.height = 2
self.speed = 5
self.gravity = 10
self.y_velocity = 0
self.jump_velocity = 5
self.on_ground = True
self.sprint_speed_modifier = 2
self.interact_distance = 5
self.shooting = False
self.last_shot = time.time()
self.mouse_sensitivity = Vec2(40, 40)
self.crosshair = Entity(parent=camera.ui, model='quad', color=color.white, scale=0.008, rotation_z=45)
self.camera_parent = Entity(parent=self, y=self.height)
self.inventory = Inventory(
Weapon(self.camera_parent, 0.25, (0.25, -0.25, 0.30), 180, 5, 20, True, 40, 0.25, 5, model='tommygun',
texture='tommygun'))
# self.weapon = Entity(parent=self.camera_parent, model='tommygun', texture='tommygun', position=(0.75, -0.95, 1), rotation_y=180)
self.health = 1000
camera.parent = self.camera_parent
camera.position = (0, 0, 0)
camera.rotation = (0, 0, 0)
camera.fov = 90
mouse.locked = True
global player_instance
player_instance = self
def tealth():
self.health -= 10
if isinstance(Player, meow.Meow):
tealth()
above is the local player class that I am doing that in.

You should use Entity's update() function here is its implementation in your code:
class Player(Entity):
def __init__(self):
super().__init__(collider="box")
self.position = (0, 5, 0)
self.collider = 'box'
self.height = 2
self.speed = 5
self.gravity = 10
self.y_velocity = 0
self.jump_velocity = 5
self.on_ground = True
self.sprint_speed_modifier = 2
self.interact_distance = 5
self.shooting = False
self.last_shot = time.time()
self.mouse_sensitivity = Vec2(40, 40)
self.crosshair = Entity(parent=camera.ui, model='quad', color=color.white, scale=0.008, rotation_z=45)
self.camera_parent = Entity(parent=self, y=self.height)
self.inventory = Inventory(
Weapon(self.camera_parent, 0.25, (0.25, -0.25, 0.30), 180, 5, 20, True, 40, 0.25, 5, model='tommygun',
texture='tommygun'))
# self.weapon = Entity(parent=self.camera_parent, model='tommygun', texture='tommygun', position=(0.75, -0.95, 1), rotation_y=180)
self.health = 1000
camera.parent = self.camera_parent
camera.position = (0, 0, 0)
camera.rotation = (0, 0, 0)
camera.fov = 90
mouse.locked = True
global player_instance
player_instance = self
def tealth(self):
self.health -= 10
def update(self):
if isinstance(Player, meow.Meow):
self.tealth()

Related

Keras Tuner on autoencoder - Add condition : first hidden layer units greater than or equal next hidden layer units

I want to use Keras-tuner to tune an autoencoder hyperparameters.
It is a symetric AE with two layers. I want the number of units in the first layer always greater than or equal the units in the second layer. But I don't know how implement it with keras-tuner. If someone can help, it would be very great. Thank you in advance.
class DAE(tf.keras.Model):
'''
A DAE model
'''
def __init__(self, hp, **kwargs):
'''
DAE instantiation
args :
hp : Tuner
input_dim : input dimension
return:
None
'''
super(DAE, self).__init__(**kwargs)
input_dim = 15
latent_dim = hp.Choice("latent_space", [2,4,8])
units_0 = hp.Choice("units_0", [8, 16, 32, 64])
units_1 = hp.Choice("units_1", [8, 16, 32, 64])
for i in [8, 16, 32, 64]:
with hp.conditional_scope("units_0", [i]):
if units_0 == i:
......? # units_1 should be <= i
dropout = hp.Choice("dropout_rate", [0.1, 0.2, 0.3, 0.4, 0.5])
inputs = tf.keras.Input(shape = (input_dim,))
x = layers.Dense(units_0, activation="relu")(inputs)
x = layers.Dropout(dropout)(x)
x = layers.Dense(units_1, activation="relu")(x)
x = layers.Dropout(dropout)(x)
z = layers.Dense(latent_dim)(x)
self.encoder = tf.keras.Model(inputs, z, name="encoder")
inputs = tf.keras.Input(shape=(latent_dim,))
x = layers.Dense(units_1, activation="relu")(inputs)
x = layers.Dropout(dropout)(x)
x = layers.Dense(units_0, activation="relu")(x)
x = layers.Dropout(dropout)(x)
outputs = layers.Dense(input_dim, activation="linear")(x)
self.decoder = tf.keras.Model(inputs, outputs, name="decoder")```
See above my code. It's a denoising autoencoder class
I found the solution. We need to create differents units_1 for for each units_O values
class DAE(tf.keras.Model):
'''
A DAE model
'''
def __init__(self, hp, training=None, **kwargs):
'''
DAE instantiation
args :
hp : Tuner
input_dim : input dimension
return:
None
'''
super(DAE, self).__init__(**kwargs)
self.input_dim = 15
l_units = [16, 32, 64, 128]
latent_dim = hp.Choice("latent_space", [2,4,8])
units_0 = hp.Choice("units_0", l_units)
dropout_0 = hp.Choice("dropout_rate_0", [0.1, 0.2, 0.3, 0.4, 0.5])
dropout_1 = hp.Choice("dropout_rate_1", [0.1, 0.2, 0.3, 0.4, 0.5])
for i in l_units:
name = "units_1_%d" % i # generates unique name for each hp.Int object
with hp.conditional_scope("units_0", [i]):
if units_0 == i:
locals()[name] = hp.Int(name, min_value = 8, max_value = i, step = 2, sampling = "log" )
inputs = tf.keras.Input(shape = (self.input_dim,))
x = layers.Dense(units_0, activation="relu")(inputs)
x = layers.Dropout(dropout_0)(x, training=training)
x = layers.Dense(locals()[name], activation="relu")(x)
x = layers.Dropout(dropout_1)(x, training=training)
z = layers.Dense(latent_dim)(x)
self.encoder = tf.keras.Model(inputs, z, name="encoder")
inputs = tf.keras.Input(shape=(latent_dim,))
x = layers.Dense(locals()[name], activation="relu")(inputs)
x = layers.Dropout(dropout_1)(x, training=training)
x = layers.Dense(units_0, activation="relu")(x)
x = layers.Dropout(dropout_0)(x, training=training)
outputs = layers.Dense(self.input_dim, activation="linear")(x)
self.decoder = tf.keras.Model(inputs, outputs, name="decoder")

Problem creating new enemies when player levels up

i'm working on a simple clone of Space Invaders for an University project. The idea is that when the players levels up, the amount of enemies increase, but when i try to do it, the enemies creates infinitly while the stablished condition is true. I can't dettect the problem, so if one of you can help me, i'll apreciate it.
import random
import csv
import operator
import pygame
import time
from pygame import mixer
# Intialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('background.png')
# Sound
mixer.music.load("background.wav")
mixer.music.play(-1)
#Reloj
clock = pygame.time.Clock()
# Caption and Icon
pygame.display.set_caption("Space Invader")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Score
score_value = 0
level_value = 1
level_up_value = ""
font = pygame.font.Font('freesansbold.ttf', 20)
game_over = False
high_scores = []
names = []
with open('high_scores.csv') as csvfile:
reader = csv.reader(csvfile)
sortedlist = sorted(reader, key=operator.itemgetter(1), reverse=True)
for i in sortedlist:
names.append(i[0])
high_scores.append(i[1])
scoreX = 10
scoreY = 10
level_textX = 10
level_textY = 80
levelX = 10
levelY = 40
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
menu_font = pygame.font.Font('freesansbold.ttf', 48)
scores_font = pygame.font.Font('freesansbold.ttf', 45)
#Número de vidas
num_vidas = 3
font = pygame.font.Font('freesansbold.ttf', 32)
vidasX = 650
vidasY = 10
# Player
playerImg = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemyImg = []
bichoImg = []
meteoroImg = []
enemyX = []
enemyY = []
enemyY_change = []
bichoX = []
bichoY = []
bichoY_change = []
meteoroX = []
meteoroY = []
meteoroY_change = []
num_of_enemies_10 = 5
num_of_enemies_20 = 4
num_of_enemies_30 = 3
for i in range(num_of_enemies_10):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyY_change.append(0.5)
for i in range(num_of_enemies_20):
bichoImg.append(pygame.image.load('bicho.png'))
bichoX.append(random.randint(0, 736))
bichoY.append(random.randint(10, 120))
bichoY_change.append(0.5)
for i in range(num_of_enemies_30):
meteoroImg.append(pygame.image.load('meteoro.png'))
meteoroX.append(random.randint(0, 736))
meteoroY.append(random.randint(0, 150))
meteoroY_change.append(0.5)
# Bullet
# Ready - You can't see the bullet on the screen
# Fire - The bullet is currently moving
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (255, 255, 255))
screen.blit(score, (x, y))
def show_level(x, y):
level = font.render("Level: " + str(level_value), True, (255, 255, 255))
screen.blit(level, (x, y))
def level_up_text(x, y):
level_text = font.render(level_up_value, True, (255, 255, 0))
screen.blit(level_text, (level_textX, level_textY))
def show_vidas(x, y):
vidas = font.render("Vidas : " + str(num_vidas), True, (255, 255, 255))
screen.blit(vidas, (x, y))
def game_over_text():
over_text = over_font.render("GAME OVER", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y, i):
screen.blit(enemyImg[i], (x, y))
def bicho(x, y, i):
screen.blit(bichoImg[i], (x, y))
def meteoro(x, y, i):
screen.blit(meteoroImg[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 16, y + 10))
#Colisiones para cada tipo de enemigo
def isCollision1(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
def isCollision2(bichoX, bichoY, bulletX, bulletY):
distance = math.sqrt(math.pow(bichoX - bulletX, 2) + (math.pow(bichoY - bulletY, 2)))
if distance < 27:
return True
else:
return False
def isCollision3(meteoroX, meteoroY, bulletX, bulletY):
distance = math.sqrt(math.pow(meteoroX - bulletX, 2) + (math.pow(meteoroY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# Pause Loop
def show_pause():
paused = True
while paused:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
pause_title = menu_font.render("PAUSED", True, (255, 255, 0))
pauseRect = pause_title.get_rect()
pauseRect.centerx = screen.get_rect().centerx
pauseRect.centery = screen.get_rect().centery - 50
screen.blit(pause_title, pauseRect)
high_title = menu_font.render("HIGH SCORES", True, (255, 255, 255))
highRect = high_title.get_rect()
highRect.centerx = screen.get_rect().centerx
highRect.centery = screen.get_rect().centery + 50
screen.blit(high_title, highRect)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
paused = False
break
if event.type == pygame.MOUSEBUTTONDOWN:
mpos = pygame.mouse.get_pos()
if highRect.collidepoint(mpos):
show_high_scores_menu()
break
pygame.display.update()
# High Scores Loop
def show_high_scores_menu():
high_scores_menu = True
global high_scores, names
high_scores.clear()
names.clear()
with open('high_scores.csv') as csvfile:
reader = csv.reader(csvfile)
sortedlist = sorted(reader, key=operator.itemgetter(1), reverse=True)
for i in sortedlist:
names.append(i[0])
high_scores.append(i[1])
while high_scores_menu:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
high_title = menu_font.render("HIGH SCORES", True, (255, 255, 0))
highRect = high_title.get_rect()
highRect.centerx = screen.get_rect().centerx
highRect.centery = 100
screen.blit(high_title, highRect)
score1 = scores_font.render(names[0] + " : " + str(high_scores[0]), True, (255, 255, 255))
score1Rect = score1.get_rect()
score1Rect.centerx = screen.get_rect().centerx
score1Rect.centery = 250
screen.blit(score1, score1Rect)
score2 = scores_font.render(names[1] + " : " + str(high_scores[1]), True, (255, 255, 255))
score2Rect = score1.get_rect()
score2Rect.centerx = screen.get_rect().centerx
score2Rect.centery = 300
screen.blit(score2, score2Rect)
score3 = scores_font.render(names[2] + " : " + str(high_scores[2]), True, (255, 255, 255))
score3Rect = score3.get_rect()
score3Rect.centerx = screen.get_rect().centerx
score3Rect.centery = 350
screen.blit(score3, score3Rect)
score4 = scores_font.render(names[3] + " : " + str(high_scores[3]), True, (255, 255, 255))
score4Rect = score4.get_rect()
score4Rect.centerx = screen.get_rect().centerx
score4Rect.centery = 400
screen.blit(score4, score4Rect)
score5 = scores_font.render(names[4] + " : " + str(high_scores[4]), True, (255, 255, 255))
score5Rect = score1.get_rect()
score5Rect.centerx = screen.get_rect().centerx
score5Rect.centery = 450
screen.blit(score5, score5Rect)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
high_scores_menu = False
show_pause()
break
pygame.display.update()
def save_high_scores():
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
name = ""
while len(name) < 3:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.unicode.isalpha():
name += event.unicode
elif event.key == pygame.K_BACKSPACE:
name = name[:-1]
name = name.upper()
screen.fill((0, 0, 0))
screen.blit(background, (0, 0))
high_title = menu_font.render("High Score!", True, (255, 255, 0))
highRect = high_title.get_rect()
highRect.centerx = screen.get_rect().centerx
highRect.centery = 100
screen.blit(high_title, highRect)
inpt = font.render("Enter a 3-letter name", True, (255, 255, 255))
inptRect = inpt.get_rect()
inptRect.centerx = screen.get_rect().centerx
inptRect.centery = 200
screen.blit(inpt, inptRect)
namedisplay = menu_font.render(name, True, (255, 255, 255))
namedisplayRect = namedisplay.get_rect()
namedisplayRect.center = screen.get_rect().center
screen.blit(namedisplay, namedisplayRect)
pygame.display.update()
#replace lowest
lowest = high_scores[0]
lowest_index = 0
for i in range(len(high_scores)):
if high_scores[i] <= lowest:
lowest = high_scores[i]
lowest_index = i
high_scores[lowest_index] = score_value
names[lowest_index] = name
with open('high_scores.csv', 'w',newline='') as csvfile:
writer = csv.writer(csvfile)
for i in range(len(names)):
writer.writerow([str(names[i]), str(high_scores[i])])
show_high_scores_menu()
BLACK = (0, 0, 0)
#Agregar imágenes para explosión
explosión_anim = []
for i in range(9):
file = "Explosión/Explosión 0{}.png".format(i)
img = pygame.image.load(file).convert()
img.set_colorkey(BLACK)
img_scale = pygame.transform.scale(img, (70, 70))
explosión_anim.append (img_scale)
def explosión1():
image = explosión_anim[0]
center = image.get_rect()
frame = 0
last_update = pygame.time.get_ticks()
frame_rate = 50 #Velocidad de la explosión
screen.blit(image, (enemyX[i], enemyY[i]))
now = pygame.time.get_ticks()
if now - last_update > frame_rate:
last_update = now
frame += 1
if frame == len(explosión_anim):
kill()
else:
center = rect.center
image = explosión_anim[frame]
rect = image.get_rect()
rect.center = center
def explosión2():
image = explosión_anim[0]
center = image.get_rect()
frame = 0
last_update = pygame.time.get_ticks()
frame_rate = 50 #Velocidad de la explosión
screen.blit(image, (bichoX[i], bichoY[i]))
now = pygame.time.get_ticks()
if now - last_update > frame_rate:
last_update = now
frame += 1
if frame == len(explosión_anim):
kill()
else:
center = rect.center
image = explosión_anim[frame]
rect = image.get_rect()
rect.center = center
def explosión3():
image = explosión_anim[0]
center = image.get_rect()
frame = 0
last_update = pygame.time.get_ticks()
frame_rate = 50 #Velocidad de la explosión
screen.blit(image, (meteoroX[i], meteoroY[i]))
now = pygame.time.get_ticks()
if now - last_update > frame_rate:
last_update = now
frame += 1
if frame == len(explosión_anim):
kill()
else:
center = rect.center
image = explosión_anim[frame]
rect = image.get_rect()
rect.center = center
# Game Loop
en_partida = True
while en_partida:
clock.tick(60)
en_final = False
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
# if player levels up
if score_value < 40:
level_value = 1
elif score_value <= 80:
level_value = 2
elif score_value <= 120:
level_value = 3
elif score_value <= 160:
level_value = 4
if (score_value >= 40 and score_value <= 42):
level_up_value = "LEVEL UP!"
elif (score_value >= 80 and score_value <= 82):
level_up_value = "LEVEL UP!"
elif (score_value >= 120 and score_value <= 122):
level_up_value = "LEVEL UP!"
else:
level_up_value = ""
for event in pygame.event.get():
if event.type == pygame.QUIT:
en_partida = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bulletSound = mixer.Sound("laser.wav")
bulletSound.play()
# Get the current x cordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# 5 = 5 + -0.1 -> 5 = 5 - 0.1
# 5 = 5 + 0.1
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy Movement
for i in range(num_of_enemies_10):
# Game Over
enemyY[i] += enemyY_change[i]
if enemyY[i] > 440:
for j in range(num_of_enemies_10):
enemyY[j] = 2000
game_over_text()
break
for i in range(num_of_enemies_20):
# Game Over
bichoY[i] += bichoY_change[i]
if bichoY[i] > 440:
for j in range(num_of_enemies_20):
bichoY[j] = 2000
game_over_text()
break
for i in range(num_of_enemies_30):
# Game Over
meteoroY[i] += meteoroY_change[i]
if meteoroY[i] > 440:
for j in range(num_of_enemies_30):
meteoroY[j] = 2000
game_over_text()
break
# Collision
collision1 = isCollision1(enemyX[i], enemyY[i], bulletX, bulletY)
collision2 = isCollision2(bichoX[i], bichoY[i], bulletX, bulletY)
collision3 = isCollision3(meteoroX[i], meteoroY[i], bulletX, bulletY)
enemy(enemyX[i], enemyY[i], i)
bicho(bichoX[i], bichoY[i], i)
meteoro(meteoroX[i], meteoroY[i], i)
if collision1:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
explosión1()
bulletY = 480
bullet_state = "ready"
score_value += 10
num_of_enemies_10 -= 1
if collision2:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
explosión2()
bulletY = 480
bullet_state = "ready"
score_value += 20
num_of_enemies_20 -= 1
if collision3:
explosionSound = mixer.Sound("explosion.wav")
explosionSound.play()
explosión3()
bulletY = 480
bullet_state = "ready"
score_value += 30
num_of_enemies_30 -= 1
#Aumento de enemigos por nivel
enemy_created = False
flag = False
if(level_value == 2 and flag == True):
flag = True
enemyX[i] = random.randint(0,736)
enemyY[i] = random.randint(50,150)
enemy(enemyX[i], enemyY[i], i)
enemy_created = True
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state == "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
show_score(scoreX, scoreY)
show_level(levelX, levelY)
level_up_text(levelX + 100, levelY)
show_vidas(vidasX, vidasY)
pygame.display.update()
pygame.quit()
Set the flag before the game loop:
# Game Loop
flag = True # set flag here
en_partida = True
while en_partida:
clock.tick(60)
....................
#Aumento de enemigos por nivel
enemy_created = False
if(level_value == 2 and flag == True): # check flag
flag = False # reset flag
enemyX[i] = random.randint(0,736)
enemyY[i] = random.randint(50,150)
enemy(enemyX[i], enemyY[i], i)
enemy_created = True

U-Net with Pre-Trained ResNet throws dimension error must match

I have an RGB image of mask for Segmentation of dimensions 900x600 (width, height)
My U-Net code is the ff. I do not really want to resize the output too much it is fine if it is resized without losing much of the aspect ratio.
import torch
import torch.nn as nn
from torchvision import models
def convrelu(in_channels, out_channels, kernel, padding):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel, padding=padding),
nn.ReLU(inplace=True)
)
class ResNetUNet(nn.Module):
def __init__(self, n_class=1):
super().__init__()
self.base_model = models.resnet18(pretrained=True)
self.base_layers = list(self.base_model.children())
self.layer0 = nn.Sequential(*self.base_layers[:3]) # size=(N, 64, x.H/2, x.W/2)
self.layer0_1x1 = convrelu(64, 64, 1, 0)
self.layer1 = nn.Sequential(*self.base_layers[3:5]) # size=(N, 64, x.H/4, x.W/4)
self.layer1_1x1 = convrelu(64, 64, 1, 0)
self.layer2 = self.base_layers[5] # size=(N, 128, x.H/8, x.W/8)
self.layer2_1x1 = convrelu(128, 128, 1, 0)
self.layer3 = self.base_layers[6] # size=(N, 256, x.H/16, x.W/16)
self.layer3_1x1 = convrelu(256, 256, 1, 0)
self.layer4 = self.base_layers[7] # size=(N, 512, x.H/32, x.W/32)
self.layer4_1x1 = convrelu(512, 512, 1, 0)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.conv_up3 = convrelu(256 + 512, 512, 3, 1)
self.conv_up2 = convrelu(128 + 512, 256, 3, 1)
self.conv_up1 = convrelu(64 + 256, 256, 3, 1)
self.conv_up0 = convrelu(64 + 256, 128, 3, 1)
self.conv_original_size0 = convrelu(3, 64, 3, 1)
self.conv_original_size1 = convrelu(64, 64, 3, 1)
self.conv_original_size2 = convrelu(64 + 128, 64, 3, 1)
self.conv_last = nn.Conv2d(64, n_class, 1)
def forward(self, input):
x_original = self.conv_original_size0(input)
x_original = self.conv_original_size1(x_original)
layer0 = self.layer0(input)
layer1 = self.layer1(layer0)
layer2 = self.layer2(layer1)
layer3 = self.layer3(layer2)
layer4 = self.layer4(layer3)
layer4 = self.layer4_1x1(layer4)
x = self.upsample(layer4)
layer3 = self.layer3_1x1(layer3)
x = torch.cat([x, layer3], dim=1)
x = self.conv_up3(x)
x = self.upsample(x)
layer2 = self.layer2_1x1(layer2)
x = torch.cat([x, layer2], dim=1)
x = self.conv_up2(x)
x = self.upsample(x)
layer1 = self.layer1_1x1(layer1)
x = torch.cat([x, layer1], dim=1)
x = self.conv_up1(x)
x = self.upsample(x)
layer0 = self.layer0_1x1(layer0)
x = torch.cat([x, layer0], dim=1)
x = self.conv_up0(x)
x = self.upsample(x)
x = torch.cat([x, x_original], dim=1)
x = self.conv_original_size2(x)
out = self.conv_last(x)
return out
for this command
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = ResNetUNet()
model = model.to(device)
# check keras-like model summary using torchsummary
from torchsummary import summary
summary(model, input_size=(3, 600, 900))
it throws the error:
54 x = self.upsample(layer4)
55 layer3 = self.layer3_1x1(layer3)
---> 56 x = torch.cat([x, layer3], dim=1)
57 x = self.conv_up3(x)
58
RuntimeError: Sizes of tensors must match except in dimension 3. Got 57 and 58
Not sure what to do here. Could someone help me how to solve this?
Try this. You just need to match tensor shapes before torch.cat.
import torch
import torch.nn as nn
from torchvision import models
import torch.nn.functional as F
def match_shapes(x, y):
if x.shape[-2:] != y.shape[-2:]:
x = F.interpolate(x, y.shape[-2:], mode='nearest')
return x
def convrelu(in_channels, out_channels, kernel, padding):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel, padding=padding),
nn.ReLU(inplace=True)
)
class ResNetUNet(nn.Module):
def __init__(self, n_class=1):
super().__init__()
self.base_model = models.resnet18(pretrained=True)
self.base_layers = list(self.base_model.children())
self.layer0 = nn.Sequential(*self.base_layers[:3]) # size=(N, 64, x.H/2, x.W/2)
self.layer0_1x1 = convrelu(64, 64, 1, 0)
self.layer1 = nn.Sequential(*self.base_layers[3:5]) # size=(N, 64, x.H/4, x.W/4)
self.layer1_1x1 = convrelu(64, 64, 1, 0)
self.layer2 = self.base_layers[5] # size=(N, 128, x.H/8, x.W/8)
self.layer2_1x1 = convrelu(128, 128, 1, 0)
self.layer3 = self.base_layers[6] # size=(N, 256, x.H/16, x.W/16)
self.layer3_1x1 = convrelu(256, 256, 1, 0)
self.layer4 = self.base_layers[7] # size=(N, 512, x.H/32, x.W/32)
self.layer4_1x1 = convrelu(512, 512, 1, 0)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
self.conv_up3 = convrelu(256 + 512, 512, 3, 1)
self.conv_up2 = convrelu(128 + 512, 256, 3, 1)
self.conv_up1 = convrelu(64 + 256, 256, 3, 1)
self.conv_up0 = convrelu(64 + 256, 128, 3, 1)
self.conv_original_size0 = convrelu(3, 64, 3, 1)
self.conv_original_size1 = convrelu(64, 64, 3, 1)
self.conv_original_size2 = convrelu(64 + 128, 64, 3, 1)
self.conv_last = nn.Conv2d(64, n_class, 1)
def forward(self, input):
x_original = self.conv_original_size0(input)
x_original = self.conv_original_size1(x_original)
layer0 = self.layer0(input)
layer1 = self.layer1(layer0)
layer2 = self.layer2(layer1)
layer3 = self.layer3(layer2)
layer4 = self.layer4(layer3)
layer4 = self.layer4_1x1(layer4)
x = self.upsample(layer4)
layer3 = self.layer3_1x1(layer3)
x = match_shapes(x, layer3)
x = torch.cat([x, layer3], dim=1)
x = self.conv_up3(x)
x = self.upsample(x)
layer2 = self.layer2_1x1(layer2)
x = match_shapes(x, layer2)
x = torch.cat([x, layer2], dim=1)
x = self.conv_up2(x)
x = self.upsample(x)
layer1 = self.layer1_1x1(layer1)
x = match_shapes(x, layer1)
x = torch.cat([x, layer1], dim=1)
x = self.conv_up1(x)
x = self.upsample(x)
layer0 = self.layer0_1x1(layer0)
x = torch.cat([x, layer0], dim=1)
x = self.conv_up0(x)
x = self.upsample(x)
x = torch.cat([x, x_original], dim=1)
x = self.conv_original_size2(x)
out = self.conv_last(x)
return out
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = ResNetUNet()
model = model.to(device)
# check keras-like model summary using torchsummary
from torchsummary import summary
summary(model, input_size=(3, 600, 900))

I want to add a bomb into my flappy bird game, but it won't detect the collision. here is the code

I want to add a bomb into my flappy bird game, but it won't detect the collision.
I cannot get the bird to be detected if it made contact with the bomb
The bomb shows up, but I can't make it detect the collision with the bird, here is the code I have so far.Also,i did not class a new object for the bomb, I put it in with the pipes.
I think there is a problem with the colliderect
If you need the images please tell me.
Can someone help me?
I would be really grateful.
Thanks in advance.
import pygame
from pygame.locals import * # noqa
import sys
import random
class FlappyBird:
def __init__(self):
self.screen = pygame.display.set_mode((400, 708))
self.bird = pygame.Rect(65, 50, 50, 50)
self.background = pygame.image.load("background.png")
self.birdSprites = [pygame.image.load("1.png"),
pygame.image.load("2.png"),
pygame.image.load("dead.png")]
self.wallUp = pygame.image.load("bottom.png")
self.wallDown = pygame.image.load("top.png")
self.bomb = pygame.image.load("bomb.png")
self.bombx = 600
self.gap = 130
self.wallx = 400
self.birdY = 350
self.jump = 0
self.jumpSpeed = 10
self.gravity = 5
self.dead = False
self.sprite = 0
self.counter = 0
self.offset = random.randint(-110, 110)
def updateWalls(self):
self.wallx -= 2
if self.wallx < -80:
self.wallx = 400
self.counter += 1
self.offset = random.randint(-110, 110)
self.bombx -= 2
if self.bombx < -80:
self.bombx = 600
self.counter += 1
self.offset = random.randint(-110, 110)
def birdUpdate(self):
if self.jump:
self.jumpSpeed -= 1
self.birdY -= self.jumpSpeed
self.jump -= 1
else:
self.birdY += self.gravity
self.gravity += 0.2
self.bird[1] = self.birdY
upRect = pygame.Rect(self.wallx,
360 + self.gap - self.offset + 10,
self.wallUp.get_width() - 10,
self.wallUp.get_height())
downRect = pygame.Rect(self.wallx,
0 - self.gap - self.offset - 10,
self.wallDown.get_width() - 10,
self.wallDown.get_height())
bombRect = pygame.Rect(self.bombx,
0 - self.gap - self.offset - 10,
self.bomb.get_width() - 10,
self.bomb.get_height()
)
if upRect.colliderect(self.bird):
self.dead = True
if downRect.colliderect(self.bird):
self.dead = True
if bombRect.colliderect(self.bird):
self.bomb = pygame.image.load("bombexplode")
self.dead = True
if not 0 < self.bird[1] < 720:
self.bird[1] = 50
self.birdY = 50
self.dead = False
self.counter = 0
self.wallx = 400
self.offset = random.randint(-110, 110)
self.gravity = 5
def run(self):
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.SysFont("Arial", 50)
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not self.dead:
self.jump = 17
self.gravity = 5
self.jumpSpeed = 10
self.screen.fill((255, 255, 255))
self.screen.blit(self.background, (0, 0))
self.screen.blit(self.wallUp,
(self.wallx, 360 + self.gap - self.offset))
self.screen.blit(self.wallDown,
(self.wallx, 0 - self.gap - self.offset))
self.screen.blit(self.bomb,
(self.bombx, 0 - self.gap - self.offset))
self.screen.blit(font.render(str(self.counter),
-1,
(255, 255, 255)),
(200, 50))
if self.dead:
self.sprite = 2
elif self.jump:
self.sprite = 1
self.screen.blit(self.birdSprites[self.sprite], (70, self.birdY))
if not self.dead:
self.sprite = 0
self.updateWalls()
self.birdUpdate()
pygame.display.update()
if __name__ == "__main__":
FlappyBird().run()
I don't know much about using sprites, but if you can get the position and size of each object, you can give them rectangular hitboxes and check if their corners are inside each other:
Another way is to use circular hitboxes if those fit better. For these, find the distace between the centers and check if it is smaller than their radius' combined.
Edit :
You can use
self.bird = pygame.Rect(65, 50, 50, 50)
# creating bomb hitbox
self.rect_bomb = pygame.Rect(100, 100, 200, 200)
if self.bird.colliderect(self.rect_bomb):
# end up your code

Pygame Snake food generator

I'm currently in the process of creating a Snake game and I want to create a food generator that generates an apple every 10 seconds based on my in-game timer. The timer counts down from 60 to 0(when the game ends) and I want an new apple to generate every 10 seconds, keeping the old one even if it hasn't been eaten. I don't know how to approach this and could use some help. Here is my full program.
Edit: this is a beginner Computer Science school project so the more basic the better.
import random
import pygame
pygame.init()
#---------------------------------------#
#
# window properties #
width = 640 #
height = 480
game_window=pygame.display.set_mode((width,height))
black = ( 0, 0, 0) #
#---------------------------------------#
# snake's properties
outline=0
body_size = 9
head_size = 10
apple_size = 8
speed_x = 8
speed_y = 8
dir_x = 0
dir_y = -speed_y
segx = [int(width/2.)]*3
segy = [height, height + speed_y, height + 2*speed_y]
segments = len(segx)
apple_counter = 0
grid_step = 8
regular_font = pygame.font.SysFont("Andina",18)
blue = [11, 90, 220]
clock = pygame.time.Clock()
time = 60
fps = 25
time = time + 1.0/fps
text = regular_font.render("Time from start: "+str(int(time)), 1, blue)
text2 = regular_font.render("Score: "+str(int(apple_counter)), 1, blue)
apple_x = random.randrange(0, 640, grid_step)
apple_y = random.randrange(0, 480, grid_step)
apple_colour = (255,0,0)
def redraw_game_window():
game_window.fill(black)
for i in range(segments):
segment_colour = (random.randint(1,50),random.randint(100,150),random.randint(1,50))
head_colour = (random.randint(180,220),random.randint(180,220),random.randint(1,15))
apple_colour = (255,0,0)
pygame.draw.circle(game_window, segment_colour, (segx[i], segy[i]), body_size, outline)
pygame.draw.circle(game_window, head_colour, (segx[0], segy[0]), head_size, outline)
game_window.blit(text, (530, 20))
game_window.blit(text2, (30, 20))
pygame.draw.circle(game_window, apple_colour, (apple_x, apple_y), apple_size, outline)
pygame.display.update()
exit_flag = False
print "Use the arrows and the space bar."
print "Hit ESC to end the program."
########################################################## TIMER/CONTROLS
while exit_flag == False:
redraw_game_window()
clock.tick(fps)
time = time - 1.00/fps
text = regular_font.render("Time: "+str(int(time)), 1, blue)
text2 = regular_font.render("Score: "+str(int(apple_counter)), 1, blue)
if time < 0.1:
print "Game Over"
exit_flag = True
pygame.event.get()
keys = pygame.key.get_pressed()
if time ==
if keys[pygame.K_ESCAPE]:
exit_flag = True
if keys[pygame.K_LEFT] and dir_x != speed_x:
dir_x = -speed_x
dir_y = 0
if keys[pygame.K_RIGHT] and dir_x != -speed_x:
dir_x = speed_x
dir_y = 0
if keys[pygame.K_UP] and dir_y != speed_x:
dir_x = 0
dir_y = -speed_y
if keys[pygame.K_DOWN] and dir_y != -speed_x:
dir_x = 0
dir_y = speed_y
############################################################ SNAKE MOVEMENT
for i in range(segments-1,0,-1):
segx[i]=segx[i-1]
segy[i]=segy[i-1]
segx[0] = segx[0] + dir_x
segy[0] = segy[0] + dir_y
############################################################ COLLISION
for i in range(segments-1, 3, -1):
if segments > 3:
if segx[0] == segx[i] and segy[0] == segy[i]:
print "You have collided into yourself, Game Over."
exit_flag = True
############################################################# BORDERS
if segx[0] > 640 or segx[0] < 0:
print "Game Over, you left the borders."
break
if segy[0] > 480 or segy[0] < 0:
print "Game Over, you left the borders."
break
############################################################# APPLE DETECT
for i in range (0 , 13):
if segx[0] == apple_x + i and segy[0] == apple_y + i:
segments = segments + 1
segx.append(segx[-1])
segy.append(segy[-1])
apple_counter = apple_counter + 1
if segx[0] == apple_x - i and segy[0] == apple_y - i:
segments = segments + 1
segx.append(segx[-1])
segy.append(segy[-1])
apple_counter = apple_counter + 1
#############################################################
pygame.quit()
You either
A) use pygame.time.set_timer to call a function every 10 seconds to spawn food, and every 60 seconds to end the round.
or
B) compare get_ticks()
def new_round():
last_apple = pygame.time.get_ticks() + 10*1000
while true:
now = pygame.time.get_ticks()
if now - last_apple >= 1000:
spawn_apple()
last_apple = now
if now - round_start >= 60*1000:
round_end()