Def mouseClicked() in draw not working, how do I fix it? - python

I am making a dnd application for fun, the char class is what each character is, but I can't seem to get to work
I have tried commenting out sections of code, yet it seems to be a problem with the init function
This is my code:
global mouseY
global x
x = 0
chars =[]
def setup():
global tsize
tsize = 50
def draw():
global x
if x == 0:
def mouseon(x,y,xs,ys):
return(mouseX <= xs and mouseX >= x and mouseY <= ys and mouseY >= y)
class char:
def __init__(self, name, HP, img, CLASS, SIZE, id):
self.xp = 0
self.yp = 0
self.SIZE = SIZE
self.name = name
self.HP = HP
self.img = img
self.CLASS = CLASS
self.id = id
self.Hover = False
chars.append(self)
dog = char("john", 100, "x.png", "archer", 50, 0)
print("l")
x = 2
else:
fill(255)
background(255)
stroke(0)
strokeWeight(1)
for i in range(height/50):
for j in range(width/50):
rect(i*50,j*50,49.5,49.5)
for i in chars:
def mouseClicked():
if mouseon(i.xp,i.yp,i.xp+i.SIZE,i.yp+i.SIZE):
i.Hover = True
print('h')
else:
print("n")
i.Hover = False
def mouseReleased():
print("o")
i.Hover = False
if i.Hover:
fill(0)
rect(i.xp+1, i.yp+1, i.xp+i.SIZE+1, i.yp+i.SIZE+1)
fill(0,255,0)
strokeWeight(0)
rect(i.xp, i.yp, i.xp+i.SIZE, i.yp+i.SIZE)
expected result:
when I press the mouse, I should get h or n printed to the console, and when I release it, I should get o
Actual results:
nothing
EDIT:
to clarify,
Draw is called once every frame
setup once at the beginning
mouseClicked when the mouse is clicked
and mouseReleased when the mouse is released

okay, so I had to put the mouse clicked and released functions at the bottom and put the for loops in those, but it solved my problem
the updated code is
global mouseX
global mouseY
global x
x = 0
chars =[]
def setup():
global tsize
tsize = 50
def draw():
global x
if x == 0:
global mouseon
def mouseon(x,y,xs,ys):
return(mouseX <= xs and mouseX >= x and mouseY <= ys and mouseY >= y)
class char:
def __init__(self, name, HP, img, CLASS, SIZE, id):
self.xp = 0
self.yp = 0
self.SIZE = SIZE
self.name = name
self.HP = HP
self.img = img
self.CLASS = CLASS
self.id = id
self.Hover = False
chars.append(self)
dog = char("john", 100, "x.png", "archer", 50, 0)
print("l")
x = 2
else:
fill(255)
background(255)
stroke(0)
strokeWeight(1)
for i in range(height/50):
for j in range(width/50):
rect(i*50,j*50,49.5,49.5)
for i in chars:
if i.Hover:
fill(0)
rect(i.xp+1, i.yp+1, i.xp+i.SIZE+1, i.yp+i.SIZE+1)
fill(0,255,0)
strokeWeight(0)
rect(i.xp, i.yp, i.xp+i.SIZE, i.yp+i.SIZE)
def mouseClicked():
for i in chars:
if mouseon(i.xp,i.yp,i.xp+i.SIZE,i.yp+i.SIZE):
i.Hover = True
print('h')
else:
print("n")
i.Hover = False
def mouseReleased():
for i in chars:
print("o")
i.Hover = False

Related

Conway's Game of Life Gliders break after a few generations

So I tried creating Conway's game of life in python with pygame. I made this without watching any tutorials, which is probably why it is so broken. It seems to be working fine, but when I creates a glider it seems to just break after a few generations. I looked at some other posts about my problem and added their solutions but that didn't make it work either. I know this is a lot to ask for, but can someone at least identify the problem.
Here is my code. I expected the glider to function as do they are supposed to, but it ended up just breaking in a few generations
Code:
main.py:
from utils import *
from grid import Grid
running = True
t = Grid(30)
while running:
pygame.display.set_caption(f'Conways Game of Life <Gen {t.generations}>')
clock.tick(200)
screen.fill(background_colour)
if not t.started:
t.EditMode()
else:
t.Update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()`
grid.py:
import cell
from utils import *
class Grid:
def __init__(self, size):
self.cells = []
self.cellSize = size
self.generations = 0
self.tick = 1
self.started = False
self.GenerateGrid()
def GenerateGrid(self):
x, y = 0, 0
while y < screen.get_height():
while x < screen.get_width():
c = cell.Cell(self, (x,y), self.cellSize)
self.cells.append(c)
x+=self.cellSize
x = 0
y+=self.cellSize
def EditMode(self):
self.Draw()
if self.started:
return
for cell in self.cells:
if pygame.mouse.get_pressed()[0]:
if cell.rect.collidepoint(pygame.mouse.get_pos()):
cell.state = 1
if pygame.mouse.get_pressed()[2]:
if cell.rect.collidepoint(pygame.mouse.get_pos()):
cell.state = 0
keys = pygame.key.get_pressed()
if keys[pygame.K_RETURN]:
self.started = True
def Draw(self):
for cell in self.cells:
cell.Draw()
def Update(self):
self.Draw()
self.tick -= 0.05
if self.tick < 0:
for cell in self.cells:
cell.UpdateState()
for cell in self.cells:
cell.state = cell.nextState
self.tick = 1
self.generations+=1
cell.py
from utils import *
class Cell:
def __init__(self, grid, position:tuple, size):
self.grid = grid
self.size = size
self.position = pygame.Vector2(position[0], position[1])
self.rect = pygame.Rect(self.position.x, self.position.y, self.size, self.size)
self.state = 0
self.nextState = self.state
def Draw(self):
pygame.draw.rect(screen, (0,0,0), self.rect)
if self.state == 0:
pygame.draw.rect(screen, (23,23,23), (self.position.x+4, self.position.y+4, self.size-4, self.size-4))
else:
pygame.draw.rect(screen, (255,255,255), (self.position.x+4, self.position.y+4, self.size-4, self.size-4))
def UpdateState(self):
rect = pygame.Rect(self.position.x-self.size, self.position.y-self.size, self.size*3, self.size*3)
pygame.draw.rect(screen, (0,0,0), rect)
targetCells = []
for c in self.grid.cells:
if rect.colliderect(c.rect):
targetCells.append(c)
livingAmt = 0
for c in targetCells:
if c.rect.x == self.rect.x and c.rect.y == self.rect.y:
continue
if c.state == 1:
livingAmt+=1
if self.state == 1:
if livingAmt > 3 or livingAmt <2:
self.nextState = 0
if self.state ==0:
if livingAmt == 3:
self.nextState =1
utils.py
import pygame
background_colour = (23, 23, 23)
screen = pygame.display.set_mode((900, 900))
clock = pygame.time.Clock()
running = True
Your function UpdateState both counts a cell's neighbors and updates the cell's state. Since you call that function in a loop, both are done together, which does not work, as explained here. You must split the "count" phase from the "update state" phase.

Pygame seemingly crashes with no error message

I'm working on creating an AI to play the classic game Snake, and have implemented it somewhat successfully, however every so often the program crashes upon reaching its target. I'm using a modified version of A* for pathfinding and pygame for the graphics.
import numpy as np
import pygame
import random
# Set constants for program
GRID_WIDTH = 25
GRID_HEIGHT = 25
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
displayX = 500
displayY = 500
SCALEX = displayX/GRID_WIDTH
SCALEY = displayY/GRID_HEIGHT
# Setyp pygame
gameDisplay = pygame.display.set_mode((displayX,displayY))
pygame.display.set_caption('Snake')
clock = pygame.time.Clock()
# Mainly stores values at each point in the game area
class Block():
def __init__(self, x, y, val):
self.x = x
self.y = y
self.val = val # Stores what type this block is e.g. snake or fruit
self.f = 0 # Values for A-Star Algorithm
self.g = 0
self.h = 0
def get_value(self):
return self.val
def set_value(self, new_val):
self.val = new_val
def set_cost(self, g, h):
self.g = g
self.h = h
self.f = self.h - self.g
def set_parent(self, parent):
self.parent = parent # Used for retracing the path
class Snake():
def __init__(self, x, y):
self.x = x
self.y = y
self.L = 4 # Length of snake
self.body = [] # List of all parts in snake
self.body.append([x, y])
self.path = None
def move(self, board):
print(self.path)
if self.path == None or self.path == []: # Check if a path exists
self.A_Star(board) # If not calculate path
else:
self.x = self.path[0][0] # Move to next point in path then remove it from list
self.y = self.path[0][1]
self.path.pop(0)
self.body.append([self.x, self.y]) # Add body part
self.body = self.body[-self.L:]
def get_snake(self):
return self.body[-self.L:]
def get_head(self):
return [self.x, self.y]
def eat(self): # Increase length and reset path
self.L += 1
self.path = None
def A_Star(self, board): # Modified version of A Star to prioritise moving away from target
start = board.get_grid()[self.x, self.y]
end = board.get_fruit()
if start != None and end != None:
open_list = []
closed_list = []
current = start
open_list.append(current)
while open_list != []:
current = open_list[0]
for block in open_list:
if block.f > current.f:
current = block
open_list.remove(current)
closed_list.append(current)
if current == end:
path = self.retrace_path(start, end)
return True
neighbours = board.get_node_neighbours(current)
for neighbour in neighbours:
if neighbour.get_value() != "body" and not neighbour in closed_list:
if not neighbour in open_list:
neighbour.set_cost(neighbour.g, board.get_distance(current, end))
neighbour.set_parent(current)
if not neighbour in open_list:
open_list.append(neighbour)
return False
def retrace_path(self, start, end):
current = end
path = []
while current != start:
path.append([current.x, current.y])
current = current.parent
self.path = path
self.path.reverse()
'''def survive(self, board):
neighbours = board.get_node_neighbours(board.get_grid()[self.x, self.y])
for neighbour in neighbours:
if neighbour.val == "empty":
self.path = [neighbour.x, neighbour.y]
break'''
class Board():
def __init__(self, snake):
self.grid = np.empty((GRID_WIDTH, GRID_HEIGHT), dtype=object)
for x in range(0, GRID_WIDTH):
for y in range(0, GRID_HEIGHT):
self.grid[x,y] = Block(x, y, "empty") # 2D Array containing all blocks
self.fruit = self.new_fruit(snake) # Generate new fruit
self.score = 0
def check_fruit(self, snake): # Check collision between snake and fruit
snake_head = snake.get_head()
if snake_head[0] == self.fruit[0] and snake_head[1] == self.fruit[1]:
snake.eat()
self.score += 1
self.fruit = self.new_fruit(snake)
def check_death(self, snake): # Check to see if snake is dead
snake_head = snake.get_head()
snake_body = snake.get_snake()
if snake_head[0] >= GRID_WIDTH or snake_head[0] < 0 or snake_head[1] >= GRID_HEIGHT or snake_head[1] < 0:
return True
collisions = 0
for part in snake_body:
if snake_head == part:
collisions += 1
if collisions == 2:
return True
def draw(self, snake): # Draw everything to screen
self.grid = np.empty((GRID_WIDTH, GRID_HEIGHT), dtype=object)
for x in range(0, GRID_WIDTH):
for y in range(0, GRID_HEIGHT):
self.grid[x,y] = Block(x, y, "empty")
for part in snake.get_snake():
self.grid[part[0], part[1]].set_value("body")
self.grid[snake.get_head()[0], snake.get_head()[1]].set_value("head")
self.grid[self.fruit[0], self.fruit[1]].set_value("fruit")
for x in range(0, GRID_WIDTH):
for y in range(0, GRID_HEIGHT):
if self.grid[x, y].get_value() == "fruit":
pygame.draw.rect(gameDisplay,RED,(x*SCALEX,y*SCALEY,SCALEX,SCALEY))
elif self.grid[x, y].get_value() == "body" or self.grid[x, y].get_value() == "head":
pygame.draw.rect(gameDisplay,WHITE,(x*SCALEX,y*SCALEY,SCALEX,SCALEY))
def new_fruit(self, snake): # Generate a new fruit location
complete = False
fail = False
while not complete:
fruit_loc = [random.randint(0, GRID_WIDTH-1), random.randint(0, GRID_HEIGHT-1)]
for part in snake.get_snake(): # Check that fruit is not in snake
if part == fruit_loc:
fail = True
if not fail:
complete = True
return fruit_loc
def get_node_neighbours(self, block): # Get surrounding blocks from block
neighbours = []
options = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for option in options:
checkX = block.x + option[0]
checkY = block.y + option[1]
if checkX >= 0 and checkX < GRID_WIDTH and checkY >= 0 and checkY < GRID_HEIGHT:
neighbours.append(self.grid[checkX,checkY])
return neighbours
def get_distance(self, start, end): # Get distance between two points
dx = abs(start.x - end.x)
dy = abs(start.y - end.y)
return dx + dy - 1
def get_grid(self):
return self.grid
def get_fruit(self):
return self.grid[self.fruit[0], self.fruit[1]]
def main():
snake = Snake(0, 0)
board = Board(snake)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
snake.move(board) # Move snake
if board.check_death(snake): # End program if snake is dead
running = False
break
board.check_fruit(snake) # Call fruit check
gameDisplay.fill(BLACK) # Draw to screen
board.draw(snake)
pygame.display.update()
clock.tick(100)
main()
pygame.quit()
No error messages appear and the only way to tell that the program has stopped is that pygame no longer allows you to quit out and crashes instead. As far as I can tell the point at which it happens if completely random but occurs on most rounds. The snake will reach the fruit but will stop right before eating it.
The issue is the method new_fruit in the class Board. You've generated and endless loop. Actually if the random position fails at the first try, fail will stay True forever.
fail = False has to be set in the outer loop, rather than before the loop:
class Board():
# [...]
def new_fruit(self, snake): # Generate a new fruit location
complete = False
# fail = False
while not complete:
fail = False # <----
fruit_loc = [random.randint(0, GRID_WIDTH-1), random.randint(0, GRID_HEIGHT-1)]
for part in snake.get_snake(): # Check that fruit is not in snake
if part == fruit_loc:
fail = True
if not fail:
complete = True
return fruit_loc
Replace all your (x*SCALEX,y*SCALEY,SCALEX,SCALEY) to (int(x*SCALEX),int(y*SCALEY),int(SCALEX),int(SCALEY))

Python - Genetic Algorithm mutation function is not working

I created an AI in python/pygame but even after spending hours of debugging, I could not find why the individuals(dots) are not getting mutated. After few generations, all the individuals just overlap each other and follow the same exact path. But after mutation they should move a little bit differently.
Here is what a population size of 10 looks like after every 2-3 generations..
Image 1 Image 2 Image 3
As you can see, just after few generations they just overlap and all the individuals in the population move together, following exact same path! We need mutations!!!
I would be really grateful to you if you could find any mistake. Thank!
I saw the code from: https://www.youtube.com/watch?v=BOZfhUcNiqk&t
and tried to make it in python. Here's my code
import pygame, random
import numpy as np
pygame.init()
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("The Dots")
FPS = 30
clock = pygame.time.Clock()
gameExit = False
grey = [30, 30, 30]
white = [255, 255, 255]
black = [0, 0, 0]
red = [255, 0, 0]
goal = [400, 10]
class Dot():
def __init__(self):
self.x = int(width/2)
self.y = int(height - 150)
self.r = 3
self.c = black
self.xVel = self.yVel = 0
self.xAcc = 0
self.yAcc = 0
self.dead = False
self.steps = 0
self.reached = False
self.brain = Brain(200)
def show(self):
pygame.draw.circle(screen, self.c, [int(self.x), int(self.y)], self.r)
def update(self):
if (self.x >= width or self.x <= 0 or self.y >= height or self.y <= 0):
self.dead = True
elif (np.sqrt((self.x-goal[0])**2 + (self.y-goal[1])**2) < 5):
self.reached = True
if not self.dead and not self.reached:
if len(self.brain.directions) > self.steps:
self.xAcc = self.brain.directions[self.steps][0]
self.yAcc = self.brain.directions[self.steps][1]
self.steps += 1
self.xVel += self.xAcc
self.yVel += self.yAcc
if self.xVel > 5:
self.xVel = 5
if self.yVel > 5:
self.yVel = 5
self.x += self.xVel
self.y += self.yVel
else: self.dead = True
def calculateFitness(self):
distToGoal = np.sqrt((self.x-goal[0])**2 + (self.y-goal[1])**2)
self.fitness = 1/(distToGoal**2)
return self.fitness
def getChild(self):
child = Dot()
child.brain = self.brain
return child
class Brain():
def __init__(self, size):
self.size = size
self.directions = []
self.randomize()
def randomize(self):
self.directions.append((np.random.normal(size=(self.size, 2))).tolist())
self.directions = self.directions[0]
def mutate(self):
for i in self.directions:
rand = random.random()
if rand < 1:
i = np.random.normal(size=(1, 2)).tolist()[0]
class Population():
def __init__(self, size):
self.size = size
self.dots = []
self.fitnessSum = 0
for i in range(self.size):
self.dots.append(Dot())
def show(self):
for i in self.dots:
i.show()
def update(self):
for i in self.dots:
i.update()
def calculateFitness(self):
for i in self.dots:
i.calculateFitness()
def allDead(self):
for i in self.dots:
if not i.dead and not i.reached:
return False
return True
def calculateFitnessSum(self):
self.fitnessSum = 0
for i in self.dots:
self.fitnessSum += i.fitness
def SelectParent(self):
rand = random.uniform(0, self.fitnessSum)
runningSum = 0
for i in self.dots:
runningSum += i.fitness
if runningSum > rand:
return i
def naturalSelection(self):
newDots = []
self.calculateFitnessSum()
for i in self.dots:
parent = self.SelectParent()
newDots.append(parent.getChild())
self.dots = newDots
def mutate(self):
for i in self.dots:
i.brain.mutate()
test = Population(100)
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
screen.fill(white)
if test.allDead():
#Genetic Algorithm
test.calculateFitness()
test.naturalSelection()
test.mutate()
else:
test.update()
test.show()
pygame.draw.circle(screen, red, goal, 4)
clock.tick(FPS)
pygame.display.update()
pygame.quit()
Thanks for any help!
I didn't go through the whole code, but over here
def mutate(self):
for i in self.directions:
rand = random.random()
if rand < 1:
i = np.random.normal(size=(1, 2)).tolist()[0]
you are trying to assign a new value to i (which is an iterater), so it won't change anything, which explains why you'r having trouble with the mutations.
You should have something like this:
def mutate(self):
for i in range(len(self.directions)):
rand = random.random()
if rand < 1:
self.directions[i] = np.random.normal(size=(1, 2)).tolist()[0]
or you can use list comprehensions
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Why my ball Sprite doesnt always bounce on my Sprite bar?!

I have some problems and I cant figure out how to fix them...
It is really simple game. A bar moved by the mouse and one ball is (or some balls) bouncing.
The user just need to keep the ball bouncing.
The user can choose how many balls he wants (1,2,3), the size of the bar (small, medium,large) and the speed of the balls (slow, normal, fast).
Problems:
- sometimes everything works fine, and sometimes the ball (or balls) just goes through the bar. Like if the collision function does not work. Is there any other way I can do?
everytime there is a collision, the score should add 10 points for the total displayed on top of the screen, but this score is been overwriting all the time.
For this game be run, I just have to call the function (startGame) from other file (settings), where it also sends the value of number of balls, size of bar and speed of balls.
If anyone can help I appreciate.
Thanks
from livewires import games, color
from tkinter import*
import random
games.init(screen_width = 735, screen_height = 350, fps = 60)
class Bounce(games.Sprite):
global total_score
total_score = 0
def update(self):
global total_score
if self.bottom == 315 and self.overlapping_sprites:
self.dy = -self.dy
total_score += 10
the_score = games.Text(value = 0, size = 25,
color = color.gray,x = 700, y = 20)
games.screen.add(the_score)
if self.right > games.screen.width or self.left < 0:
self.dx = -self.dx
if self.top < 0:
self.dy = -self.dy
if self.bottom == 400:
lose_message = games.Message(value = " - GAME OVER -",
size = 50,
color = color.gray,
x = games.screen.width/2,
y = games.screen.height/2,
lifetime = 300,
after_death = games.screen.quit)
games.screen.add(lose_message)
class Bar_moving(games.Sprite):
def update(self):
self.x = games.mouse.x
self.y = 315
if self.left < 0:
self.left = 0
if self.right > games.screen.width:
self.right = games.screen.width
class have_settings():
def __init__(self):
global the_ball_speed
global the_ball_number
global the_bar_size
if "the_ball_speed" not in globals():
the_ball_speed = "normal"
if "the_bar_size" not in globals():
the_bar_size = "medium"
if "the_ball_number" not in globals():
the_ball_number = 1
def set_all(self, number, size, speed):
global the_ball_speed
global the_bar_size
global the_ball_number
if speed in ("slow","normal","fast"):
the_ball_speed = speed
if size in ("small","medium","large"):
the_bar_size = size
if number in (1,2,3):
the_ball_number = number
def startGame():
call = have_settings()
background = games.load_image("BG.jpg", transparent = False)
games.screen.background = background
#-------------------------------------SPEED
sp_is = 0
if the_ball_speed == "slow":
sp_is = 2
elif the_ball_speed == "normal":
sp_is = 3
elif the_ball_speed == "fast":
sp_is = 4
#-------------------------------------BALL NUMBER
if the_ball_number in (1,2,3):
for n in range(the_ball_number):
position_x_list =(50,150,250,350,400,450,500,550)
position_x = random.choice(position_x_list)
position_y_list =(50,100,150,200,225,250)
position_y = random.choice(position_y_list)
vert_speed_list = (-2,2)
vert_speed = random.choice(vert_speed_list)
ball_img = games.load_image("ball.bmp")
ball = Bounce(image = ball_img,
x = position_x,
y = position_y,
dx = vert_speed,
dy = - sp_is)
games.screen.add(ball)
#-------------------------------------BAR SIZE
if the_bar_size in ("small","medium","large"):
if the_bar_size == "small":
bar_pic = "bar_small.jpg"
elif the_bar_size == "medium":
bar_pic = "bar_medium.jpg"
elif the_bar_size == "large":
bar_pic = "bar_large.jpg"
bar = games.load_image(bar_pic, transparent = False)
the_bar = Bar_moving(image = bar, x = games.mouse.x)
games.screen.add(the_bar)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
You should do a greater than check rather than an equals check as follows:
if self.bottom >= 315 and self.overlapping_sprites:
^^
instead of
if self.bottom == 315 and self.overlapping_sprites:
This is because rarely will the ball's y position ever perfectly line up with the bottom. In some cases it may go from y==314 to y==316. In such cases, your method above wouldn't work. Therefore, you should be a greater than test rather than an equality test.
You can apply similar changes everywhere else and it should work.

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