Malfunctioning condition in collision evaluation - python

I'm really a beginner and I'm looking for a mistake.
This is a condition in the Game class in the "collision" method.
I need to detect a collision between a missile and an enemy.
Problem: When a missile is at the same coordinate as the enemy, a collision is detected. However, if one of the shots is outside the X coordinate, another collision is not detected until the shot outside the enemy's X coordinate disappears beyond the top edge of the screen.
import pygame
import os
import sys
import random
from pygame.locals import *
pygame.init()
pygame.font.init()
DIR = os.path.dirname(os.path.realpath(__file__)) # získání cesty k adresáři se soubory
OKNO_X = 1024
OKNO_Y = 768
CLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((OKNO_X, OKNO_Y))
BACKGROUND = pygame.image.load(os.path.join(DIR, "universe.jpg"))
DEBUGFONT = pygame.font.SysFont("Comic Sans MS", 20)
class Spaceship():
def __init__(self, x=510, y=OKNO_Y-50):
self.x = x
self.y = y
def vykresli(self):
ship = pygame.image.load(os.path.join(DIR, "spaceship.png"))
SCREEN.blit(ship, (self.x, self.y))
def pohyb(self, x, y):
self.x += x
self.y += y
if self.x < 0: self.x = 0
if self.x > OKNO_X - 50: self.x = OKNO_X - 54
if self.y < 0: self.y = 0
if self.y > OKNO_Y - 50: self.y = OKNO_Y - 54
class Enemies():
def __init__(self):
self.enem_x = []
self.enem_y = []
self.enem_invader = []
self.enem_speed = []
def vygeneruj(self):
#generování nepřátel
invader_green = pygame.image.load(os.path.join(DIR, "invader_green.png"))
invader_blue = pygame.image.load(os.path.join(DIR, "invader_blue.png"))
invader_yellow = pygame.image.load(os.path.join(DIR, "invader_yellow.png"))
invader_red = pygame.image.load(os.path.join(DIR, "invader_red.png"))
if random.randrange(0, 50) == 1:
#self.enem_x.append(random.randrange(50, 970))
self.enem_x.append(510)
self.enem_y.append(0)
self.enem_invader.append(random.choice([invader_green, invader_blue, invader_yellow, invader_red]))
self.enem_speed.append(random.randrange(1,5))
#self.enem_speed.append(10)
def vykresli(self):
#vykreslení nepřátel
for i in range(len(self.enem_invader)):
SCREEN.blit(self.enem_invader[i], (self.enem_x[i], self.enem_y[i]))
self.enem_y[i] += self.enem_speed[i]
##############DEBUG################x
label_d1 = DEBUGFONT.render(str(self.enem_x[i]), 1, (255,255,255))
SCREEN.blit(label_d1, (self.enem_x[i], self.enem_y[i]-10))
label_d1 = DEBUGFONT.render(str(self.enem_y[i]), 1, (255,255,255))
SCREEN.blit(label_d1, (self.enem_x[i]+30, self.enem_y[i]-10))
#smazání nepřátel, co přeletěly za hranu
e = 0
pocet_enemies = len(self.enem_invader)
while e < pocet_enemies:
if self.enem_y[e] > OKNO_Y:
del self.enem_x[e]
del self.enem_y[e]
del self.enem_invader[e]
del self.enem_speed[e]
pocet_enemies -= 1
e += 1
class Game():
def __init__(self):
self.sestreleno = 0
def kolize(self):
#vyhodnocuje střet střely s enemies
x, y = 0, 0
pocet_enemies = len(enemies.enem_x)
pocet_shots = len(shot.x)
while y < pocet_shots:
while x < pocet_enemies:
if (shot.y[y] - 23 > enemies.enem_y[x] and shot.y[y] - 23 < enemies.enem_y[x] + 50) and (shot.x[y] >= enemies.enem_x[x]-50 and shot.x[y] <= enemies.enem_x[x]+50):
del shot.x[y]
del shot.y[y]
del enemies.enem_x[x]
del enemies.enem_y[x]
del enemies.enem_invader[x]
del enemies.enem_speed[x]
pocet_enemies -= 1
pocet_shots -= 1
self.sestreleno += 1
break
x += 1
y += 1
def skore(self):
myfont_skore = pygame.font.SysFont("Comic Sans MS", 30)
label_skore = myfont_skore.render("Sestřeleno: " + str(self.sestreleno), 1, (100,100,100))
SCREEN.blit(label_skore, (10, 10))
class Shot():
def __init__(self):
self.x = []
self.y = []
self.missile = pygame.image.load(os.path.join(DIR, "missile.png"))
def vystrel(self, x, y):
#přidání střely do seznamu střel
self.x.append(x)
self.y.append(y)
def strela(self):
#vykreslení střely
for m in range(len(self.x)):
SCREEN.blit(self.missile, (self.x[m]+23, self.y[m]-50))
self.y[m] -= 5
##############DEBUG################x
label_d1 = DEBUGFONT.render(str(self.x[m]), 1, (255,255,255))
SCREEN.blit(label_d1, (self.x[m], self.y[m]-10))
label_d1 = DEBUGFONT.render(str(self.y[m]), 1, (255,255,255))
SCREEN.blit(label_d1, (self.x[m]+30, self.y[m]-10))
label_d1 = DEBUGFONT.render(str(m), 1, (255,255,255))
SCREEN.blit(label_d1, (self.x[m]+40, self.y[m]-20))
#smazání střely ze seznamu pokud vletí za hranu screenu
for s in range(len(self.y)):
if self.y[s] <= 0:
del self.x[s]
del self.y[s]
break
#print(self.x)
#instance
spaceship = Spaceship()
enemies = Enemies()
shot = Shot()
game = Game()
while True:
SCREEN.blit(BACKGROUND, (0, 0, OKNO_X, OKNO_Y)) # překreslení pozadí
KEY = pygame.key.get_pressed()
if KEY[pygame.K_LEFT]:
spaceship.pohyb(-10, 0)
if KEY[pygame.K_RIGHT]:
spaceship.pohyb(+10, 0)
if KEY[pygame.K_UP]:
spaceship.pohyb(0, -10)
if KEY[pygame.K_DOWN]:
spaceship.pohyb(0, +10)
if KEY[pygame.K_ESCAPE]:
pygame.quit()
sys.exit()
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
shot.vystrel(spaceship.x, spaceship.y+30)
if event.type == KEYUP:
if event.key == K_p:
pygame.time.wait(5000)
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
spaceship.vykresli()
enemies.vygeneruj()
enemies.vykresli()
shot.strela()
game.kolize()
game.skore()
CLOCK.tick(30) # rychlost FPS
pygame.display.update() # obnovení obrazovky

Instead of a method,
def kolize(self):
#vyhodnocuje střet střely s enemies
x, y = 0, 0
pocet_enemies = len(enemies.enem_x)
pocet_shots = len(shot.x)
while y < pocet_shots:
while x < pocet_enemies:
if (shot.y[y] - 23 > enemies.enem_y[x] and shot.y[y] - 23 < enemies.enem_y[x] + 50) and (shot.x[y] >= enemies.enem_x[x]-50 and shot.x[y] <= enemies.enem_x[x]+50):
del shot.x[y]
del shot.y[y]
del enemies.enem_x[x]
del enemies.enem_y[x]
del enemies.enem_invader[x]
del enemies.enem_speed[x]
pocet_enemies -= 1
pocet_shots -= 1
self.sestreleno += 1
break
x += 1
y += 1
I had to use this method.
def kolize(self):
#vyhodnocuje střet střely s invaderem
myBreak = False
pocet_enemies = len(enemies.enem_x)
pocet_shots = len(shot.x)
for y in range(pocet_shots):
for x in range(pocet_enemies):
if (shot.y[y] - 23 > enemies.enem_y[x] and shot.y[y] - 23 < enemies.enem_y[x] + 50) and (shot.x[y]-23 >= enemies.enem_x[x]-50 and shot.x[y] <= enemies.enem_x[x]+27):
game.explosion(enemies.enem_x[x], enemies.enem_y[x]) # předání souřadnic výbuchu
game.delShots(y)
game.delEnem(x)
pocet_enemies -= 1
pocet_shots -= 1
self.sestreleno += 1
if spaceship.health < 50: spaceship.health += 1
myBreak = True
break
if myBreak == True:
myBreak = False
break
I needed to conditionally jump out of the nested loop and out of the main loop.

Related

Pygame - generating random objects bug

Good evening, my dear stackoverflowers.
I'm creating a game in Pygame. Until now I wasn't really having any problems, but now I would appreciate some help. I'm trying to create function that will automatically generate new level every time I call it (after defeating every enemy in current level to be more specific). For now I'm generating only images that you don't collide with, only to make levels more nice but I will be using the function for generating objects aswell so it's kinda important for me. So the problem is that I need to continuously update the game window obviously but the function will keep generating everything too as you can see in the video bellow. I have no idea how to make level generate only once and make the game to remember all the images generated (theirs x and y positions) and how to keep them displayed until I call the function again when I come to another level. Any ideas?
Here is the video: https://vimeo.com/532903523
Here is the function and everything you need to know for my problem. It may be harder for you to understand because its not in English but translation would be irritaing so I at least translated the most important things in these two functions.
vytvor_level = create_level
sirka_okna = ´width of the game window´
vyska_okna = ´height of the game window´
trava = grass
kytka = flower
aktulizace_okna = ´updating the game window´
okno = window
hrac.animace_hrace = player.player_animation
hrac.animace_dashe = player.dash_animation
def vytvor_level():
for objekt in range(200):
x = random.randint(0, sirka_okna)
y = random.randint(0, vyska_okna)
trava = random.choice(travy)
okno.blit(trava, (x,y))
x = random.randint(0, sirka_okna)
y = random.randint(0, vyska_okna)
kytka = random.choice(kytky)
okno.blit(kytka, (x,y))
def aktulizace_okna():
okno.blit(pozadi, (0,0))
hrac.animace_hrace(okno)
hrac.animace_dashe(okno)
vytvor_level()
py.display.update()
Here is the full code if needed.
import pygame as py
import random
py.init()
sirka_okna = 1000
vyska_okna = 600
okno = py.display.set_mode((sirka_okna, vyska_okna))
py.display.set_caption("Little Hero")
bezi_program = True
# Animace hráče
animaceVpravo = [py.image.load('WR1.png'), py.image.load('WR2.png'), py.image.load('WR3.png'), py.image.load('WR4.png'), py.image.load('WR5.png'), py.image.load('WR6.png')]
animaceVlevo = [py.image.load('WL1.png'), py.image.load('WL2.png'), py.image.load('WL3.png'), py.image.load('WL4.png'), py.image.load('WL5.png'), py.image.load('WL6.png')]
animaceNahoru = [py.image.load('WU1.png'), py.image.load('WU2.png'), py.image.load('WU3.png'), py.image.load('WU4.png'), py.image.load('WU5.png'), py.image.load('WU6.png')]
animaceDolu = [py.image.load('WD1.png'), py.image.load('WD2.png'), py.image.load('WD3.png'), py.image.load('WD4.png'), py.image.load('WD5.png'), py.image.load('WD6.png')]
animaceDash = [py.image.load('DASH1.png'), py.image.load('DASH2.png'), py.image.load('DASH3.png'), py.image.load('DASH4.png'), py.image.load('DASH5.png'), py.image.load('DASH6.png'), py.image.load('DASH7.png')]
animaceStoji = [py.image.load('IDLE1.png'), py.image.load('IDLE2.png'), py.image.load('IDLE3.png'), py.image.load('IDLE4.png'), py.image.load('IDLE5.png'), py.image.load('IDLE6.png')]
# Prostředí
travy = [py.image.load('GRASS1.png'), py.image.load('GRASS2.png'), py.image.load('GRASS3.png'), py.image.load('GRASS4.png'), py.image.load('GRASS5.png'), py.image.load('GRASS6.png')]
kytky = [py.image.load('FLOWERS1.png'), py.image.load('FLOWERS2.png'), py.image.load('FLOWERS3.png'), py.image.load('FLOWERS4.png')]
pozadi = py.image.load('Little_Hero_Pozadi.png')
#------------------------------------------------------
class Hrac:
def __init__(self, x, y, sirka, vyska, rychlost, sila_dashe):
self.x = y
self.y = y
self.sirka = sirka
self.vyska = vyska
self.rychlost = rychlost
self.sila_dashe = sila_dashe
self.jde_vpravo = False
self.jde_vlevo = False
self.jde_nahoru = False
self.jde_dolu = False
self.stoji = True
self.dashuje = False
self.pocet_kroku = 0
self.snimek_dashe = 0
def animace_hrace(self, okno):
if self.pocet_kroku + 1 >= 18:
self.pocet_kroku = 0
if not self.stoji:
if self.jde_vlevo:
okno.blit(animaceVlevo[hrac.pocet_kroku//3], (round(hrac.x),round(hrac.y)))
self.pocet_kroku += 1
elif self.jde_vpravo:
okno.blit(animaceVpravo[hrac.pocet_kroku//3], (round(hrac.x),round(hrac.y)))
self.pocet_kroku += 1
elif hrac.jde_nahoru:
okno.blit(animaceNahoru[hrac.pocet_kroku//3], (round(hrac.x),round(hrac.y)))
self.pocet_kroku += 1
else:
okno.blit(animaceDolu[hrac.pocet_kroku//3], (round(hrac.x),round(hrac.y)))
self.pocet_kroku += 1
else:
okno.blit(animaceStoji[hrac.pocet_kroku//3], (round(hrac.x),round(hrac.y)))
self.pocet_kroku += 1
def animace_dashe(self, okno):
x = self.x + self.sirka
y = self.y + self.vyska * 0.25
if self.snimek_dashe + 1 >= 7:
self.snimek_dashe = 0
if self.dashuje:
self.snimek_dashe += 0.25
okno.blit(animaceDash[int(self.snimek_dashe)], (round(x),round(y)))
def pohyb_hrace(self):
if (klavesa[py.K_a] or klavesa[py.K_LEFT]) and self.x > self.rychlost:
self.jde_vlevo = True
self.jde_vpravo = False
self.jde_nahoru = False
self.jde_dolu = False
self.stoji = False
self.x -= self.rychlost
if (klavesa[py.K_e]) and self.x > self.sila_dashe:
self.dashuje = True
self.x -= self.sila_dashe
if (klavesa[py.K_w] or klavesa[py.K_UP]) and self.y > self.rychlost:
hrac.y -= self.rychlost
if (klavesa[py.K_s] or klavesa[py.K_DOWN]) and self.y > self.rychlost:
hrac.y += self.rychlost
elif (klavesa[py.K_d] or klavesa[py.K_RIGHT]) and self.x < sirka_okna - self.sirka - self.rychlost:
self.jde_vlevo = False
self.jde_vpravo = True
self.jde_nahoru = False
self.jde_dolu = False
self.stoji = False
self.x += self.rychlost
if (klavesa[py.K_e]) and self.x < sirka_okna - self.sila_dashe - self.sirka:
self.dashuje = True
self.x += self.sila_dashe
if (klavesa[py.K_w] or klavesa[py.K_UP]) and self.y > self.rychlost:
hrac.y -= self.rychlost
if (klavesa[py.K_s] or klavesa[py.K_DOWN]) and self.y > self.rychlost:
hrac.y += self.rychlost
elif (klavesa[py.K_w] or klavesa[py.K_UP]) and self.y > self.rychlost:
self.jde_vlevo = False
self.jde_vpravo = False
self.jde_nahoru = True
self.jde_dolu = False
self.stoji = False
self.y -= hrac.rychlost
if (klavesa[py.K_e]) and self.y > self.sila_dashe:
self.dashuje = True
self.y -= self.sila_dashe
elif (klavesa[py.K_s] or klavesa[py.K_DOWN]) and self.y < vyska_okna - self.vyska - self.rychlost:
self.jde_vlevo = False
self.jde_vpravo = False
self.jde_nahoru = False
self.jde_dolu = True
self.stoji = False
self.y += self.rychlost
if (klavesa[py.K_e]) and self.y < vyska_okna - self.sila_dashe - self.sirka:
self.dashuje = True
self.y += self.sila_dashe
else:
self.stoji = True
self.pocet_kroku = 0
self.dashuje = False
self.snimek_dashe = 0
def vytvor_level():
for objekt in range(200):
x = random.randint(0, sirka_okna)
y = random.randint(0, vyska_okna)
trava = random.choice(travy)
okno.blit(trava, (x,y))
x = random.randint(0, sirka_okna)
y = random.randint(0, vyska_okna)
kytka = random.choice(kytky)
okno.blit(kytka, (x,y))
def aktulizace_okna():
okno.blit(pozadi, (0,0))
hrac.animace_hrace(okno)
hrac.animace_dashe(okno)
vytvor_level()
py.display.update()
hrac = Hrac(10, 458, 40, 40, 3, 20)
tik = py.time.Clock()
while bezi_program:
tik.tick(60)
for event in py.event.get():
if event.type == py.QUIT:
bezi_program = False
klavesa = py.key.get_pressed()
hrac.pohyb_hrace()
#if hrac.x < enemy.x + enemy.sirka and hrac.x + hrac.sirka > enemy.x and hrac.y < enemy.y + enemy.vyska and hrac.y + hrac.vyska > enemy.y:
#print("Kolize detekována")
aktulizace_okna()
py.quit()
Ok i managed to do it. I used Pillow to paste all the generated images to my background and then keep displaying that one background.

Python numpy : index 20 is out of bounds for axis 0 with size 20?

I've read other answered questions relating to this topic and they all refer to the nested loops "axis" but in my case, I have used the inbuilt index by just using a single value.
import random, pygame, numpy
#window setup aswell as global variable
pygame.init()
screen_size = 400
global window
window = pygame.display.set_mode((screen_size,screen_size))
pygame.display.set_caption("evolution simulator")
window.fill((255,255,255))
pygame.display.update()
def draw_Window():
global grid
blockSize = 20
# grid = []
for row in range(20):#NO IT ISNT
for column in range(20):
grid = numpy.zeros((20,20))
rect = pygame.Rect(row*blockSize, column*blockSize,blockSize, blockSize)
pygame.draw.rect(window,(0,0,0), rect, 1)
#0 EMPTY
#1 spurgs
#2 FOOD
class spurgs:
def __init__(self,age,hunger,speed,gender,x,y,race):
# 1 for male, 2 for female
self.hunger = hunger
self.speed = speed
self.gender = gender
self.age = age
self.race = race
self.x = x
self.y = y
self.size = 8
self.death = False
def update(self):
if self.death == False:
self.age = self.age + 1
self.draw()
if self.age <= 100:
coin_flip = random.randint(1,2)
if coin_flip == 1:
self.death == True
if grid[self.x,self.y] == 0:
grid[self.x,self.y] = 1
self.sense()
#MATRIX
#SURVIVAL ELEMENTS
def eat(self):
self.hunger +=1
def breed(self,mate):
# In the generation class, make a list for the next generation and append baby to the list
pass
# SENSE
def sense(self):
self.senses = 1
if grid[self.x,self.y] == grid[20,self.y]:
right = False
else:
right = True
if grid[self.x+self.senses,self.y] == 2 and right:#Right
self.move("right")
if grid[self.x,self.y] == grid[0,self.y]:
left = False
else:
left = True
if grid[self.x-self.senses,self.y] == 2 and left:#left
self.move("left")
if grid[self.x,self.y] == grid[self.x,20]:
down = False
else:
down = True
if grid[self.x,self.y-self.senses] ==2 and up:
self.move("down")
if grid[self.x,self.y] == grid[self.x,0]:
up = False
else:
up = True
if grid[self.x,self.senses+self.y] == 2:
self.move("up")
#MOVEMENT
def move(self,dir):
if self.death == False:
if dir == "right":
self.x += self.senses
self.update()
if self.death == False:
if dir == "left":
self.x -= self.senses
self.update()
if self.death == False:
if dir == "up":
self.y += self.senses
self.update()
if self.death == False:
if dir == "down":
self.y -= self.senses
self.update()
#DRAWING
def draw(self):
# x =1 , y =4
#for grid system
if self.death ==False:
#{Pixel Converter}
self.d_x = self.x * 20 - 10
self.d_y = self.y * 20 - 10
pygame.draw.circle(window,self.race,(self.d_x,self.d_y),self.size)
# GENERATION class
class generation:
def __init__(self,size):
self.size = size + 1
self.currentGen = []
def makeGeneration(self):
for i in range(self.size):
self.seed_mutations = random.randint(0,20)
self.x = random.randint(0,20)
self.y = random.randint(0,20)
self.gender = random.randint(1,2)
#Race chooser
race = random.randint (1,4)
if race == 1:
self.color_race = (0, 110, 255)
elif race == 2:
self.color_race = (255, 234, 0)
if race == 3:
self.color_race = (132, 0, 255)
if race == 4:
self.color_race = (242, 53, 53)
self.currentGen.append(spurgs(1,self.seed_mutations,self.seed_mutations,self.gender,self.x,self.y,self.color_race))
def update(self):
for s in self.currentGen:
s.update()
class food:
def __init__(self,type):
self.type = type
if self.type == "m":
self.hunger_val = 2
elif self.type == "a":
self.hunger_val = 1
self.eaten = False
self.x = random.randint(0,20)
self.y = random.randint(0,20)
def draw(self):
if self.eaten == False:
x = self.x * 20 - 10
y = self.y * 20 - 10
if self.type =="m":
pygame.draw.circle(window,(10,255,50),(x,y),self.hunger_val*5)
elif self.type == "a":
pygame.draw.circle(window,(0,0,0),(x,y),self.hunger_val*5)
def update(self):
if self.eaten == False:
self.draw()
if grid[self.x,self.y] == 0:
grid[self.x,self.y] = 2
elif grid[self.x,self.y] == 1:
grid[self.x,self.y] = 1
self.eaten = False
a = food("m")
a.draw()
gen_1 = generation(8)
gen_1.makeGeneration()
run = True
while run:
#WINDOW
window.fill((255,255,255))
draw_Window()
#QUIT CONDITION
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("closing the loop")
run = False
#TESTING
gen_1.update()
a.update()
print("getting here")
#FINAL LOOP
pygame.display.update()
pygame.time.delay(1000)
pygame.quit()
This is the error :
if grid[self.x+self.senses,self.y] == 2 and right:#Right
IndexError: index 21 is out of bounds for axis 0 with size 20
index 20 is out of bounds for axis 0 with size 20?
Yes of course. The indices start at 0. Therefor the indices from 0 to 19 are valid, but 20 is out of bounds.
The last element in the array si addressed with 19 rather than 20:
if grid[self.x,self.y] == grid[20,self.y]:
if grid[self.x,self.y] == grid[19,self.y]:
if grid[self.x,self.y] == grid[self.x,20]:
if grid[self.x,self.y] == grid[self.x,19]:
self.x = random.randint(0,20)
self.x = random.randint(0,19)
Alternatively, you can use random.randrange instead of random.randint:
self.x = random.randrange(20)
To supplement #Rabbid76 's answer:
>>> x = [1, 6, 2, 3, 7, 2, 8, 9, 5, 4]
>>> for idx, val in enumerate(x):
... print(f"index: {idx}, value: {val}")
...
index: 0, value: 1
index: 1, value: 6
index: 2, value: 2
index: 3, value: 3
index: 4, value: 7
index: 5, value: 2
index: 6, value: 8
index: 7, value: 9
index: 8, value: 5
index: 9, value: 4
>>> len(x)
10

TypeError: not supported between instances of 'NoneType' and 'float'

I am doing flappyBird game with neat from Tech with Tim tutorial and I created self.type inside Bird Class which means that bird is controllable by keyboard input or neat class, but I am getting this error after finish last generation:
C:/Users/papadi166/Documents/MEGAsync/AppDev/FlappyBird/main.py:185: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
new_rect = rotated_image.get_rect(center = image.get_rect(topleft = topleft).center)
Traceback (most recent call last):
File "C:/Users/papadi166/Documents/MEGAsync/AppDev/FlappyBird/main.py", line 393, in <module>
run(config_path, genome_path="dict.pickle")
File "C:/Users/papadi166/Documents/MEGAsync/AppDev/FlappyBird/main.py", line 364, in run
winner = p.run(main, 2)
File "C:\Users\papadi166\PycharmProjects\FlappyBird\venv\lib\site-packages\neat\population.py", line 99, in run
if best is None or g.fitness > best.fitness:
TypeError: '>' not supported between instances of 'NoneType' and 'float'
Process finished with exit code 1
before i added this code to population.py:
self.population = fitness_function(list(iteritems(self.population)), self.config)
self.species.species[1].members = self.population
I got this error after finish one generation:
if best is None or g.fitness > best.fitness:
TypeError: '>' not supported between instances of 'NoneType' and 'float'
I understand that there is something wrong with loaded winner object, but I dont' know how to fix that in my code..
class Bird:
IMGS = BIRD_IMGS
P_IMGS = PLAYER_BIRD_IMGS
MAX_ROTATION = 25
ROT_VEL = 20
ANIMATION_TIME = 5
def __init__(self, x, y, t):
self.x = x
self.y = y
self.tilt = 0
self.tick_count = 0
self.vel = 0
self.height = self.y
self.img_count = 0
self.p_img = self.P_IMGS[0]
self.img = self.IMGS[0]
self.type = t
def jump(self):
self.vel = -10.5
self.tick_count = 0
self.height = self.y
def move(self):
self.tick_count +=1
d = self.vel * (self.tick_count) + 0.5 * (3) * (self.tick_count)**2
if d >= 16:
d = (d/abs(d)) * 16
if d < 0:
d -= 2
self.y = self.y + d
if d < 0 or self.y < self.height + 50:
if self.tilt < self.MAX_ROTATION:
self.tilt = self.MAX_ROTATION
else:
if self.tilt > -90:
self.tilt -= self.ROT_VEL
def draw(self, win):
self.img_count += 1
if self.type == 0:
if self.img_count < self.ANIMATION_TIME:
self.img = self.IMGS[0]
elif self.img_count < self.ANIMATION_TIME*2:
self.img = self.IMGS[1]
elif self.img_count < self.ANIMATION_TIME*3:
self.img = self.IMGS[2]
elif self.img_count < self.ANIMATION_TIME*4:
self.img = self.IMGS[1]
elif self.img_count < self.ANIMATION_TIME*4 + 1:
self.img = self.IMGS[0]
self.img_count = 0
if self.tilt <= -80:
self.img = self.IMGS[1]
self.img_count = self.ANIMATION_TIME*2
blitRotateCenter(win, self.img, (self.x, self.y), self.tilt)
if self.type == 1:
if self.img_count < self.ANIMATION_TIME:
self.img = self.P_IMGS[0]
elif self.img_count < self.ANIMATION_TIME * 2:
self.img = self.P_IMGS[1]
elif self.img_count < self.ANIMATION_TIME * 3:
self.img = self.P_IMGS[2]
elif self.img_count < self.ANIMATION_TIME * 4:
self.img = self.P_IMGS[1]
elif self.img_count < self.ANIMATION_TIME * 4 + 1:
self.img = self.P_IMGS[0]
self.img_count = 0
if self.tilt <= -80:
self.img = self.P_IMGS[1]
self.img_count = self.ANIMATION_TIME * 2
blitRotateCenter(win, self.p_img, (self.x, self.y), self.tilt)
def get_mask(self):
if self.type == 0:
return pygame.mask.from_surface(self.img)
elif self.type == 1:
return pygame.mask.from_surface(self.p_img)
def main(genomes, config):
"""
We need to keep track of neural network that controls each bird, because these genomes when they come in
are really just a bunch of neural networks that are gonna control each of our birds, I need to keep track of the bird
that that neural networks controlling so where that position is in the screen and I need to keep track of our genomes so
that I actually change their fitness based on you know for they move or if they hit a pipe or if they do all this stuff
so i do three lists to do this maybe not the most efficient way but should work fine
"""
global GEN
GEN += 1
nets = []
birds = []
ge = []
# Change bird = Bird(230, 350) to
x = 0
for _, g in genomes:
if (x < len(genomes) -1) :
net = neat.nn.FeedForwardNetwork.create(g, config)
nets.append(net)
birds.append(Bird(230, 350, 0))
g.fitness = 0
ge.append(g)
x += 1
if (x == len(genomes) -1):
net = neat.nn.FeedForwardNetwork.create(g, config)
nets.append(net)
birds.append(Bird(230, 350, 1))
g.fitness = 0
ge.append(g)
x += 1
base = Base(730)
pipes = [Pipe(600)]
win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
run = True
clock = pygame.time.Clock()
score = 0
while run:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
for bird in birds:
if bird.type == 1:
bird.jump()
pipe_ind = 0
if len(birds) > 0:
if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():
pipe_ind = 1
else:
run = False
break
for x, bird in enumerate(birds):
bird.move()
ge[x].fitness += 0.1
output = nets[x].activate((bird.y, abs(bird.y - pipes[pipe_ind].height), abs(bird.y - pipes[pipe_ind].bottom)))
if output[0] > 0.5:
if bird.type != 1:
bird.jump()
#bird.move()
add_pipe = False
rem = []
for pipe in pipes:
for x, bird in enumerate(birds):
# indent only this collision if becouse the rest of code don't have to be running at this for loop.
if pipe.collide(bird):
ge[x].fitness -= 1 # Every time a bird hits a pipe is gonna have one removed from its fitness score
birds.pop(x)
nets.pop(x)
ge.pop(x)
#Change bird.x to birds[0]... OR NOT.. better put that function into this for loop, because mian will runs 50 times so caling birds[0] 50 times isn't.. IDK. Efficient?
if not pipe.passed and pipe.x < bird.x:
pipe.passed = True
add_pipe = True
if pipe.x + pipe.PIPE_TOP.get_width() < 0:
rem.append(pipe)
pipe.move()
if add_pipe:
score += 1
for g in ge:
g.fitness += 5
pipes.append(Pipe(700))
for r in rem:
pipes.remove(r)
for x, bird in enumerate(birds):
if bird.y + bird.img.get_height() >= 730 or bird.y < 0:
birds.pop(x)
nets.pop(x)
ge.pop(x)
base.move()
draw_window(win, birds, pipes, base, score, GEN)
if score >= 50:
for x, bird in enumerate(birds):
# indent only this collision if becouse the rest of code don't have to be running at this for loop.
ge[x].fitness -= 1 # Every time a bird hits a pipe is gonna have one removed from its fitness score
birds.pop(x)
nets.pop(x)
ge.pop(x)
def run(config_path, genome_path="dict.pickle"):
import pickle
genomes = []
# Load the configuration
config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path)
# Setup population
p = neat.Population(config)
#Set the output that we gonna see
p.add_reporter(neat.StdOutReporter(True))
stats = neat.StatisticsReporter()
p.add_reporter(stats)
# Set the fitness funnction ( This func. runs main func. 50 times and pass it all of the genoms so like that population current generation populations )
winner = p.run(main, 2)
with open("dict.pickle", "wb") as infile:
pickle.dump(winner, infile)
infile.close()
# Unpickle saved winner
with open(genome_path, "rb") as infile:
genome = pickle.load(infile)
# Convert loaded genome into required data structure
genomes = [(1, genome)]
type = "test"
# Call game with only the loaded genome
main(genomes, config)
print("LOL")
if __name__ == '__main__':
local_dir = os.path.dirname(__file__)
config_path = os.path.join(local_dir, "config-feedforward.txt")
run(config_path, genome_path="dict.pickle")
For me, Declaring ge[x].fitness in a for loop before worked.
# put this above the other for loops
for x, bird in enumerate(birds):
ge[x].fitness = 0

How do I add a score tracker?

So I want it to count the score every time the snake eats a candy.
I haven't tried much, but I tried to find existing codes and adding them to mine but that just broke the game. I also tried to make my own score board by watching a tutorial, but I don't know where the code should go like at the beginning or end.
import pygame
import random
score = 0
welcome = ("Welcome to our snake game")
print(welcome)
class cube:
height = 20
w = 500
def __init__(movee,start,x=1,y=0,color=(0,0,0)):
movee.pos = start
movee.x = 1
movee.y = 0
movee.color = color
def move(movee, x, y):
movee.x = x
movee.y = y
movee.pos = (movee.pos[0] + movee.x, movee.pos[1] + movee.y)
def draw(movee, surface, eyes=False):
leng = movee.w // movee.height
i = movee.pos[0]
j = movee.pos[1]
pygame.draw.rect(surface, movee.color, (i*leng+1,j*leng+1, leng-2, leng-2))
class snake:
body = []
turns = {}
def __init__(movee, color, pos):
movee.color = color
movee.head = cube(pos)
movee.body.append(movee.head)
def move(movee):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed()
for key in keys:
if keys[pygame.K_LEFT]:
movee.x = -1
movee.y = 0
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_RIGHT]:
movee.x = 1
movee.y = 0
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_UP]:
movee.x = 0
movee.y = -1
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
elif keys[pygame.K_DOWN]:
movee.x = 0
movee.y = 1
movee.turns[movee.head.pos[:]] = [movee.x, movee.y]
for i, c in enumerate(movee.body):
p = c.pos[:]
if p in movee.turns:
turn = movee.turns[p]
c.move(turn[0],turn[1])
if i == len(movee.body)-1:
movee.turns.pop(p)
else:
if c.x == -1 and c.pos[0] <= 0: c.pos = (c.height-1, c.pos[1])
elif c.x == 1 and c.pos[0] >= c.height-1: c.pos = (0,c.pos[1])
elif c.y == 1 and c.pos[1] >= c.height-1: c.pos = (c.pos[0], 0)
elif c.y == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.height-1)
else: c.move(c.x,c.y)
def add(movee):
tail = movee.body[-1]
dx, dy = tail.x, tail.y
if dx == 1 and dy == 0:
movee.body.append(cube((tail.pos[0]-1,tail.pos[1])))
elif dx == -1 and dy == 0:
movee.body.append(cube((tail.pos[0]+1,tail.pos[1])))
elif dx == 0 and dy == 1:
movee.body.append(cube((tail.pos[0],tail.pos[1]-1)))
elif dx == 0 and dy == -1:
movee.body.append(cube((tail.pos[0],tail.pos[1]+1)))
movee.body[-1].x = dx
movee.body[-1].y = dy
def draw(movee, surface):
for i, c in enumerate(movee.body):
if i ==0:
c.draw(surface, True)
else:
c.draw(surface)
def drawingAGrid(w, height, surface):
sizein = w // height
x = 0
y = 0
for l in range(height):
x = x + sizein
y = y + sizein
def redrawGrid(surface):
global height, width, s, snack
surface.fill((255,255,255))
s.draw(surface)
snack.draw(surface)
drawingAGrid(width, height, surface)
pygame.display.update()
def Candy(height, item):
positions = item.body
while True:
x = random.randrange(height)
y = random.randrange(height)
if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:
continue
else:
break
return (x,y)
def gameloop():
global width, height, s, snack, x_pos, y_pos, reset
width = 500
height = 20
win = pygame.display.set_mode((width, width))
s = snake((255, 0, 0), (10, 10))
snack = cube(Candy(height, s), color=(0, 0, 0))
flag = True
clock = pygame.time.Clock()
x_pos, y_pos = s.body[0].pos
while flag:
pygame.time.delay(50)
clock.tick(7)
s.move()
x, y = s.body[0].pos
if not -1 <= x - x_pos <= 1 or not -1 <= y - y_pos <= 1:
movee.reset((10,10))
x_pos, y_pos = s.body[0].pos
if s.body[0].pos == snack.pos:
s.add()
snack = cube(Candy(height, s), color=(0, 0, 0))
redrawGrid(win)
gameloop()
I just want like a scoreboard in any of the corners counting the score.
Use pygame.freetype to render text. e,g, crated a pygame.freetype.SysFont object:
import pygame.freetype
pygame.init()
font = pygame.freetype.SysFont('Times New Roman', 30)
The score is the number of body parts. Use str to convert a number to a text and .render() to render a text to a pygame.Surface object:
score = len(s.body)
text_surf, text_rect = font.render(str(score), (255, 0, 0), size=30)
Define a margin to the border of the window, calculate the text position (e.g. bottom right) and .blit the text to the window surfrace:
margin = 10
text_pos = (width - text_rect.width - margin, width - text_rect.height - margin)
surface.blit(text_surf, text_pos)
Function redrawGrid:
def redrawGrid(surface):
global height, width, s, snack
surface.fill((255,255,255))
s.draw(surface)
snack.draw(surface)
drawingAGrid(width, height, surface)
score = len(s.body)
text_surf, text_rect = font.render(str(score), (255, 0, 0), size=30)
margin = 10
text_pos = (width - text_rect.width - margin, width - text_rect.height - margin)
surface.blit(text_surf, text_pos)
pygame.display.update()

Broken calling function in Python

When I was programing a basic UFO game in python 2.7 and with pygame I came accross an error, However it didn't come up in the consol. What happend was:
I was programing
Made a little change in the code
The Menu Screen worked fine and I go to play the game
It then keeps restarting.
I edited a few more bits of code so it'd be in a while loop until it would call a command correctly.
And It still wouldent call the command.
If you want to have the Images you can download them and the Sorcecode here:
http://dl.dropbox.com/u/33487921/A%20Problem.zip
Here is the code:
import sys, pygame, random
from pygame.locals import *
from time import gmtime, strftime
pygame.init()
width = int(500*2)
height = int(300*2)
width2 = width + (width/5)
height2 = height + ((height/3)/2)
screen = pygame.display.set_mode((width, height2))
pygame.display.set_caption("MoeTM's UFO Game")
class FlyingObject():
def Restart(self):
self.amount = 0
self.array = []
def New(self, FPS):
self.amount += 1
for i in range(self.amount):
if i == self.amount-1:
self.array.append([])
Strength = random.randrange(1, 101, 1)
if Strength in range(1, 51, 1):
Type = 1
if Strength in range(51, 76, 1):
Type = 2
if Strength in range(76, 88, 1):
Type = 3
if Strength in range(88, 94, 1):
Type = 4
if Strength in range(94, 101, 1):
Type = 5
X = random.randrange(0,1,1)
if X == 0:
XMove = random.randrange(1,6,1)
if X == 1:
XMove = random.randrange(1,6,1)
XMove /= 5.0
Y = random.randrange(0,2,1)
if Y == 0:
YMove = random.randrange(1,6,1)
if Y == 1:
YMove = random.randrange(1,6,1)
YMove /= 5.0
XMove *= 10
YMove *= 10
XMove *= FPS
YMove *= FPS
TLBR = random.randrange(0,4,1)
if TLBR == 0:#top
XIntercept = random.randrange(0,width+1,1)
YIntercept = -5
if TLBR == 1:#left
XIntercept = -5
YIntercept = random.randrange(0,height+1,1)
if TLBR == 2:#bottom
XIntercept = random.randrange(0,width+1,1)
YIntercept = height + 5
if TLBR == 3:#right
XIntercept = width + 5
YIntercept = random.randrange(0,height+1,1)
if XIntercept in range((width/4)*3,width+1,1):
XMove = -XMove
if YIntercept in range((height/4)*3,height+1,1):
YMove = -YMove
if XIntercept in range((width/4),(width/4)*3, 1):
chance = random.randrange(0,2,1)
if chance == 1:
XMove=-XMove
if YIntercept in range((height/4),(height/4)*3, 1):
chance = random.randrange(0,2,1)
if chance == 1:
YMove=-YMove
if XMove < 1 and YMove >= 1:
XMove *= 3
YMove *= 3
if YMove < 1 and XMove >= 1:
XMove *= 3
YMove *= 3
if YMove < 1 and XMove <1:
XMove *= 3
YMove *= 3
self.array[i] = [XMove,YMove,XIntercept,YIntercept,False,False, Type, "image"]
def Move(self, PX, PY, IX, IY):
for i in range(self.amount):
self.array.append([])
if self.array[i][2] > width +10 or self.array[i][2] < -10:
self.array[i][4] = False
self.array[i][5] = True
if self.array[i][3] > height +10 or self.array[i][3] < -10:
self.array[i][4] = False
self.array[i][5] = True
Check = True
if self.array[i][4] == False and self.array[i][5] == True:
Check = False
if Check == True:
self.array[i][2] += self.array[i][0]#XIntercept+=XMove
self.array[i][3] += self.array[i][1]#YIntercept+=Ymove
if self.array[i][2] in range(0,width+1,1) and self.array[i][3] in range(0,height+1,1):
self.array[i][4] = True
self.array[i][5] = True
else:
self.array[i][4] = False
if int(self.array[i][2]+5) in range(PX, PX+IX, 1) and int(self.array[i][3]+5) in range(PY, PY+IY, 1):
self.colide(self.array[i][6])
self.array[i][4] = False
self.array[i][5] = True
def Blit(self):
for i in range(self.amount):
self.array.append([])
Check = True
if self.array[i][4] == False and self.array[i][5] == True:
Check = False
if Check == True:
screen.blit(self.array[i][7], (int(self.array[i][2]), int(self.array[i][3])))
class Bullits(FlyingObject):
def colide(self, damage=1):
Play.Game.Player.Hit(damage)
def Convert(self):
for i in range(self.amount):
self.array.append([])
self.array[i][7]=self.Image = pygame.image.load("images\Bullit"+str(self.array[i][6])+".png")
class Orbs(FlyingObject):
def colide(self, ammount=1):
Play.Game.Player.GotPoint(ammount)
def Convert(self):
for i in range(self.amount):
self.array.append([])
self.array[i][7]=self.Image = pygame.image.load("images\Orb"+str(self.array[i][6])+".png")
class UFO():
def __init__(self):
self.health = 10
self.maxhealth = 50
self.startinghealth = 10
self.maxspeed = 20
self.Image = pygame.image.load("images\UFO.png")
self.Heart0 = pygame.transform.scale(pygame.image.load("images\Heart0.png"), (width/50,height/30))
self.Heart1 = pygame.transform.scale(pygame.image.load("images\Heart1.png"), (width/50,height/30))
self.Heart2 = pygame.transform.scale(pygame.image.load("images\Heart2.png"), (width/50,height/30))
self.Heart3 = pygame.transform.scale(pygame.image.load("images\Heart3.png"), (width/50,height/30))
self.Heart4 = pygame.transform.scale(pygame.image.load("images\Heart4.png"), (width/50,height/30))
self.Heart5 =pygame.transform.scale( pygame.image.load("images\Heart5.png"), (width/50,height/30))
self.ix = 100
self.iy = 40
self.points = 0
self.collection = 0
self.x = (width-self.ix)/2
self.y = (height-self.iy)/2
self.HeartCol= []
self.DA = "New"
for i in range(0,10,1):
self.HeartCol.append([])
dif = int((width/2.5)/10)
higt = int(((height2-height)/2)+height)
self.HeartCol[i] = [dif*i, higt]
def New(self):
print "Starting"
self.health = self.startinghealth
self.x = (width-self.ix)/2
self.y = (height-self.iy)/2
self.DA = "Alive"
print Alive
def Hit(self, damage=1):
self.health -= damage
if self.health <= 0:
self.DA = "Dead"
def GotPoint(self, amount=1):
self.points += amount
if self.points >= 10:
self.points -= 10
self.collection += 1
self.health += 1
if self.health >= self.maxhealth:
self.health = self.maxhealth
def Move(self,mx,my):
if mx >= width - (self.ix/2):
mx = width - self.ix
elif mx <= self.ix/2:
mx = 0
else:
mx = mx - (self.ix/2)
if my >= height - (self.iy/2):
my = height - self.iy
elif my <= self.iy/2:
my = 0
else:
my = my - (self.iy/2)
if mx > self.x:
if mx-self.x > self.maxspeed:
self.x += self.maxspeed
else:
self.x = mx
if mx < self.x:
if self.x-mx > self.maxspeed:
self.x -= self.maxspeed
else:
self.x = mx
if my > self.y:
if my-self.y > self.maxspeed:
self.y += self.maxspeed
else:
self.y = my
if my < self.y:
if self.y-my > self.maxspeed:
self.y -= self.maxspeed
else:
self.y = my
def Blit(self):
screen.blit(self.Image, (self.x, self.y))
def ForBlit(self):
return self.x, self.y, self. ix, self.iy
def Toolbar(self):
pygame.draw.rect(screen, [127,127,127], pygame.Rect(0, height, width, height2))
for i in range(0,10,1):
if self.health >= 41+i:
screen.blit(self.Heart5, (self.HeartCol[i][0], self.HeartCol[i][1]))
elif self.health >= 31+i:
screen.blit(self.Heart4, (self.HeartCol[i][0], self.HeartCol[i][1]))
elif self.health >= 21+i:
screen.blit(self.Heart3, (self.HeartCol[i][0], self.HeartCol[i][1]))
elif self.health >= 11+i:
screen.blit(self.Heart2, (self.HeartCol[i][0], self.HeartCol[i][1]))
elif self.health >= 1+i:
screen.blit(self.Heart1, (self.HeartCol[i][0], self.HeartCol[i][1]))
else:
screen.blit(self.Heart0, (self.HeartCol[i][0], self.HeartCol[i][1]))
def DOA(self):
return self.DA
def New(self):
pass
class Background():
def __init__(self):
self.sr = 5
self.bg = [0,0,0]
def New(self):
self.amountOfStars = random.randrange(10,51,1)
self.stars=[]
for i in range(self.amountOfStars):
x = random.randrange(self.sr*2,width-(self.sr*2)+1,1)
y = random.randrange(self.sr*2,height-(self.sr*2)+1,1)
coulerr = random.randrange(200,256,1)
coulerg = random.randrange(200,256,1)
coulerb = random.randrange(0,56,1)
size = random.randrange(5, 10, 1)
self.stars.append([])
self.stars[i] = [[x,y],[coulerr,coulerg,coulerb],size]
def Blit(self):
screen.fill(self.bg)
for i in range(self.amountOfStars):
self.stars.append([])
pygame.draw.circle(screen,self.stars[i][1],self.stars[i][0],self.stars[i][2])
class Text():
def Text(self, Text, TextSize, Couler):
self.Couler = Couler
self.TextSize = int(TextSize)
self.Text = str(Text)
self.font = pygame.font.Font(None, self.TextSize)
self.text = self.font.render(self.Text, 1, self.Couler)
self.Size = self.text.get_rect()
self.ctext = self.text
self.cCouler = self.Couler
def Position(self, X, Y):
self.X = X
self.Y = Y
self.Position = self.X,self.Y
def Blit(self):
screen.blit(self.ctext, [self.X,self.Y])
def IsItClicked(self, MouseX, MouseY):
if MouseX in range(self.X,self.X+self.Size[2]+1,1) and MouseY in range(self.Y,self.Y+self.Size[3]+1,1):
return True
else:
return False
def Hover(self, MouseX=0, MouseY=0, couler=-1):
if couler == -1:
couler = self.Couler
hover = self.IsItClicked(MouseX, MouseY)
if hover == True:
self.cCouler = couler
self.ctext = self.font.render(self.Text, 1, self.cCouler)
else:
self.cCouler = self.Couler
self.ctext = self.font.render(self.Text, 1, self.cCouler)
class Menu():
def __init__(self):
self.Move = (height2/4)/2
self.move = self.Move*2
self.Menu = Text()
self.Menu.Text("MoeTM's UFO Game", 50, [255,255,0])
self.Menu.Position((width - self.Menu.Size[2])/2,self.Menu.Size[0])
self.Play = Text()
self.Play.Text("Play The Game!", 30, [255,255,0])
self.Play.Position(self.Play.Size[0]+20,self.Play.Size[0]+self.Move)
self.Shop = Text()
self.Shop.Text("Enter the Shop, Why?", 30, [255,255,0])
self.Shop.Position(self.Shop.Size[0]+20,self.Shop.Size[0]+self.move*2-self.Move)
self.Saves = Text()
self.Saves.Text("Save the game, ;P", 30, [255,255,0])
self.Saves.Position(self.Saves.Size[0]+20,self.Saves.Size[0]+self.move*3-self.Move)
self.Options = Text()
self.Options.Text("Options...", 30, [255,255,0])
self.Options.Position(self.Options.Size[0]+20,self.Options.Size[0]+self.move*4-self.Move)
self.Area = "Menu"
def Blit(self, MouseX=0, MouseY=0):
if self.Area == "Menu":
self.Play.Hover(MouseX, MouseY, [192,255,0])
self.Shop.Hover(MouseX, MouseY, [192,255,0])
self.Saves.Hover(MouseX, MouseY, [192,255,0])
self.Options.Hover(MouseX, MouseY, [192,255,0])
self.Play.Blit()
self.Shop.Blit()
self.Saves.Blit()
self.Options.Blit()
if self.Area == "Shop":
pass
if self.Area == "Saves":
pass
if self.Area == "Options":
pass
if self.Area != "Play":
self.Menu.Hover(MouseX, MouseY, [192,255,0])
self.Menu.Blit()
def IsClicked(self, MouseX, MouseY):
if self.Area == "Menu":
play = self.Play.IsItClicked(MouseX, MouseY)
if play == True:
self.Area = "Play"
Shop = self.Shop.IsItClicked(MouseX, MouseY)
if Shop == True:
self.Area = "Shop"
Saves = self.Saves.IsItClicked(MouseX, MouseY)
if Saves == True:
self.Area = "Saves"
Options = self.Options.IsItClicked(MouseX, MouseY)
if Options == True:
self.Area = "Options"
menu = self.Menu.IsItClicked(MouseX, MouseY)
if menu == True:
self.Area = "Menu"
def getArea(self):
return self.Area
class Game():
def __init__(self):
self.Player = UFO()
self.Background = Background()
self.Orbs = Orbs()
self.Bullits = Bullits()
self.Death = pygame.image.load("images\Death.png")
self.Death = pygame.transform.scale(self.Death, (width2, height2))
self.death = 0
def New(self):
while True:
self.Player.New()
Place = self.Player.DOA()
if Place != "New":
self.TotalTime = 0
self.Background.New()
self.Bullits.Restart()
self.Orbs.Restart()
def Blit(self):
self.Bullits.Convert()
self.Orbs.Convert()
self.Background.Blit()
self.Bullits.Blit()
self.Orbs.Blit()
self.Player.Blit()
def Move(self, MX, MY):
self.Player.Move(MX, MY)
PX, PY, IX, IY = self.Player.ForBlit()
self.Bullits.Move(PX, PY, IX, IY)
self.Orbs.Move(PX, PY, IX, IY)
def Updater(self, time):
self.TotalTime += time
def Death(self):
if self.death >= 1: return 0
self.death += 1
time = float(self.TotalTime) * 10
time = int(time)
time /= 10.0
time = str(time)
self.DeadText = Text()
text = "You died in "+time+" seconds"
self.DeadText.Text(text,50,[0,0,0])
self.DeadText.Position((width-self.DeadText.Size[2])/2,(height2-self.DeadText.Size[3])/2)
def DeadBlit(self):
screen.blit(self.Death, (0, 0))
self.DeadText.Blit()
class Main():
def __init__(self):
self.Game = Game()
self.Menu = Menu()
self.DA= ""
self.seconds = 0
self.clock = pygame.time.Clock()
self.FPS = 0.1
self.QUIT = False
self.Place = ["","New"]
self.difficalty1 = 10
self.difficalty2 = 5
def Main(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.QUIT = True
if event.type == KEYDOWN:
if event.key == K_p:
time = strftime("%a, %d %b %Y %H:%M:%S", gmtime())
pygame.image.save(screen, time+".png")
#if event.key == K_DOWN:
#if event.key == K_UP:
if event.type == MOUSEBUTTONDOWN:
self.Menu.IsClicked(MouseX, MouseY)
if self.QUIT == True:
pygame.quit()
break
self.seconds += self.clock.tick()/1000.0
if self.seconds >= self.FPS:
MouseX,MouseY = pygame.mouse.get_pos()
self.Place[0] = self.Menu.getArea()
if self.Place[0] == "Play" and self.Place[1] == "New":
self.Game.New()
screen.fill([0,0,0])
if self.Place[0] != "Play":
self.Menu.Blit(MouseX, MouseY)
if self.Place[0] == "Play":
if self.Place[1] != "Dead":
self.Game.Move(MouseX,MouseY)
self.Game.Updater(self.seconds)
randomChance = random.randrange(0,self.difficalty1,1)
if randomChance in range(0, self.difficalty2, 1):
self.Game.Orbs.New(self.FPS)
randomChance = random.randrange(0,self.difficalty1,1)
if randomChance in range(0, self.difficalty2, 1):
self.Game.Bullits.New(self.FPS)
self.Game.Blit()
self.Place[1] = self.Game.Player.DOA()
if self.Place[1] == "Dead":
self.Game.Death()
self.Game.DeadBlit()
pygame.display.flip()
self.seconds -= self.FPS
Play = Main()
Play.Main()
pygame.quit()
here is the two bits of code that have broke. (I put the class abouve the def's so you know what class there in)
class UFO():
def New(self):
print "Starting"
self.health = self.startinghealth
self.x = (width-self.ix)/2
self.y = (height-self.iy)/2
self.DA = "Alive"
print Alive
class Game():
def New(self):
while True:
self.Player.New()
Place = self.Player.DOA()
if Place != "New":
self.TotalTime = 0
self.Background.New()
self.Bullits.Restart()
self.Orbs.Restart()
if you use the code in IDLE then you will know that it dousent even call self.Player.New() because the Shell dousn't print "Starting" or give an error for me putting print Alive, it just continuosly loops the while loop.
Sorry for the Miles of code, :( But Hopefully it helps, mostly because without some of it you wouldent understand it. Also Thankyou for taking the time to read and try to answer this. And Sorry for all the grammer and spalling mistakes, I can't spell.
Your issues is the While True in your Game.New method, also i have found other issues that make the game to not run.
Below is the diff with the fixed code:
--- ../A Problem-1/Game.pyw 2012-01-25 13:32:00.000000000 -0300
+++ Game.pyw 2012-01-25 11:55:56.000000000 -0300
## -11,6 +11,9 ##
pygame.display.set_caption("MoeTM's UFO Game")
class FlyingObject():
+ def __init__(self):
+ self.amount = 0
+ self.array = []
def Restart(self):
self.amount = 0
self.array = []
## -233,6 +236,7 ##
def __init__(self):
self.sr = 5
self.bg = [0,0,0]
+ self.amountOfStars = 0
def New(self):
self.amountOfStars = random.randrange(10,51,1)
self.stars=[]
## -352,15 +356,15 ##
self.Death = pygame.image.load("images\Death.png")
self.Death = pygame.transform.scale(self.Death, (width2, height2))
self.death = 0
+ self.TotalTime = 0
def New(self):
- while True:
- self.Player.New()
- Place = self.Player.DOA()
- if Place != "New":
- self.TotalTime = 0
- self.Background.New()
- self.Bullits.Restart()
- self.Orbs.Restart()
+ self.Player.New()
+ Place = self.Player.DOA()
+ if Place != "New":
+ self.TotalTime = 0
+ self.Background.New()
+ self.Bullits.Restart()
+ self.Orbs.Restart()
def Blit(self):
self.Bullits.Convert()
self.Orbs.Convert()

Categories

Resources