why are my bullets not moving even though my tanks are - python

I'm making a pygame game.When I click on the tanks button and then click on the screen(play area) a tank is blitted on that coordinate. Along with the tank a bullet is also blitted. I'm able to make my tank move but the bullets are not shooting. I want the tanks to keep shooting automatically after the bullet gets reset after travelling, say 40 pixels.
This is the function that gives the tanks and the bullets the coordinates
tank_pos_list = []
bullet_list = []
def spawn_tank():
global tank_pos_list
global bullet_list
qx, qy = pygame.mouse.get_pos()
tankxy = [(qx - 35), (qy - 35)]
tank_pos_list.append(tankxy)
bullet_list.append(tankxy)
This is my movement class for tanks and bullets.
class MovementClass:
global bullet_list
global tank_pos_list
tank_surf = pygame.image.load("tank.png")
bullet = pygame.image.load("bullet.png")
def movetank(self, tankimg):
for tank_pos in tank_pos_list:
screen.blit(tankimg, (tank_pos[0], tank_pos[1]))
tank_pos[0] += 0.2
def movebullet(self, bulletimg):
for j in range(len(bullet_list)):
newx = (bullet_list[j][0] + 35)
screen.blit(bulletimg, (newx, (bullet_list[j][1] + 34)))
newx += 1
This is my main function
def main():
global new_tanks
global spawner
global tank_pos_list
global fire_bullet_tank
run = True
fps = 90
tanks = Button((59, 255, 140), 100, 610, 80, 80, text="Tanks")
tanks_over = Button((0, 255, 0), 100, 610, 80, 80, text="Tanks")
towers = Button((59, 255, 140), 510, 610, 150, 80, text="Towers")
towers_over = Button((0, 255, 0), 510, 610, 150, 80, text="Towers")
blue = pygame.image.load("blue_base.png")
red = pygame.image.load("red_base.png")
spawner = False
while run:
mx, my = pygame.mouse.get_pos()
pos = (mx, my)
x = pos[0]
y = pos[1]
mouse_pos = (mx, my)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if spawner and my < 550 and mx < 500:
spawn_tank()
spawner = False
if tanks.isOver(mouse_pos):
spawner = True
screen.fill((50, 168, 66))
if len(tank_pos_list) >= 11:
tank_pos_list.pop(-1)
pygame.draw.rect(screen, (201, 142, 47), (0, 600, 1000, 100))
pygame.draw.line(screen, (0, 0, 0), (500, 0), (500, 600))
if tanks.isOver(mouse_pos):
tanks_over.draw(screen)
else:
tanks.draw(screen)
if towers.isOver(mouse_pos):
towers_over.draw(screen)
else:
towers.draw(screen)
screen.blit(blue, (0, 100))
screen.blit(red, (800, 100))
#movement()
movingtank = MovementClass()
movingtank.movetank(pygame.image.load("tank.png"))
movingbullet = MovementClass()
movingbullet.movebullet(pygame.image.load("bullet.png"))
pygame.display.flip()
clock.tick(fps)

When you run
for tank_pos in tank_pos_list:
...
tank_pos[0] += 0.2
you're changing the first value in a list inside the tank_pos_list list. Note that you add tankxy to both lists in spawn_tank so you can see the change in tank_pos_list and bullet_list. It's the same list in both lists you're changing here.
But when you run
for j in range(len(bullet_list)):
newx = (bullet_list[j][0] + 35)
...
newx += 1
you just create a new variable newx and change its value; but you never change any values of the lists in bullet_list.
Some more notes:
The MovementClass has no internal state; it's basically useless that you create 2 new instances every frame. Use global functions instead (without a class) or just inline those functions.
You load "tank.png" and "bullet.png" every frame from disk. You should just load the images once outside your main loop. Otherwise, it becomes a major performance killer soon.
Try to create a class or multiple classes that represents the different actors of your game (pygame offers the Sprite class for this) and implement the behaviour and state in that class. While that's not the most advanced technique it is the right way to go IMHO for small games.
For an example, maybe take a look at this answer I did for another questions, which is pretty much a step-by-step guide on how I would create such a game.

Related

pygame.Rect.colliderect() giving me error [duplicate]

This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
How do I detect collision in pygame?
(5 answers)
Closed 2 years ago.
I am working on a game and I needed to make collision detection. I decided to use the function pygame.Rect.colliderect(). However, it is giving me the error:
pygame 2.0.0.dev6 (SDL 2.0.10, python 3.7.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:/Users/admin/PycharmProjects/ProgrammingLearn/SpaceInvaders.py", line 185, in <module>
main()
File "C:/Users/admin/PycharmProjects/ProgrammingLearn/SpaceInvaders.py", line 112, in main
if pygame.Rect.colliderect(blue_enemy_rect):
TypeError: Argument must be rect style object
I will "Bookmark" the place where I have used pygame.Rect.colliderect() with #Bookmark
# importing packages
import pygame
import random
import time
import sys
# Initializing Pygame
pygame.init()
# Setting a display width and height and then creating it
display_width = 700
display_height = 500
display_size = [display_width, display_height]
game_display = pygame.display.set_mode(display_size)
intro_display = pygame.display.set_mode(display_size)
# Setting a display caption
pygame.display.set_caption("Space Bugs")
spaceship = pygame.image.load("spaceship2.png")
blue_enemy = pygame.image.load("blue_enemy.png")
green_enemy = pygame.image.load("green_enemy.png")
orange_enemy = pygame.image.load("orange_enemy.png")
pink_enemy = pygame.image.load("pink_enemy.png")
yellow_enemy = pygame.image.load("yellow_enemy.png")
# Creating a font
pygame.font.init()
font = pygame.font.SysFont("consolas", 30)
large_font = pygame.font.SysFont("consolas", 60)
small_font = pygame.font.SysFont("consolas", 20)
# Creating a way to add text to the screen
def message(sentence, color, x, y, font_type, display):
sentence = font_type.render(str.encode(sentence), True, color)
display.blit(sentence, [x, y])
def main():
global white
global black
global clock
# Spaceship coordinates
spaceship_x = 300
spaceship_y = 375
spaceship_x_change = 0
blue_enemy_health = 5
green_enemy_health = 5
orange_enemy_health = 5
pink_enemy_health = 5
yellow_enemy_health = 5
blue_enemy_rect = pygame.Rect(30, 35, 80, 70)
# Initializing pygame
pygame.init()
# Creating colors
red = (255, 0, 0)
blue = (0, 0, 255)
# clock stuff
clock = pygame.time.Clock()
time_elapsed_since_last_action = 0
time_elapsed_since_last_action2 = 0
# Creating a loop to keep the program running
while True:
# --- Event Processing and controls
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
spaceship_x_change = 10
elif event.key == pygame.K_LEFT:
spaceship_x_change = -10
elif event.type == pygame.KEYUP:
spaceship_x_change = 0
spaceship_x += spaceship_x_change
# Preventing the ship from going off the screen
if spaceship_x > display_width - 140:
spaceship_x -= 10
if spaceship_x < 1:
spaceship_x += 10
laser_coords = [70, 209, 348, 505, 630]
random_x_coord = random.choice(laser_coords)
dt = clock.tick()
time_elapsed_since_last_action += dt
if time_elapsed_since_last_action > 500:
pygame.draw.rect(game_display, blue, [random_x_coord, 85, 6, 305])
time_elapsed_since_last_action = 0
time_elapsed_since_last_action2 += dt
# Setting Display color
game_display.fill(black)
message(str(blue_enemy_health), white, 65, 10, font, game_display)
game_display.blit(blue_enemy, (20, 25))
blue_hit_box = pygame.draw.rect(game_display, white, blue_enemy_rect, 1)
# Bookmark
if pygame.Rect.colliderect(blue_enemy_rect):
blue_enemy_health = blue_enemy_health - 1
message(str(green_enemy_health), white, 203, 10, font, game_display)
game_display.blit(green_enemy, (160, 25))
green_hit_box = pygame.draw.rect(game_display, white, [180, 35, 60, 70], 1)
message(str(orange_enemy_health), white, 341, 10, font, game_display)
game_display.blit(orange_enemy, (300, 25))
orange_hit_box = pygame.draw.rect(game_display, white, [315, 43, 65, 70], 1)
message(str(pink_enemy_health), white, 496, 10, font, game_display)
game_display.blit(pink_enemy, (440, 25))
pink_hit_box = pygame.draw.rect(game_display, white, [460, 35, 90, 70], 1)
message(str(yellow_enemy_health), white, 623, 10, font, game_display)
game_display.blit(yellow_enemy, (580, 25))
yellow_hit_box = pygame.draw.rect(game_display, white, [590, 40, 85, 70], 1)
# Creating a spaceship, lasers, and enemies
laser = pygame.draw.rect(game_display, red, [spaceship_x + 69, 100, 4, 300])
game_display.blit(spaceship, (spaceship_x, spaceship_y))
health = 10
message("Spaceship durability: " + str(health), white, 20, 480, small_font, game_display)
# Updating Screen so changes take places
pygame.display.flip()
# Setting FPS
FPS = pygame.time.Clock()
FPS.tick(60)
# Executing the function
if __name__ == "__main__":
main()
I don't see what is wrong here, as I believe this is how colliderect is used.
I am really close to finishing this program, and any help is appreciated. Thanks.
colliderect is an instance method (see Method Objects). The method tests whether 2 rectangles overlap. It needs to be called with 2 rectangles.
Either
if pygame.Rect.colliderect(rect1, rect2):
# [...]
or
if rect1.colliderect(rect2):
# [...]
This means that you can do the following:
blue_enemy_rect = pygame.Rect(30, 35, 80, 70)
green_enemy_rect = pygame.Rect(180, 35, 60, 70])
# [...]
while True:
# [...]
if green_enemy_rect.colliderect(blue_enemy_rect):
blue_enemy_health = blue_enemy_health - 1

How to make a picture appear from a list and make it disappear, while setting a variable to it in pygame?

I was wondering how would I get an image to appear out of a list and then make it disappear once it is clicked on. And once it is clicked on a variable will be assigned.
When I run this in pygame I get a bunch all of these pictures printed and they go by really fast.
def game():
screen = pygame.display.set_mode((1400, 750))
pygame.display.set_caption("Goofspiel")
screenExit = False
while not screenExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
screenExit = True
keys = pygame.key.get_pressed()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen.fill(lightgray)
fontname = pygame.font.SysFont("Denmark", 150)
font = pygame.font.SysFont("Denmark", 40)
font1 = pygame.font.SysFont("Denmark", 75)
name = fontname.render("Goofspeil", True, (black))
score = font.render("Player 1", True, (blue))
score1 = font.render("Player 2", True, (red))
player = font1.render("Player 1", True, (black))
que = font.render("Who's turn is it?", True, (black))
screen.blit(name, (490, 0))
#Score board
pygame.draw.rect(screen, sun, [0,20,375,80])
pygame.draw.rect(screen, black, [0,20,375,5])
pygame.draw.rect(screen, black, [0, 100.5, 375, 5])
pygame.draw.rect(screen, black, [375, 20, 5, 85])
pygame.draw.rect(screen, black, [305, 20, 5, 85])
pygame.draw.rect(screen, black, [180, 20, 5, 85])
pygame.draw.rect(screen, black, [110, 20, 5, 85])
screen.blit(score, (0, 50))
screen.blit(score1, (190, 50))
screen.blit(que, (1100, 20))
screen.blit(player, (1120, 70))
#Displaying the cards
screen.blit(DK, (5, 450))
screen.blit(DQ, (100, 450))
screen.blit(DJ, (200, 450))
screen.blit(D10, (300, 450))
screen.blit(D9, (400, 450))
screen.blit(D8, (500, 450))
screen.blit(D7, (600, 450))
screen.blit(D6, (700, 450))
screen.blit(D5, (800, 450))
screen.blit(D4, (900, 450))
screen.blit(D3, (1000, 450))
screen.blit(D2, (1100, 450))
screen.blit(D1, (1200, 450))
#Add a random picture
list = []
list.append(HK)
list.append(HQ)
list.append(HJ)
list.append(H10)
list.append(H9)
list.append(H8)
list.append(H7)
list.append(H6)
list.append(H5)
list.append(H4)
list.append(H3)
list.append(H2)
list.append(H1)
#rand = random.randrange(0, len(list))
random.shuffle(list)
screen.blit(list[0], (700,150))
if 200 > mouse[0] > 100 and 700 > mouse[1] > 450:
pygame.draw.rect(screen, lightblue2, [80, 705, 200, -60])
if click[0] == 1:
x = 12
score2 = font.render(str(x), True, (black))
screen.blit(score2, (135, 50))
pygame.display.update()
game()
What I want to do, is that I want a picture randomly out of this list to show up, then get "removed" from the list and then make the picture disappear from the screen. Because these pictures are cards, I want that if a person clicks on the king, the x value = 13 and so on.
Can someone please help, I'm stuck on this question. I'm trying to make the game Goofspiel and I can't!
Here's a point-form of how I would proceed:
Convert your H1, H2 ... images into PyGame Sprites.
This melds an image with a rectangle. It allows you to easily re-position and draw all the cards. The code an also use the mouse-click event to easily determine which of the cards (if any) was clicked.
Add the necessary card details into the Sprite Class too
This allows your Card to "know" its suit, number, and whether it's face-up.
Put your Card Sprites into a Pygame SpriteGroup
This facilitates easy drawing and mouse-click collision detection.
Once you know which card was clicked, it's pretty easy to remove it from the screen, turn it over, whatever because its state (location, suit, number, face-up, etc.) is all kept together in the sprite class. It no longer becomes a question of removing "#8 from the list".
Something like this:
class Card( pygame.sprite.Sprite ):
def __init__( self, front_image, back_image, suit, number, facing_up=True ):
pygame.sprite.Sprite.__init__(self)
self.front = pygame.image.load( front_image ).convert()
self.back = pygame.image.load( back_image ).convert()
self.rect = self.front.get_rect()
self.suit = suit
self.number = number
self.face_up = not facing_up
self.flip() # re-draw
def flip( self ):
self.face_up = not self.face_up
if ( self.face_up ):
self.image = self.front
else:
self.image = self.back
def moveTo( self, x, y ):
self.rect.x = x
self.rect.y = y
def isFaceUp( self ):
return self.face_up
# ... etc.
# make the cards
HK = Card( 'hearts_king.png', 'card_back.png', 'hearts', 13 )
HQ = Card( 'hearts_queen.png', 'card_back.png', 'hearts', 12 )
HJ = Card( 'hearts_jack.png', 'card_back.png', 'hearts', 11 )
H10 = Card( 'hearts_10.png', 'card_back.png', 'hearts', 10 )
# ... etc
all_hearts = [ HK, HQ, HJ, H10, H9, ... H1 ]
# TODO: call Card.moveTo() to position each card
cards_on_table = pygame.sprite.Group()
for card in all_hearts:
cards_on_table.add( card )
# Main Loop:
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.MOUSEBUTTONUP ):
# On mouse-click
mouse_pos = pygame.mouse.get_pos()
# Did we click on a card?
for card in cards_on_table:
if ( card.rect.collidepoint( mouse_pos ) ):
print( "Card [%s, %d] was clicked" % ( card.suit, card.number ) )
cards_on_table.remove( card ) # remove card from group
break
# Re-draw the window
window.fill( DARK_GREEN )
cards_on_table.draw( window )
pygame.display.flip()
# ... etc

How do I increase the size of a rectangle if a key is pressed?

Using pygame, I'm trying to create a simple mechanic which will increase a rectangle in the top right of my code, in this case it is a health bar. For now I want to make the bar increase everytime the button 'x' is clicked. Here is my code:
DISPLAYSURF = DISPLAYSURF = pygame.display.set_mode((900, 550), 0, 32)
heatBar = [45, 30]
hbPosition = [45, 30]
# Main game loop
while True:
heatBar.insert(0, list(hbPosition))
for event in pygame.event.get():
#Heat Bar (Tap x to increase)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
for pos in heatBar:
pygame.draw.rect(DISPLAYSURF, GREEN,
pygame.Rect(pos[0],pos[1],10,50))
The pygame.Rect on the last line is part of the line previous to it.
Anyway, I've tried to add various things and comment out things but I just can't seem to get it to work. Any idea on what I'm doing wrong or how to fix it?
Here's an example of a health bar:
import pygame
pygame.init()
w, h = 400, 400
screen = pygame.display.set_mode((w, h))
health = 0
while True:
screen.fill((0, 0, 0))
if pygame.event.poll().type == pygame.QUIT: pygame.quit(); break
keys = pygame.key.get_pressed()
if keys[pygame.K_x]:
health += 0.1
pygame.draw.rect(screen,
(100, 240, 100),
pygame.Rect(0, 0, health, 35
))
pygame.display.flip()
EDIT(added extra features):
import pygame
pygame.init()
w, h = 400, 400
screen = pygame.display.set_mode((w, h))
# I decided to go for a maxhealth type thing here,
health = 100
while True:
screen.fill((0, 0, 0))
# VVV This line polls pygames events and checks if it a QUIT event,
if pygame.event.poll().type == pygame.QUIT: pygame.quit(); break
# This relies on the previous line being called, or else it won't update,
keys = pygame.key.get_pressed()
# I added `Z` for adding to the health too,
if keys[pygame.K_x] and health > 0:
health -= 0.1
if keys[pygame.K_z] and health < 100:
health += 0.1
# The tint value is multiplied by 2.55 to map 0-100 to 0-255. Try it yourself(algebra): 255/100 = 2.55,
tint = 255 - (health * 2.55)
pygame.draw.rect(screen,
(tint, 255 - tint, 0),
pygame.Rect(0, 0, health, 35
))
pygame.display.flip()
Unfortunently because of how tint works, the middle range looks like a ugly brownish colour.
Also I would highly recommend you make your game with classes, they are much more uniform, and they are great for making large scale projects.
Here's a nice link: https://www.youtube.com/watch?v=ZDa-Z5JzLYM
EDIT(fixing brownish colour):
To fix the brownish colour, change this line:
pygame.draw.rect(screen,
(tint, 255 - tint, 0),
pygame.Rect(0, 0, health, 35
))
To,
pygame.draw.rect(screen,
(min(255, tint * 2), min(255, 335 - tint), 0),
pygame.Rect(0, 0, health, 35
))
NOTE: Using min(255, ...) will effectively make sure that the value does not exceed 255, because as long as the number is less than 255 it will return the number, otherwise it will return 255. Multiplying the tint by two is basically offsetting it, and the 335 - tint is to offset the other one too, you can change 335 to another number to change where the yellow is in the health bar :)

Bouncing an image in a polygonal way with pygame

Hey guys am new to pygame .I have to make a ball image ball.jpg to bounce in polygonal way.I have also an another ball image which is running in a square way.What i need is to add an another ball image and bounce it in a polygonal way. My code is
import pygame
from itertools import cycle
pygame.init()
screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()
ball = pygame.image.load('ball.jpg')
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()
speed = 5
up, down, left, right = (0, -speed), (0, speed), (-speed, 0), (speed, 0)
dirs = cycle([up, right, down, left])
dir = next(dirs)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise
# move player
player.move_ip(dir)
# if it's outside the screen
if not s_r.contains(player):
# put it back inside
player.clamp_ip(s_r)
# and switch to next direction
dir = next(dirs)
screen.fill(pygame.color.Color('Black'))
screen.blit(ball,player)
pygame.display.flip()
timer.tick(25)
This code works perfectly with one image ..What i need is to add an another image and it must run in polygonal shape on pygame window..
Hope you guys can help me out ..Thanks
You'll need some vector math to do this.
Create a list of points that describe the path the object should move, then calculate a vector describing the direction from the current position to the target position. Then move the object by using that vector. Once you hit your target, aim for the next point to move.
Here's an example:
import pygame
import math
from itertools import cycle
# some simple vector helper functions, stolen from http://stackoverflow.com/a/4114962/142637
def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def add(u, v):
return [ u[i]+v[i] for i in range(len(u)) ]
def sub(u, v):
return [ u[i]-v[i] for i in range(len(u)) ]
def dot(u, v):
return sum(u[i]*v[i] for i in range(len(u)))
def normalize(v):
vmag = magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ]
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
class Ball(object):
def __init__(self, path):
self.x, self.y = (0, 0)
self.speed = 2.5
self.color = (200, 200, 200)
self.path = cycle(path)
self.set_target(next(self.path))
#property
def pos(self):
return self.x, self.y
# for drawing, we need the position as tuple of ints
# so lets create a helper property
#property
def int_pos(self):
return map(int, self.pos)
#property
def target(self):
return self.t_x, self.t_y
#property
def int_target(self):
return map(int, self.target)
def next_target(self):
self.set_target(self.pos)
self.set_target(next(self.path))
def set_target(self, pos):
self.t_x, self.t_y = pos
def update(self):
# if we won't move, don't calculate new vectors
if self.int_pos == self.int_target:
return self.next_target()
target_vector = sub(self.target, self.pos)
# a threshold to stop moving if the distance is to small.
# it prevents a 'flickering' between two points
if magnitude(target_vector) < 2:
return self.next_target()
# apply the balls's speed to the vector
move_vector = [c * self.speed for c in normalize(target_vector)]
# update position
self.x, self.y = add(self.pos, move_vector)
def draw(self):
pygame.draw.circle(screen, self.color, self.int_pos, 4)
pygame.init()
quit = False
path = [(26, 43),
(105, 110),
(45, 225),
(145, 295),
(266, 211),
(178, 134),
(250, 56),
(147, 12)]
path2 = [(26, 43),
(105, 10),
(45, 125),
(150, 134),
(150, 26),
(107, 12)]
ball = Ball(path)
ball.speed = 1.9
ball2 = Ball(path2)
ball2.color = (200, 200, 0)
balls = [ball, ball2]
while not quit:
quit = pygame.event.get(pygame.QUIT)
pygame.event.poll()
map(Ball.update, balls)
screen.fill((0, 0, 0))
map(Ball.draw, balls)
pygame.display.flip()
clock.tick(60)
Here's an example without a custom class:
import pygame
import math
from itertools import cycle
# some simple vector helper functions, stolen from http://stackoverflow.com/a/4114962/142637
def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def sub(u, v):
return [ u[i]-v[i] for i in range(len(u)) ]
def normalize(v):
vmag = magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ]
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
pygame.init()
quit = False
path = [(26, 43),
(105, 110),
(45, 225),
(145, 295),
(266, 211),
(178, 134),
(250, 56),
(147, 12)]
path = cycle(path)
target = next(path)
ball = pygame.rect.Rect(target[0], target[1], 10, 10)
speed = 3.6
while not quit:
quit = pygame.event.get(pygame.QUIT)
pygame.event.poll()
if ball.topleft == target:
target = next(path)
target_vector = sub(target, ball.topleft)
if magnitude(target_vector) < 2:
target = next(path)
else:
move_vector = [c * speed for c in normalize(target_vector)]
ball.move_ip(move_vector)
screen.fill((0, 0, 0))
pygame.draw.rect(screen, pygame.color.Color('Grey'), ball)
pygame.display.flip()
clock.tick(60)

How do I solve an attribute error?

So like I said before my code (Or my current project that I am working on) is riddled with errors. So far I have at least solved a dozen errors or more and honestly I just give up. I mean God knows how many more there are.
The current problem that I am having is an AttributeError which is in my opinion one of the easiest errors to fix however I seem to have gone in to complete spaghetti mode and I have no clue on how to fix the problem.
{The error itself:
Traceback (most recent call last):
File "C:\Users\Burak\Desktop\boxtrial.py", line 87, in <module>
myScreen.addPane("1")
File "C:\Users\Burak\Desktop\boxtrial.py", line 67, in addPane
myPane.drawPane()
File "C:\Users\Burak\Desktop\boxtrial.py", line 19, in drawPane
self.Screen.blit(self.font.render(textToDisplay, True, (black)), (250, 115))
AttributeError: 'Pane' object has no attribute 'Screen'
}
I will list the code below but I feel as if I should explain what I am trying to do so you have some sort of understanding of the code.
Basically in the main loop I call upon the "Class Screen" which helps to create a PyGame screen that comes up once run. On that screen I am trying to get rectangles to appear on the screen in fixed positions (The coordinates are specific but the ones I use on the code are just for test purposes). I then have another class that is called "Pane" and this class is there so that I can draw many instances of the class pane within screen (If that makes sense).
If someone can help me get rid of the error that would be of grate help, but if you think that this is not a good way of solving the problem then please be my guest to come up with or teach me of a better way to do the same thing.
{The code:
import pygame
import sys
from pygame.locals import *
white = (255,255,255)
black = (0,0,0)
objs = []
MAIN_BUTTON = 1
class Pane():
def __init__(self, textToDisplay, coordinates, screen):
self.textToDisplay = textToDisplay
self.coordinates = coordinates
self.screen = screen
def drawPane(self):
self.Screen.blit(self.font.render(textToDisplay, True, (black)), (250, 115))
pygame.draw.rect(self.screen, (black), self.coordinates, 2)
pygame.display.update()
class Screen():
#constants/array(?) outlining the x,y boundaries of each of x10 panes
#Note to self - Remember to change co-ordinate values
NoOfPanes = 0
Panes = []
def __init__(self):
pygame.init()
pygame.display.set_caption('Box Test')
self.font = pygame.font.SysFont('Arial', 25)
Screen = pygame.display.set_mode((1000,600), 0, 32)
self.screen = Screen
self.screen.fill((white))
pygame.display.update()
def addPane(self, textToDisplay):
paneLocs = [(175, 75, 200, 100),
(0, 0, 200, 100),
(600, 400, 200, 100),
(175, 75, 200, 100),
(175, 75, 200, 100),
(175, 75, 200, 100),
(175, 75, 200, 100),
(175, 75, 200, 100),
(175, 75, 200, 100),
(175, 75, 200, 100)
]
if self.NoOfPanes > 10:
print("Limit Reached")
else:
myPane = Pane(textToDisplay, paneLocs[self.NoOfPanes], Screen)
myPane.drawPane()
self.NoOfPanes = self.NoOfPanes + 1
pygame.display.update()
def mousePosition(self):
global clickPos
global releasePos
for event in pygame.event.get():
if event.type == MAIN_BUTTON:
self.Pos = pygame.mouse.get_pos()
return MAIN_BUTTON
else:
return False
if __name__ == '__main__':
myScreen = Screen()
myScreen.addPane("1")
myScreen.addPane("2")
myScreen.addPane("3")
myScreen.addPane("4")
while True:
ev = pygame.event.get()
for event in ev:
if event.type == pygame.MOUSEBUTTONUP:
posx,posy = pygame.mouse.get_pos()
if (posx >= 175 and posx <= 375) and (posy >= 75 and posy <= 175):
print("BOB") #Bob was there just for test purposes
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit();
Fix your case.
class Pane():
def __init__(self, textToDisplay, coordinates, screen):
...
self.screen = screen
def drawPane(self):
self.Screen.... # <<< HERE

Categories