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.
Related
I m stuck with this DFS search for a Robo vac cleaner to clean the given grid. The Robo can move up, down, right, or left. The goal of the program is to find the next move.
Here is my python code, I m not sure what exactly I m doing wrong.
Based on the move returned the Robo will clean the room and calls this class with current position
'''
class RoboVac:
def __init__(self, config_list):
self.room_width, self.room_height = config_list[0]
self.pos = config_list[1]
self.block_list = config_list[2]
self.angle = 90
self.visited = []
self.block_size = 30
self.move = 0
self.max_x = self.room_width - 1
self.max_y = self.room_height - 1
self.is_move_back = False
# To store the new position
self.x = self.pos[0]
self.y = self.pos[1]
self.block_tiles_set = set()
for b in self.block_list:
for x in range(b[0], b[0] + b[2]):
for y in range(b[1], b[1] + b[3]):
self.block_tiles_set.add((x, y))
def visited_cell(self):
if (self.x, self.y) in self.visited:
return True
return False
def evaluate_new_position(self):
x = self.x
y = self.y
dir = self.move
# adjust based on direction only if new pos inside room
if dir == 0:
if y > 0:
y = y - 1
elif dir == 1:
if x < self.max_x:
x = x + 1
elif dir == 2:
if y < self.max_y:
y = y + 1
elif dir == 3:
if x > 0:
x = x - 1
if (x, y) == self.pos: # tried to go beyond room
return False
elif (x, y) in self.block_tiles_set:
return False
else:
return True
def find_next_move(self):
match self.angle:
case 0:
return 1
case 90:
return 0
case 180:
return 3
case 270:
return 2
return -1 #none
def move_left(self):
# to move left
self.angle = (self.angle + 90) % 360
def move_right(self):
if self.angle == 0:
self.angle = 270
self.angle = (self.angle - 90) % 360
def move_back(self):
self.move_right()
self.move_right()
def move_cell(self):
# find next move
self.move = self.find_next_move()
# check if it is safe to move
safe_move = self.evaluate_new_position()
if self.is_move_back:
self.move_back()
if safe_move:
return True
return False
def dfs(self):
if self.visited_cell():
self.move_back()
self.is_move_back = True
if self.move_cell():
self.visited.append(self.pos)
return self.move
self.move_left()
if self.move_cell():
self.visited.append(self.pos)
return self.move
self.move_left()
if self.move_cell():
self.visited.append(self.pos)
return self.move
self.move_left()
if self.move_cell():
self.visited.append(self.pos)
return self.move
self.dfs()
def get_next_move(self, current_pos): # called by PyGame code
# Return a direction for the vacuum to move
#mark current position visited
self.pos = current_pos
self.x = self.pos[0]
self.y = self.pos[1]
return self.dfs()
'''
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.
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
I have a section of my code that is spitting the error "does not match any other indentation level" or spitting "inconsistent use of tabs and spaces". I have tried so many different things just to get this code to run but no matter what I do it still errors. I have used online tab -> space websites such as https://tabstospaces.com/ . I have also done so many google searches to try and find some kind of help. The full code can be found below, but I believe the troublesome section is right here:
if man.jumpCount >= -10:
neg = 1
if man.jumpCount < 0:
neg = -1
if canGoDown():
if neg == -1:
if canGoDown() and man.y + gravity + man.height > gameY:
man.y -= (man.jumpCount ** 2) * 0.5 * neg
else:
man.y -= (man.jumpCount ** 2) * 0.5 * neg
man.jumpCount -= 1
I am using python 3.8 with notepad ++.
I have tried for quite awhile now to fix this. I have used multiple online "replace tab with spaces", I have tried retyping the white spaces multiple times as well. I've had this issue before but it has fixed itself without me knowing how. This time I cannot get it to fix. Any help will be amazing!
Full code:
import pygame
import time
import ctypes
#Gets screen resolution and assigns to resX and resY
user32 = ctypes.windll.user32
resX,resY = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
print('Resolution is: ', resX,resY)
pygame.init()
#Sets display size
gameX,gameY = 750,562
win = pygame.display.set_mode((gameX,gameY))
pygame.display.set_caption('Squared: The Game')
#Scales background image
bg = pygame.image.load('background.jpeg')
bg = pygame.transform.scale(bg, (gameX,gameY))
boungindRect = bg.get_rect()
objectList = []
gravity = 5
class cube(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
self.isJump = False
self.jumpCount = 10
self.hitbox = (self.x,self.y, self.width, self.height)
def move(self):
pass
def draw(self,spawnX,spawnY):
self.hitbox = (self.x,self.y,self.width,self.height)
pygame.draw.rect(win, (255,0,0), self.hitbox,2)
pygame.draw.rect(win, (255,0,0), (self.x, self.y, self.width,self.height))
pass
pass
class object():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self,color):
self.hitbox = (self.x,self.y,self.width,self.height)
pygame.draw.rect(win, (255,0,0), self.hitbox,2)
pygame.draw.rect(win, color, (self.x,self.y, self.width, self.height))
pass
def collision():
print('Collided')
pass
def makeObject(win,color,boundingBox): #x,y,width,height):
maxX = x + width
maxY = y + height
pygame.draw.rect(win, color, boundingBox) #(x,y,width,height))
xList = [x,maxX]
yList = [y,maxY]
return xList,yList
pass
def ldr1():
objectList.clear()
pygame.draw.rect(win, (0,255,0),(400,350,100,20))
object1X = [400,500]
object1Y = [350,370]
object1 = [object1X,object1Y]
objectList.append(object1)
pygame.draw.rect(win, (0,0,255), (250,375,100,20))
object2X = [250,350]
object2Y = [375,395]
object2 = [object2X,object2Y]
objectList.append(object2)
pygame.draw.rect(win, (255,255,255), (50, 350,20, 100))
object3X = [50, 70]
object3Y= [350,450]
object3 = [object3X,object3Y]
objectList.append(object3)
pygame.draw.rect(win, (0,0,0), (100,475,50,50))
object4X = [100,150]
object4Y = [475,525]
object4 = [object4X,object4Y]
objectList.append(object4)
pass
def updateScreen():
win.blit(bg,(0,0))
man.draw(250,250)
ldr1()
#pygame.draw.rect(win, (255,0,0), (50,50,50,50))
pygame.display.update()
pass
def callCurrentLvl():
ldr1()
pass
def canGoDown():
return canGo(0,-man.vel)
pass
def canGoUp():
return canGo(0,man.vel)
pass
def canGoRight():
print('checking canGoRight')
print('man.vel is ', man.vel)
#print('The list of objects is ' , objectList)
return canGo(man.vel,0)
pass
def canGoLeft():
return canGo(-man.vel,0)
pass
def canGoY(thisY = 0):
if minY <= man.y + thisY <= maxY or minY <= (man.y + man.height-20 + thisY) <= maxY:
#Activates if inside a hitbox
print("cannot travel Y")
return False
pass
else:
print('can travel Y')
return True
pass
def canGo(thisX = 0,thisY = 0):
"""
Is only checking the farthest right box... because it returns, breaking the loop after just one iteration.
"""
print('checking can Go ')
#print(objectList)
for curObject in objectList:
print('\n\n\n',curObject)
objectsX = curObject[0]
objectsY = curObject[1]
minX = objectsX[0]
minY = objectsY[0]
maxX = objectsX[1]
maxY = objectsY[1]
print(man.x, ' ', man.y)
print('-------')
print(minX,maxX)
print(minY,maxY)
print('-------')
#print('cur vel ',man.vel,' ', man.x,man.y)
#First if statement checks if both bottom x and top x are inside the points.
#second if statement does that with y
inX = False
inY = False
if minX <= man.x + thisX<= maxX and minX <= (man.x + man.width + thisX) <= maxX:
print('Inside x range')
inX = True
pass
else:
print('Outside x range')
pass
if minY <= man.y + thisY <= maxY or minY <= (man.y + man.height-20 +thisY ) <= maxY:
#Activates if inside a hitbox
print('Inside y range')
inY = True
pass
else:
print('Outside y range')
pass
if inX and inY:
print('inX and inY is True')
return False
pass
else:
print('one or the other is false')
print(inX, inY)
#return True
pass
pass
return True
pass
"""
Actual game
"""
man = cube(60,490, 40, 40)
#main loop
run = True
while run:
callCurrentLvl()
#print(objectList)
pygame.time.delay(25)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
#for objects in objectList:
#print(objects)
#object1 = object(objects)
#pass
if keys[pygame.K_LEFT] and man.x > (man.vel-3): #and canGoLeft():
print('Left key held')
print(man.x)
man.x = man.x - man.vel
pass
if keys[pygame.K_RIGHT] and man.x < gameX - man.width - man.vel + 5 and canGoRight():
print('Going right')
print(man.x)
man.x = man.x + man.vel
pass
if not(man.isJump):
if keys[pygame.K_UP]:
man.isJump = True
man.right = False
man.left = False
man.walkCount = 0
else:
if keys[pygame.K_DOWN] and man.jumpCount >= -10:
print('hammering')
pass
if man.jumpCount >= -10:
neg = 1
if man.jumpCount < 0:
neg = -1
if canGoDown():
if neg == -1:
if canGoDown() and man.y + gravity + man.height > gameY:
man.y -= (man.jumpCount ** 2) * 0.5 * neg
else:
man.y -= (man.jumpCount ** 2) * 0.5 * neg
man.jumpCount -= 1
else:
man.isJump = False
man.jumpCount = 10
#gravity
if canGoDown() and man.y + gravity + man.height < gameY:
man.y = man.y + gravity
updateScreen()
pass
pygame.quit()
Near the end of the file, at line 402:
if man.jumpCount >= -10:
neg = 1
if man.jumpCount < 0:
neg = -1
Move neg = 1 to the left so it corresponds to the next if:
if man.jumpCount >= -10:
neg = 1
if man.jumpCount < 0:
neg = -1
I guess the mistake is caused by the following sequence of events: you have been writing your code in some editor, which doesn't convert tab to spaces and assumes that tab corresponds to 8 spaces. When you used an online tool for converting tabs to spaces you used the default settings for tab equal to 4 spaces. Because of that you get inconsistent indentation in your file.
in your code "cango(): and addnewgame" method you have used in 'while' loop 'if' condition same indent to the another 'if' condition this is the error i think ..... instead of 'if' in same indent 'if' you use a better coding for ('elif': it is the correct way your query)
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()