Label Position, Resize Background And Hide Title Bar - python

I'm trying to better understand Pyglet and I'm using a script posted by Torxed in my previous question. I started to modify it until I reached this point:
import pyglet, datetime, os
from pyglet.gl import *
from collections import OrderedDict
from time import time
from pathlib import Path
key = pyglet.window.key
class main(pyglet.window.Window):
#Variable Display
Fullscreen = False
CountDisplay = 0
setDisplay0 = (1024, 576)
setDisplay1 = (800, 600)
setDisplay2 = (1024, 768)
setDisplay3 = (1280, 720)
setDisplay4 = (1280, 1024)
setDisplay5 = (1366, 768)
setDisplay6 = (1920, 1080)
#Variable Info
infoHidden = False
title = "Pokémon Life And Death: Esploratori Del Proprio Destino"
build = "Versione: 0.0.0"
keyPrint = "Nessuno"
MousekeyPrint = "Nessuno"
infoFullscreen = "Disattivo"
infoDisplay = "1024, 576"
def __init__ (self, width=1024, height=576, fullscreen=False, *args, **kwargs):
super(main, self).__init__(width, height, fullscreen, *args, **kwargs)
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
self.infoScreen = (screen.width, screen.height)
self.xDisplay = int(screen.width / 2 - self.width / 2)
self.yDisplay = int(screen.height / 2 - self.height / 2)
self.set_location(self.xDisplay, self.yDisplay)
self.sprites = OrderedDict()
self.spritesInfo = OrderedDict()
#Information Hidden
#Title
self.spritesInfo["title_label"] = pyglet.text.Label(self.title, x=self.infoPos("x", 0), y=self.infoPos("y", 0))
#Build Version
self.spritesInfo["build_label"] = pyglet.text.Label(self.build, x=self.infoPos("x", 0), y=self.infoPos("y", 20))
#Fullscreen
self.spritesInfo["fullscreen_label"] = pyglet.text.Label("Fullscreen: " + self.infoFullscreen, x=self.infoPos("x", 0), y=self.infoPos("y", 40))
#Display
self.spritesInfo["screen_label"] = pyglet.text.Label("Display: " + self.infoDisplay, x=self.infoPos("x", 0), y=self.infoPos("y", 60))
#FPS
self.spritesInfo["fps_label"] = pyglet.text.Label("FPS: 0", x=self.infoPos("x", 0), y=self.infoPos("y", 80))
self.last_update = time()
self.fps_count = 0
#Mouse Position
self.mouse_x = 0
self.mouse_y = 0
self.spritesInfo["mouse_label"] = pyglet.text.Label(("Mouse Position (X,Y): " + str(self.mouse_x) + "," + str(self.mouse_y)), x=self.infoPos("x", 0), y=self.infoPos("y", 100))
#Player Position
self.player_x = 0
self.player_y = 0
self.spritesInfo["player_label"] = pyglet.text.Label(("Player Position (X,Y): " + str(self.player_x) + "," + str(self.player_y)), x=self.infoPos("x", 0), y=self.infoPos("y", 120))
#Key Press
self.keys = OrderedDict()
self.spritesInfo["key_label"] = pyglet.text.Label(("Key Press: " + self.keyPrint), x=self.infoPos("x", 0), y=self.infoPos("y", 140))
#Mouse Press
self.spritesInfo["MouseKey_label"] = pyglet.text.Label(("Mouse Key Press: " + self.MousekeyPrint), x=self.infoPos("x", 0), y=self.infoPos("y", 160))
self.alive = 1
def infoPos(self, object, ny):
posInfo = self.get_size()
if object is "x":
elab = 10
elif object is "y":
elab = posInfo[1] - 20 - ny
else:
elab = 0
return elab
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_x = x
self.mouse_y = y
def on_mouse_release(self, x, y, button, modifiers):
self.MousekeyPrint = "Nessuno"
def on_mouse_press(self, x, y, button, modifiers):
self.MousekeyPrint = str(button)
def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
self.drag = True
print('Dragging mouse at {}x{}'.format(x, y))
def on_key_release(self, symbol, modifiers):
self.keyPrint = "Nessuno"
try:
del self.keys[symbol]
except:
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE:
self.alive = 0
if symbol == key.F2:
datanow = datetime.datetime.now()
if not Path("Screenshot").is_dir():
os.makedirs("Screenshot")
pyglet.image.get_buffer_manager().get_color_buffer().save("Screenshot/"+str(datanow.day)+"-"+str(datanow.month)+"-"+str(datanow.year)+"_"+str(datanow.hour)+"."+str(datanow.minute)+"."+str(datanow.second)+".png")
if symbol == key.F3:
if self.infoHidden:
self.infoHidden = False
else:
self.infoHidden = True
if symbol == key.F10:
self.CountDisplay += 1
if self.CountDisplay == 1:
size = self.setDisplay1
elif self.CountDisplay == 2:
size = self.setDisplay2
elif self.CountDisplay == 3:
size = self.setDisplay3
elif self.CountDisplay == 4:
size = self.setDisplay4
elif self.CountDisplay == 5:
size = self.setDisplay5
elif self.CountDisplay == 6:
size = self.setDisplay6
else:
self.CountDisplay = 0
size = self.setDisplay0
self.set_size(size[0], size[1])
self.infoDisplay = str(size[0]) + "," + str(size[1])
pos = (int(self.infoScreen[0] / 2 - size[0] / 2), int(self.infoScreen[1] / 2 - size[1] / 2))
self.set_location(pos[0], pos[1])
if symbol == key.F11:
if self.Fullscreen:
self.Fullscreen = False
self.set_fullscreen(False)
self.infoFullscreen = "Disattivo"
else:
self.Fullscreen = True
self.set_fullscreen(True)
self.infoFullscreen = "Attivo"
self.keyPrint = str(symbol)
self.keys[symbol] = True
def pre_render(self):
pass
def render(self):
self.clear()
#FPS
self.fps_count += 1
if time() - self.last_update > 1:
self.spritesInfo["fps_label"].text = "FPS: " + str(self.fps_count)
self.fps_count = 0
self.last_update = time()
#Mouse Position
self.spritesInfo["mouse_label"].text = "Mouse Position (X,Y): " + str(self.mouse_x) + "," + str(self.mouse_y)
#Player Position
self.spritesInfo["player_label"].text = "Player Position (X,Y): " + str(self.player_x) + "," + str(self.player_y)
#Key Press
self.spritesInfo["key_label"].text = "Key Press: " + self.keyPrint
#Mouse Press
self.spritesInfo["MouseKey_label"].text = "Mouse Key Press: " + self.MousekeyPrint
#Fullscreen
self.spritesInfo["fullscreen_label"].text = "Fullscreen: " + self.infoFullscreen
#Display
self.spritesInfo["screen_label"].text = "Display: " + self.infoDisplay
#self.bg.draw()
self.pre_render()
for sprite in self.sprites:
self.sprites[sprite].draw()
if self.infoHidden:
for spriteInfo in self.spritesInfo:
self.spritesInfo[spriteInfo].draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
event = self.dispatch_events()
if __name__ == '__main__':
x = main()
x.run()
But now I find myself in front of a point where I can not proceed in Pyglet alone.
I can not understand how I can change the coordinates of the "label" every time the window size changes.
I would like to be able to use an image as a background and adapt it to the size of the window (basic the image is 1920x1080, ie the maximum window size). The problem is that I did not find much on this subject. I state that what I'm working on is 2D, not 3D. I had found a possible solution in another question, always answered by Torxed on the resizing of an image, but in some tests before this, after having adapted it, it did not work. So I do not know where to bang my head sincerely. In Pygame it was easy to use "pygame.transform.scale", but in Pyglet I would not know.
Finally, I tried both on the Pyglet wiki and on the web, but I did not find anything. How can I delete or hide the window title bar? In Pygame, you could with the flags. Is it possible to do this also with Pyglet?
EDIT:
I forgot to ask another question. When I press a key on the keyboard or mouse, the information displayed with F3 is printed in the corresponding key number. Is there a way to replace the number with the name of the button? For example, 97 is replaced with "A"? Obviously, I mean if there's a way without having to list all the keys and put the "if" statement for everyone.
EDIT2:
It seems like the script posted, the def on_resize (self, width, height) part does not like it very much. Let me explain, if for itself the function works correctly. The problem is that if I insert it, the labels, once pressed F3, do not appear. I tried to test it using print in several places and it seems that the only instruction that is not executed is self.spritesInfo [spriteInfo] .draw ()

Related

shooting game in kivy

I am currently making simple shooting game in python kivy. My character is moving but when pressed space bar, the bullet is generated in the same position. So the bullet is not mapped onto the character.
I tried creating bullet as a class but it didn't help.
I will be glad for any help.
Here is my code:
def __init__(self, *args, **kwargs):
super(Auto,self).__init__(*args,**kwargs)
self.rect = Rectangle(size = (150, 150), pos = (0, 0), source = "spriteshd00.png")
self.canvas.add(self.rect)
def pohyb(self, vector):
self.rect.pos = Vector(self.rect.pos) + Vector(vector)
class Hra(BoxLayout):
def __init__(self, *args, **kwargs):
super(Hra,self).__init__(*args,**kwargs)
self.orientation = "vertical"
self.car = Auto(size_hint = (1,.9))
self.bullet = Rectangle(pos=(0,0), size=(20, 5))
Clock.schedule_interval(self.movebullet, .025)
self.add_widget(self.car)
ovladaci_panel_obal = BoxLayout(orientation = "horizontal", size_hint = (1,.1))
self.up_btn = ToggleButton(text = "Up", group = "smer")
self.up_btn.bind(state = self.on_state)
ovladaci_panel_obal.add_widget(self.up_btn)
self.left_btn = ToggleButton(text = "Left", group = "smer")
self.left_btn.bind(state = self.on_state)
ovladaci_panel_obal.add_widget(self.left_btn)
self.down_btn = ToggleButton(text = "Down", group = "smer")
self.down_btn.bind(state = self.on_state)
ovladaci_panel_obal.add_widget(self.down_btn)
self.right_btn = ToggleButton(text = "Right", group = "smer")
self.right_btn.bind(state = self.on_state)
ovladaci_panel_obal.add_widget(self.right_btn)
self.add_widget(ovladaci_panel_obal)
# Připojíme klávesnici k aplikaci
self.Keyboard = Window.request_keyboard(self._keyboard_closed,self,'text')
self.Keyboard.bind(on_key_down = self._on_keyboard_down)
self.Keyboard.bind(on_key_up = self._on_keyboard_up)
self.Keyboard.bind(on_key_up=self.shoot)
def _keyboard_closed(self):
#Funkce už nebude volána při stisku klávesy
self.Keyboard.unbind(on_key_down = self._on_keyboard_down())
self.Keyboard.unbind(on_key_up=self._on_keyboard_down())
self.Keyboard.unbind(on_key_up=self.shoot())
self.Keyboard = None #odstraneni klavesnice
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
if(keycode[1] == "up"):
self.reset_state()#resetovani stavu tlacitek
self.up_btn.state = "down"
elif(keycode[1] == "left"):
self.reset_state()#resetovani stavu tlacitek
self.left_btn.state = "down"
elif(keycode[1] == "right"):
self.reset_state()#resetovani stavu tlacitek
self.right_btn.state = "down"
elif(keycode[1] == "down"):
self.reset_state()#resetovani stavu tlacitek
self.down_btn.state = "down"
if(keycode[1] == "escape"):
keyboard.release()#stisknu escape a aplikace prestane fungovat
return True
def _on_keyboard_up(self,keyboard, keycode):
self.reset_state()
def movebullet(self, *args):
y = self.car.pos[1]*3 + self.car.pos[0]*3
x = self.bullet.pos[0] + 15
#self.bullet.pos = self.car.pos
self.bullet.pos = (x,y) #tahle konfiiguarce umozni jit kulce horizontalne
#blx, bly = self.ball.pos
# Check for hit. Ball size is 15. Bullet size is 5.
#if (x + 5 > blx and x < blx + 15 and y > bly and y < 400):
#self.canvas.remove(self.ball)
#self.newball()
#self.lblRes.text = str(int(self.lblRes.text) + 100)
def shoot(self, keyboard, keycode):
if (keycode[1] == 'spacebar'):
with self.canvas:
Color(0, 0, 0, 1, mode="rgba")
self.bullet = Rectangle(pos= (300, 0), size=(20, 5))
g1 = self.car.pos[0] + 15
g2 = self.car.pos[1] + 15
self.bullet.pos = (g1, g2)
def reset_state(self):
self.up_btn.state = "normal"
self.left_btn.state = "normal"
self.down_btn.state = "normal"
self.right_btn.state = "normal"
def on_state(self, obj, state):
if(obj.text == "Up"):
if(state == "down"):
self.timer = Clock.schedule_interval(lambda dt: self.car.pohyb((0, 1)), 0.01)
#self.auto.rect.source = "up.png" # Změníme obrázek
if(state == "normal"):
#Zastavíme timer
Clock.unschedule(self.timer)
elif(obj.text == "Left"):
if(state == "down"):
self.timer = Clock.schedule_interval(lambda dt: self.car.pohyb((-1, 0)), 0.01)
#self.car.rect.source = "left.png" # Změníme obrázek
if(state == "normal"):
Clock.unschedule(self.timer)
elif(obj.text == "Down"):
if(state == "down"):
self.timer = Clock.schedule_interval(lambda dt: self.car.pohyb((0, -1)), 0.01)
#self.car.rect.source = "down.png" # Změníme obrázek
if(state == "normal"):
Clock.unschedule(self.timer)
elif(obj.text == "Right"):
if(state == "down"):
self.timer = Clock.schedule_interval(lambda dt: self.car.pohyb((1, 0)), 0.01)
#self.car.rect.source = "right.png" # Změníme obrázek
if(state == "normal"):
Clock.unschedule(self.timer)
class MainApp(App):
def build(self):
Window.clearcolor = (1,1,1,1)
return Hra()
root = MainApp()
root.run()``
It looks like your Auto instance is nearly the size of the Hra (size_hint = (1,.9)), and your Bullet position is based on the position of the Auto instance. Your Up, Left, Right, and Down buttons are moving the Rectangle that is drawn on the Canvas, but have no effect on the actual position of the Auto instance. So your Bullet is always created at the same position (the Auto position never changes). One way to fix it is to make the Bullet position depend on the Rectangle instead. Like this:
def movebullet(self, *args):
y = self.car.rect.pos[1] # use position of Rectangle
x = self.bullet.pos[0] + 15
#self.bullet.pos = self.car.pos
self.bullet.pos = (x,y) #tahle konfiiguarce umozni jit kulce horizontalne
and
def shoot(self, keyboard, keycode):
if (keycode[1] == 'spacebar'):
with self.canvas:
Color(0, 0, 0, 1, mode="rgba")
self.bullet = Rectangle(pos= (300, 0), size=(20, 5))
# use position of Rectangle
g1 = self.car.rect.pos[0] + 15
g2 = self.car.rect.pos[1] + 15
self.bullet.pos = (g1, g2)

TypeError: start_new_game() missing 1 required positional argument: 'max_health' [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
So I have been trying to figure out why I keep getting this error, even though everything is run from my game_view.py module. Everytime I press the 1 key to start a game and test to see if the players health bar and hit points works, I get this error message. TypeError: start_new_game() missing 1 required positional argument: 'max_health'
The sad part is, is that it reffers me to the start_view which doesn't have anything to do with anything else but running the start screen so players can choose to play solo or with another player. Below is the game_view and start_view so you guys can see where I'm going wrong. I wanted to test this out so this way I can add other enemies, bosses and power-ups later, but running into this error for the past several days is hindering progress. Anyway, code for both will be below. Thanks in advance for any and all help.
start_view:
import arcade
from game_view import GameView
class StartView(arcade.View):
def on_show(self):
# This is run once when we switch to this view
arcade.set_background_color(arcade.csscolor.BLACK)
# Reset the viewport, necessary if we have a scrolling game
arcade.set_viewport(0, self.window.width, 0, self.window.height)
def on_draw(self):
# Draw this view
arcade.start_render()
line_height = 70
line_location = self.window.height - line_height * 2
arcade.draw_text("Space Defense Force",
self.window.width / 2,
line_location,
arcade.color.WHITE,
font_size=50,
anchor_x="center",
font_name="SF Atarian System")
line_location -= line_height
line_location -= line_height
arcade.draw_text("1 - Start One Player Game",
self.window.width / 2,
line_location,
arcade.color.WHITE,
font_size=20,
anchor_x="center",
font_name="SF Atarian System")
# if len(self.window.joysticks) > 1:
# color = arcade.color.WHITE
# else:
# color = arcade.color.GRAY
color = arcade.color.GRAY
line_location -= line_height
arcade.draw_text("2 - Start Two Player Game",
self.window.width / 2,
line_location,
color,
font_size=20,
anchor_x="center",
font_name="SF Atarian System")
line_location -= line_height
line_location -= line_height
color = arcade.color.WHITE
arcade.draw_text("Use joysticks to play, or arrow keys to move and number keys to fire.",
self.window.width / 2,
line_location,
color,
font_size=20,
anchor_x="center",
font_name="SF Atarian System")
def on_key_press(self, symbol: int, modifiers: int):
if symbol == arcade.key.KEY_1:
game_view = GameView()
game_view.start_new_game(1)
self.window.show_view(game_view)
elif symbol == arcade.key.KEY_2:
game_view = GameView()
game_view.start_new_game(2)
self.window.show_view(game_view)
game_view:
import random
import math
import arcade
from health import Health
from game_over_view import GameOverView
from typing import cast
from arcade.experimental.shadertoy import Shadertoy
from constants import *
from asteroid_sprite import AsteroidSprite
from ship_sprite import ShipSprite
from bullet import Bullet
from glow_line import GlowLine
from glow_ball import GlowBall
from explosion import ExplosionMaker
from glow_image_sprite import GlowImageSprite
from window import Window as window
class GameView(arcade.View):
# Main application class
def __init__(self):
super().__init__()
# Sprite lists
self.player_sprite_list = arcade.SpriteList()
self.asteroid_list = arcade.SpriteList()
self.bullet_list = arcade.SpriteList()
self.ship_life_list = arcade.SpriteList()
self.health_list = arcade.SpriteList()
# Sounds
self.laser_sound = arcade.load_sound(":resources:sounds/hurt5.wav")
self.hit_sound1 = arcade.load_sound(":resources:sounds/explosion1.wav")
self.hit_sound2 = arcade.load_sound(":resources:sounds/explosion2.wav")
self.hit_sound3 = arcade.load_sound(":resources:sounds/hit1.wav")
self.hit_sound4 = arcade.load_sound(":resources:sounds/hit2.wav")
self.dead_sound = arcade.load_sound(":resources:sounds/gameover2.wav")
self.glowball_shadertoy = Shadertoy.create_from_file(self.window.get_size(), "glow_ball.glsl")
self.glowline_shadertoy = Shadertoy.create_from_file(self.window.get_size(), "glow_line.glsl")
self.explosion_list = []
# for joystick in self.window.joysticks:
# joystick.push_handlers(self)
def start_new_game(self, player_count, max_health):
#Set up the game and initialize the variables
self.game_over = False
arcade.set_background_color(arcade.csscolor.BLACK)
# Sprite lists
self.player_sprite_list = arcade.SpriteList()
self.asteroid_list = arcade.SpriteList()
self.bullet_list = arcade.SpriteList()
self.ship_life_list = arcade.SpriteList()
self.health_list = arcade.SpriteList()
# if len(self.window.joysticks) > 0:
# joystick = self.window.joysticks[0]
# else:
# joystick = None
joystick = None
player_sprite = ShipSprite(":resources:images/space_shooter/playerShip1_orange.png",
SCALE,
joystick,
player_no=1,
player_count=player_count,
max_health=5)
self.player_sprite_list.append(player_sprite)
self.health_list.append(max_health)
if player_count > 1:
joystick = None
# if len(self.window.joysticks) > 1:
# joystick = self.window.joysticks[1]
# else:
# joystick = None
player_sprite = ShipSprite(":resources:images/space_shooter/playerShip1_green.png",
SCALE,
joystick,
player_no=2,
player_count=player_count,
max_health=5
)
self.player_sprite_list.append(player_sprite)
self.health_list.append(max_health)
# Set up the player
for player in self.player_sprite_list:
player.score = 0
player.lives = 3
# Set up the little icons that represent the player lives.
cur_pos = 10
for i in range(self.player_sprite_list[0].lives):
life = arcade.Sprite(":resources:images/space_shooter/playerLife1_orange.png", SCALE)
life.center_x = cur_pos + life.width
life.center_y = life.height
cur_pos += life.width
self.ship_life_list.append(life)
if len(self.player_sprite_list) > 1:
cur_pos = 100
for i in range(self.player_sprite_list[1].lives):
life = arcade.Sprite(":resources:images/space_shooter/playerLife1_green.png", SCALE)
life.center_x = cur_pos + life.width
life.center_y = life.height
cur_pos += life.width
self.ship_life_list.append(life)
# Make the asteroids
image_list = (":resources:images/space_shooter/meteorGrey_big1.png",
":resources:images/space_shooter/meteorGrey_big2.png",
":resources:images/space_shooter/meteorGrey_big3.png",
":resources:images/space_shooter/meteorGrey_big4.png")
for i in range(STARTING_ASTEROID_COUNT):
image_no = random.randrange(4)
enemy_sprite = AsteroidSprite(image_list[image_no], SCALE)
enemy_sprite.guid = "Asteroid"
enemy_sprite.center_y = random.randrange(BOTTOM_LIMIT, TOP_LIMIT)
enemy_sprite.center_x = random.randrange(LEFT_LIMIT, RIGHT_LIMIT)
enemy_sprite.change_x = random.random() * 2 - 1
enemy_sprite.change_y = random.random() * 2 - 1
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 4
self.asteroid_list.append(enemy_sprite)
def on_draw(self):
# Render the screen.
# This command has to happen before we start drawing
arcade.start_render()
# Draw all the sprites.
self.asteroid_list.draw()
self.ship_life_list.draw()
for bullet in self.bullet_list:
bullet.draw()
self.bullet_list.draw()
for explosion in self.explosion_list:
explosion.render()
self.player_sprite_list.draw()
self.health_list.draw()
# Put the text on the screen.
output = f"Player 1 Score: {self.player_sprite_list[0].score}"
arcade.draw_text(output, 10, 40, arcade.color.AMBER,
font_size=15,
font_name="Arcade")
if len(self.player_sprite_list) > 1:
output = f"Player 2 Score: {self.player_sprite_list[1].score}"
arcade.draw_text(output, 500, 40, arcade.color.AMBER,
font_size=15,
font_name="Arcade")
output = f"Asteroid Count: {len(self.asteroid_list)}"
arcade.draw_text(output, 10, 80, arcade.color.AMBER,
font_size=15,
font_name="Arcade")
for player in health_list:
player.draw_health_number()
player.draw_health_bar()
# def on_joybutton_press(self, joystick, button):
# # What player is this?
# if joystick == self.window.joysticks[0]:
# player_sprite = self.player_sprite_list[0]
# else:
# player_sprite = self.player_sprite_list[1]
# if player_sprite.player_no == 1:
# color = 255, 128, 128
# else:
# color = 128, 255, 128
# if button == 0:
# self.fire_circle(color, player_sprite, player_no=player_sprite.player_no)
# elif button == 1:
# self.fire_line(color, player_sprite, player_no=player_sprite.player_no)
# elif button == 2:
# bullet_sprite = GlowImageSprite(":resources:images/space_shooter/laserBlue01.png",
# SCALE,
# glowcolor=arcade.color.WHITE,
# shadertoy=self.glowball_shadertoy,
# player_no=player_sprite.player_no)
# self.set_bullet_vector(bullet_sprite, 10, player_sprite)
# arcade.play_sound(self.laser_sound)
def on_key_press(self, symbol, modifiers):
# Shoot if the player hit the space bar and we aren't respawning.
if symbol == arcade.key.LEFT:
self.player_sprite_list[0].change_angle = 3
elif symbol == arcade.key.RIGHT:
self.player_sprite_list[0].change_angle = -3
elif symbol == arcade.key.UP:
self.player_sprite_list[0].thrust = 0.15
elif symbol == arcade.key.DOWN:
self.player_sprite_list[0].thrust = -.2
elif symbol == arcade.key.KEY_1:
color = (255, 128, 128)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_2:
color = (128, 255, 128)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_3:
color = (128, 128, 255)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_4:
color = (255, 128, 255)
self.fire_circle(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_5:
color = (255, 255, 255)
self.fire_line(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_6:
color = (64, 255, 64)
self.fire_line(color, self.player_sprite_list[0], player_no=0)
elif symbol == arcade.key.KEY_7:
bullet_sprite = GlowImageSprite(":resources:images/space_shooter/laserBlue01.png",
SCALE,
glowcolor=arcade.color.WHITE,
shadertoy=self.glowball_shadertoy,
player_no=0)
self.set_bullet_vector(bullet_sprite, 13, self.player_sprite_list[0])
arcade.play_sound(self.laser_sound)
def fire_circle(self, bullet_color, player_sprite, player_no):
bullet_sprite = GlowBall(glowcolor=bullet_color,
radius=5,
shadertoy=self.glowball_shadertoy,
player_no=player_no)
self.set_bullet_vector(bullet_sprite, 5, player_sprite)
arcade.play_sound(self.laser_sound)
def fire_line(self, bullet_color, player_sprite, player_no):
bullet_sprite = GlowLine(glowcolor=bullet_color,
shadertoy=self.glowline_shadertoy,
player=player_sprite,
player_no=player_no)
self.set_bullet_vector(bullet_sprite, 13, player_sprite)
arcade.play_sound(self.laser_sound)
def set_bullet_vector(self, bullet_sprite, bullet_speed, player_sprite):
bullet_sprite.change_y = \
math.cos(math.radians(player_sprite.angle)) * bullet_speed
bullet_sprite.change_x = \
-math.sin(math.radians(player_sprite.angle)) \
* bullet_speed
bullet_sprite.center_x = player_sprite.center_x
bullet_sprite.center_y = player_sprite.center_y
self.bullet_list.append(bullet_sprite)
def on_key_release(self, symbol, modifiers):
# Called whenever a key is released
if symbol == arcade.key.LEFT:
self.player_sprite_list[0].change_angle = 0
elif symbol == arcade.key.RIGHT:
self.player_sprite_list[0].change_angle = 0
elif symbol == arcade.key.UP:
self.player_sprite_list[0].thrust = 0
elif symbol == arcade.key.DOWN:
self.player_sprite_list[0].thrust = 0
def split_asteroid(self, asteroid: AsteroidSprite):
# Split an asteroid into chunks
x = asteroid.center_x
y = asteroid.center_y
if asteroid.size == 4:
for i in range(3):
image_no = random.randrange(2)
image_list = [":resources:images/space_shooter/meteorGrey_med1.png",
":resources:images/space_shooter/meteorGrey_med2.png"]
enemy_sprite = AsteroidSprite(image_list[image_no],
SCALE * 1.5)
enemy_sprite.center_y = y
enemy_sprite.center_x = x
enemy_sprite.change_x = random.random() * 2.5 - 1.25
enemy_sprite.change_y = random.random() * 2.5 - 1.25
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 3
self.asteroid_list.append(enemy_sprite)
self.hit_sound1.play()
elif asteroid.size == 3:
for i in range(3):
image_no = random.randrange(2)
image_list = [":resources:images/space_shooter/meteorGrey_small1.png",
":resources:images/space_shooter/meteorGrey_small2.png"]
enemy_sprite = AsteroidSprite(image_list[image_no],
SCALE * 1.5)
enemy_sprite.center_y = y
enemy_sprite.center_x = x
enemy_sprite.change_x = random.random() * 3 - 1.5
enemy_sprite.change_y = random.random() * 3 - 1.5
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 2
self.asteroid_list.append(enemy_sprite)
self.hit_sound2.play()
elif asteroid.size == 2:
for i in range(3):
image_no = random.randrange(2)
image_list = [":resources:images/space_shooter/meteorGrey_tiny1.png",
":resources:images/space_shooter/meteorGrey_tiny2.png"]
enemy_sprite = AsteroidSprite(image_list[image_no],
SCALE * 1.5)
enemy_sprite.center_y = y
enemy_sprite.center_x = x
enemy_sprite.change_x = random.random() * 3.5 - 1.75
enemy_sprite.change_y = random.random() * 3.5 - 1.75
enemy_sprite.change_angle = (random.random() - 0.5) * 2
enemy_sprite.size = 1
self.asteroid_list.append(enemy_sprite)
self.hit_sound3.play()
elif asteroid.size == 1:
self.hit_sound4.play()
def on_update(self, x, delta_time):
# Move everything
self.asteroid_list.update()
self.bullet_list.update()
self.player_sprite_list.update()
self.health_list.update()
explosion_list_copy = self.explosion_list.copy()
for explosion in explosion_list_copy:
explosion.update(x)
if explosion.time > .9:
self.explosion_list.remove(explosion)
for bullet in self.bullet_list:
hit_list = arcade.check_for_collision_with_list(bullet, self.player_sprite_list)
# If it did hit, get rid of sprite
if len(hit_list) > 0:
bullet.remove_from_lists()
for player in hit_list:
if not isinstance(player, ShipSprite):
raise TypeError("List contents must be all ints")
# Remove one health point
player.cur_health -= 1
# Check Health
if player.cur_health <= 0:
arcade.play_sound(self.dead_sound)
view=GameOverView
self.window.show_view(view)
else:
# Not Dead
arcade.play_sound(self.hit_sound1)
assert isinstance(bullet, Bullet)
asteroids = arcade.check_for_collision_with_list(bullet, self.asteroid_list)
if len(asteroids) > 0:
explosion = ExplosionMaker(self.window.get_size(), bullet.position)
self.explosion_list.append(explosion)
for asteroid in asteroids:
assert isinstance(asteroid, AsteroidSprite)
self.player_sprite_list[bullet.player_no - 1].score += 1
self.split_asteroid(cast(AsteroidSprite, asteroid)) # expected AsteroidSprite, got Sprite instead
asteroid.remove_from_sprite_lists()
bullet.remove_from_sprite_lists()
# Remove bullet if it goes off-screen
size = max(bullet.width, bullet.height)
if bullet.center_x < 0 - size:
bullet.remove_from_sprite_lists()
if bullet.center_x > SCREEN_WIDTH + size:
bullet.remove_from_sprite_lists()
if bullet.center_y < 0 - size:
bullet.remove_from_sprite_lists()
if bullet.center_y > SCREEN_HEIGHT + size:
bullet.remove_from_sprite_lists()
for player in self.player_sprite_list:
assert isinstance(player, ShipSprite, max_health)
if not player.respawning:
asteroids = arcade.check_for_collision_with_list(player, self.asteroid_list)
if len(asteroids) > 0:
if player.lives > 0:
player.lives -= 1
player.respawn()
self.split_asteroid(cast(AsteroidSprite, asteroids[0]))
asteroids[0].remove_from_sprite_lists()
self.ship_life_list.pop().remove_from_sprite_lists()
elif len(asteroids) > 0:
if player.health > 0:
player.health -=1
player.respawn()
self.split_asteroid(cast(AsteroidSprite, asteroids[0]))
asteroids[0].remove_from_sprite_lists()
self.ship_list_list.pop().remove_from_sprite_lists()
else:
arcade.play_sound(self.dead_sound)
view = GameOverView()
self.window.show_view(view)
Sorry in advance if I have tons of code to go through. But like I said I am adding some features that wasn't in the Arcade Repository from github. I even set a separte module for the health bar and hit points so this way I can see what conflicts. But the error above has been a royal pain.Thanks again.
P.S. Remarked out joysticks because it was conflicting with another module I built.
As your title says, your start game function requires 2 arguments: player_count and max_healh. And in your code, when using start_new_game, you aren't supplying the max_health argument, thus raising an error.
(function) start_new_game(self, player_count, max_health)

Putting the scrolling camera in a mini-window in pygame

I'm trying to create a game where the action is shown in a little box within the main screen object, freeing up the surrounding space for text and menus and what-not. Since the map is larger than the allotted window, I coded a basic "camera" that follows the player around. It mostly works, but I'm having trouble "trimming off" the area outside of this window.
Here's the relevant bits of code (EDITED to provide Working Example):
import pygame, os, sys
from pygame.locals import *
pygame.init()
RIGHT = 'RIGHT'
LEFT = 'LEFT'
UP = 'UP'
DOWN = 'DOWN'
class Camera():
def __init__(self, screen, x_ratio = 1, y_ratio = 1, x_offset = 0, y_offset = 0):
self.screen = screen.copy()
self.rec = self.screen.get_rect()
self.rec.width *= x_ratio
self.rec.height *= y_ratio
self.x_offset = x_offset
self.y_offset = y_offset
def get_pos(self):
return (self.x_offset - self.rec.x, self.y_offset - self.rec.y)
def get_window(self):
w = pygame.Rect(self.rec)
w.topleft = (0 - self.rec.x, 0 - self.rec.y)
return w
def move(self, x, y):
"""Move camera into new position"""
self.rec.x = x
self.rec.y = y
def track(self, obj):
while obj.rec.left < self.rec.left:
self.rec.x -= 1
while obj.rec.right > self.rec.right:
self.rec.x += 1
while obj.rec.top < self.rec.top:
self.rec.y -= 1
while obj.rec.bottom > self.rec.bottom:
self.rec.y += 1
class Map:
def __init__(self, width, height):
self.width = width
self.height = height
self.rec = pygame.Rect(0,0,self.width,self.height)
def draw(self, screen):
pygame.draw.rect(screen, (200,200,200), self.rec)
class Obj:
def __init__(self, char, x = 0, y = 0, width = 0, height = 0):
self.width = width
self.height = height
self.rec = pygame.Rect(x, y, width, height)
self.cur_map = None
self.timers = {}
#Dummying in chars for sprites
self.char = char
self.x_dir = 1
self.y_dir = 1
self.speed = 1
self.moving = False
def move(self):
if self.x_dir != 0 or self.y_dir != 0:
new_x = self.rec.x + (self.x_dir*self.speed)
new_y = self.rec.y + (self.y_dir*self.speed)
new_rec = pygame.Rect(new_x, new_y, self.width, self.height)
#Keep movement within bounds of map
while new_rec.left < self.cur_map.rec.left:
new_rec.x += 1
while new_rec.right > self.cur_map.rec.right:
new_rec.x -= 1
while new_rec.top < self.cur_map.rec.top:
new_rec.y += 1
while new_rec.bottom > self.cur_map.rec.bottom:
new_rec.y -= 1
self.rec = new_rec
def set_dir(self, d):
self.x_dir = 0
self.y_dir = 0
if d == LEFT:
self.x_dir = -1
elif d == RIGHT:
self.x_dir = 1
elif d == UP:
self.y_dir = -1
elif d == DOWN:
self.y_dir = 1
def set_moving(self, val = True):
self.moving = val
class Game:
def __init__(self):
self.screen_size = (800, 600)
self.screen = pygame.display.set_mode(self.screen_size)
self.map_screen = self.screen.copy()
self.title = 'RPG'
pygame.display.set_caption(self.title)
self.camera = Camera(self.screen, 0.75, 0.75)#, 10, 75)
self.fps = 80
self.clock = pygame.time.Clock()
self.debug = False
self.bg_color = (255,255,255)
self.text_size = 18
self.text_font = 'Arial'
self.text_style = pygame.font.SysFont(self.text_font, self.text_size)
self.key_binds = {LEFT : [K_LEFT, K_a], RIGHT : [K_RIGHT, K_d], UP : [K_UP, K_w], DOWN : [K_DOWN, K_s],
'interact' : [K_RETURN, K_z], 'inventory' : [K_i, K_SPACE], 'quit' : [K_ESCAPE]}
self.player = Obj('p', 0, 0, 10, self.text_size)
def draw(self, obj):
char = obj.char
self.draw_text(char, obj.rec.x, obj.rec.y, screen = self.map_screen)
def draw_text(self, text, x, y, color = (0,0,0), screen = None):
textobj = self.text_style.render(text, 1, color)
textrect = textobj.get_rect()
textrect.x = x
textrect.y = y
if screen == None:
"""Use default screen"""
self.screen.blit(textobj, textrect)
else:
screen.blit(textobj, textrect)
def play(self):
done = False
cur_map = Map(800, 800)
self.map_screen = pygame.Surface((cur_map.width, cur_map.height))
self.map_screen.fill(self.bg_color)
bg = pygame.Surface((cur_map.width, cur_map.height))
cur_map.draw(bg)
self.player.cur_map = cur_map
while not done:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key in self.key_binds[LEFT]:
self.player.set_dir(LEFT)
self.player.set_moving()
elif event.key in self.key_binds[RIGHT]:
self.player.set_dir(RIGHT)
self.player.set_moving()
elif event.key in self.key_binds[UP]:
self.player.set_dir(UP)
self.player.set_moving()
elif event.key in self.key_binds[DOWN]:
self.player.set_dir(DOWN)
self.player.set_moving()
elif event.type == KEYUP:
self.player.set_moving(False)
if self.player.moving:
self.player.move()
self.camera.track(self.player)
self.clock.tick()
self.screen.fill(self.bg_color)
self.map_screen.blit(bg, (0,0))
self.draw(self.player)
pygame.draw.rect(self.map_screen, (0,0,0), self.camera.rec, 1)
#self.screen.blit(self.map_screen, (0,0), [0 - self.camera.rec.x, 0 - self.camera.rec.y, self.camera.rec.width, self.camera.rec.height])
self.screen.blit(self.map_screen, self.camera.get_pos(), self.camera.get_window())
pygame.display.flip()
game = Game()
game.play()
Moving the player past past the bounds of the camera's window causes the window to roll up completely and disappear. I tried adjusting the blitting coordinates, as advised earlier, but it seems to only change the direction in which the window rolls up.
From your updated code, the blitting coordinates for self.screen.blit(...) are still changing: self.camera.get_window() changes value because rec.x and rec.y are values referring to the player position within the map. Hence you should define a constant minimap coordinate, this should be the same as the camera offset.
self.screen.blit(self.map_screen, (self.camera.x_offset,self.camera.y_offset), (*self.camera.get_pos(), self.camera.rec.width, self.camera.rec.height))
Change the Camera().get_pos() to:
def get_pos(self):
return (self.rec.x, self.rec.y)
I believe I only changed the self.screen.blit(...) and stopped using or rewrote your Camera functions as you're confusing yourself with all the rec variables.
To illustrate it working amend the Map().draw(screen) to:
def draw(self, screen):
pygame.draw.rect(screen, (200,200,200), self.rec)
pygame.draw.circle(screen, (255, 255, 255), (50, 50), 20, 2)
One tip as well don't draw the entire map at each loop, just the part that will be visible.

How to make a mouse click do something at a specific point?

how can I make the mouse do something once it's clicking at a certain point in Zelle's graphics? What I am trying to do is make my stopwatch start when I click the "startbutton" image. However, I am obviously doing something wrong because my program either crashes or doesn't do anything.
from graphics import *
import time
#from tkinter import *
win = GraphWin('Stopwatch', 600, 600)
win.yUp()
#Assigning images
stopWatchImage = Image(Point (300, 300), "stopwatch.png")
startImage = Image(Point (210, 170), "startbutton.png")
stopImage = Image(Point (390, 170), "stopbutton.png")
lapImage = Image(Point (300, 110), "lapbutton.png")
stopWatchImage.draw(win)
startImage.draw(win)
stopImage.draw(win)
lapImage.draw(win)
sec = 0
minute = 0
hour = 0
def isBetween(x, end1, end2):
'''Return True if x is between the ends or equal to either.
The ends do not need to be in increasing order.'''
return end1 <= x <= end2 or end2 <= x <= end1
def isInside(point, startImage):
'''Return True if the point is inside the Rectangle rect.'''
pt1 = startImage.getP1()
pt2 = startImage.getP2()
return isBetween(point.getX(), pt1.getX(), pt2.getX()) and \
isBetween(point.getY(), pt1.getY(), pt2.getY())
def getChoice(win): #NEW
'''Given a list choicePairs of tuples with each tuple in the form
(rectangle, choice), return the choice that goes with the rectangle
in win where the mouse gets clicked, or return default if the click
is in none of the rectangles.'''
point = win.getMouse()
if isInside(point, startImage):
time.sleep(1)
sec += 1
timeText.setText(sec)
timeText.setText('')
while sec >= 0 and sec < 61:
#Displaying Time
timeText = Text(Point (300,260), str(hour) + ":" + str(minute) + ":" + str(sec))
timeText.setSize(30)
timeText.draw(win)
time.sleep(1)
sec += 1
timeText.setText(sec)
timeText.setText('')
#Incrementing minutes,hours
if sec == 60:
sec = 0
minute += 1
if minute == 60:
sec = 0
minute = 0
hour += 1
return default
def layout()
getChoice(win)
layout()
I can't seem to get it to work.
Edit: added the rest of my code for clarification.
You can use setMouseHandler to assign function which will called when you click in window.
In example if you click in left part of window then it draws rectangle, if you click in right part of window then it draws circle.
You can open file graphics.py and see all code. It is the fastest method to can see what functions you can use.
from graphics import *
# --- functions ---
def on_click(point):
# inform function to use global variable
global win
if point.x > win.width//2:
c = Circle(point, 10)
c.draw(win)
else:
a = Point(point.x - 10, point.y - 10)
b = Point(point.x + 10, point.y + 10)
r = Rectangle(a, b)
r.draw(win)
def main():
# inform function to use global variable
global win
win = GraphWin("My Circle", 500, 500)
win.setMouseHandler(on_click)
win.getKey()
win.close()
# --- start ---
# create global variable
win = None
main()
BTW: graphics uses Tkinter which has widgets Button, Label, Text, etc. It can use canvas.create_window() to add widget to canvas.
Tkinter has also function after(miliseconds, function_name) which lets you execute function periodically - ie. to update time.
Example
from graphics import *
import datetime
# --- classes ---
class _Widget():
def __init__(self, x, y, w, h, **options):
self.x = x
self.y = y
self.w = w
self.h = h
self.options = options
def draw(self, canvas, **options):
return None
def set(self, **options):
self.widget.config(options)
def get(self, **options):
self.widget.cget(options)
class Button(_Widget):
def draw(self, canvas, **options):
x, y = canvas.toScreen(self.x, self.y) # ???
self.widget = tk.Button(canvas, self.options)
return canvas.create_window((x, y), options, width=self.w, height=self.h, window=self.widget, anchor='nw')
class Label(_Widget):
def draw(self, canvas, **options):
x, y = canvas.toScreen(self.x, self.y) # ???
self.widget = tk.Label(canvas, self.options)
return canvas.create_window((x, y), options, width=self.w, height=self.h, window=self.widget, anchor='nw')
# --- functions ---
def on_start():
#global b1, b2
global running
b1.set(state='disabled')
b2.set(state='normal')
running = True
# run first time
update_time()
print("START")
def on_stop():
#global b1, b2
global running
b1.set(state='normal')
b2.set(state='disabled')
l.set(text="Controls:")
running = False
print("STOP")
def update_time():
#global l
#global running
if running:
l.set(text=datetime.datetime.now().strftime("%H:%M:%S"))
# run again after 1000ms (1s)
win.after(1000, update_time)
# --- main ---
def main():
global win, l, b1, b2
win = GraphWin("My Buttons", 500, 500)
l = Label(0, 0, 100, 50, text="Controls:")
l.draw(win)
b1 = Button(100, 0, 100, 50, text="START", command=on_start)
b1.draw(win)
b2 = Button(200, 0, 100, 50, text="STOP", command=on_stop, state='disabled')
b2.draw(win)
win.getKey()
win.close()
# --- global variable to access in functions ---
win = None
l = None
b1 = None
b2 = None
running = False
# --- start ---
main()
Tkinter: Canvas, Button, other
EDIT: working example
from graphics import *
def isBetween(x, end1, end2):
return end1 <= x <= end2 or end2 <= x <= end1
def isInside(point, startImage):
x = startImage.getAnchor().getX()
y = startImage.getAnchor().getY()
w = startImage.getWidth()/2
h = startImage.getHeight()/2
pt1_x = x - w
pt1_y = y - h
pt2_x = x + w
pt2_y = y + h
return isBetween(point.getX(), pt1_x, pt2_x) and \
isBetween(point.getY(), pt1_y, pt2_y)
def getChoice(event):
global hour, minute, sec
global running
point = Point(round(event.x), round(event.y))
if isInside(point, startImage):
sec = 0
minute = 0
hour = 0
running = True
update_time()
if isInside(point, stopImage):
running = False
def update_time():
global hour, minute, sec
#global timeText
#global win
sec += 1
if sec == 60:
sec = 0
minute += 1
if minute == 60:
minute = 0
hour += 1
timeText.setText('{}:{}:{}'.format(hour, minute, sec))
if running:
win.after(1000, update_time)
else:
timeText.setText('')
def layout():
global win
global stopWatchImage
global startImage
global stopImage
global lapImage
global timeText
win = GraphWin('Stopwatch', 600, 600)
#win.yUp()
#Assigning images
stopWatchImage = Image(Point(300, 300), "stopwatch.png")
startImage = Image(Point(210, 170), "startbutton.png")
stopImage = Image(Point(390, 170), "stopbutton.png")
lapImage = Image(Point(300, 110), "lapbutton.png")
#Drawing images
stopWatchImage.draw(win)
startImage.draw(win)
stopImage.draw(win)
lapImage.draw(win)
timeText = Text(Point(300,260), '')
timeText.setSize(30)
timeText.draw(win)
win.setMouseHandler(getChoice)
win.getKey()
# --- global variable ---
win = None
stopWatchImage = None
startImage = None
stopImage = None
lapImage = None
timeText = None
running = False
# --- start ---
layout()

moving an object in a circular path [duplicate]

This question already has answers here:
Why it doesn't spin in a circle? And how to fix it?
(1 answer)
Ship moves up and left faster than down and right when rotating in pygame
(1 answer)
Closed 2 years ago.
This question is related to
My code is below. You can use any small image for my images.
import sys, os, pygame, itertools
from math import sin,cos,pi, radians
from pygame.locals import *
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (50,50) #Set window position
pygame.init()
clock = pygame.time.Clock()
FPS = 1000
SCREENW = 800 #screen width
SCREENH = 740 #screen height
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
ORANGE = (128, 100, 30)
FONT1= "Cookie-Regular.ttf"
SCREEN = pygame.display.set_mode((SCREENW, SCREENH), 0, 32) #display screen
clock = pygame.time.Clock()
#-------------------------------------------------------------------------------
def maketext(msg,fontsize, colour = ORANGE, font = FONT1):
mafont = pygame.font.Font(font, fontsize)
matext = mafont.render(msg, True, colour)
matext = matext.convert_alpha()
return matext
#-------------------------------------------------------------------------------
def print_info():
""""""
textcos = maketext(str(round(obj.rect.x, 2)) + " " + str(round(obj.rect.y, 2)), 30)
SCREEN.blit(textcos, (obj.rect.x, obj.rect.y + 30))
#-------------------------------------------------------------------------------
class object_factory(pygame.sprite.Sprite):
def __init__(self, imagelist, xpos, ypos, speedx = 0, speedy = 0, value = 0):
"""Constructor"""
pygame.sprite.Sprite.__init__(self)
self.name = ""
self.frame = 0
self.imagelist = imagelist
self.image = imagelist[self.frame]
self.mask = pygame.mask.from_surface(self.image) # pixelmask
self.rect = self.image.get_rect()
self.rect.x = xpos
self.rect.y = ypos
#self.speedx = speedx
#self.speedy = speedy
self.timer = 0
self.timerlimit = 10
#----------------------------------------------------------------------
#def move(self): # wallsprites, Herosprite, looptime
#self.rect.x += self.speedx
#self.rect.y += self.speedy
#----------------------------------------------------------------------
def update(self):
""""""
self.image = self.imagelist[self.frame]
if self.timer >= self.timerlimit:
self.frame += 1
if self.frame >= len(self.imagelist):
self.frame = 0
self.timer = 0
self.timer += 1
plat = pygame.image.load("plt0.png").convert_alpha()
star = pygame.image.load("gemp0.png").convert_alpha()
#box = pygame.image.load("crateB.png").convert_alpha()
platforms = pygame.sprite.Group()
boxes = pygame.sprite.Group()
rotcenx = SCREENW/2
rotceny = SCREENH/2
radius = 200
angle = radians(90) #pi/4 # starting angle 45 degrees
omega = radians(5) #Angular velocity
m = rotcenx + radius * cos(angle) #Starting position x
n = rotceny - radius * sin(angle) #Starting position y
for _ in itertools.repeat(None, 1):
madyax = SCREENW/2
madyay = SCREENH/2
araya = 200
konaya = radians(180) #pi/4 # starting angle 45 degrees
konika_pravegaya = radians(5) #Angular velocity
a = madyax + (araya * cos(konaya)) #Starting position x
b = madyay - (araya * sin(konaya)) #Startinh position y
plat = object_factory([plat], a, b)
plat.araya = araya
plat.konaya = konaya
plat.kp = konika_pravegaya
platforms.add(plat)
while True:
ms = clock.tick(FPS) # milliseconds passed since last frame
#looptime = milliseconds / 1000.0 # seconds passed since last frame
SCREEN.fill((BLACK))
pygame.draw.circle(SCREEN, BLUE, (SCREENW / 2, SCREENH / 2), 5)
##-----------------------------------------------------------
SCREEN.blit(star, (m, n)) # Draw current x,y
angle = angle + omega # New angle, we add angular velocity
m = m + radius * omega * cos(angle + pi / 2) # New x
n = n - radius * omega * sin(angle + pi / 2) # New y
##-----------------------------------------------------------
# show object anchored to center of rotation
pygame.draw.line(SCREEN, ORANGE, (rotcenx, rotceny), (m, n))
text = maketext(str(radius), 30)
SCREEN.blit(text, (m, n - 40))
text = maketext((str(round(m, 2)) + " " + str(round(n, 2))), 30)
SCREEN.blit(text, (m, n + 40)) # Draw current x,y
##------------------------------------------------------------------
for plat in platforms:
plat.konaya = plat.konaya + plat.kp
plat.rect.x = plat.rect.x + plat.araya * plat.kp * cos(plat.konaya + pi / 2)
plat.rect.y = plat.rect.y - plat.araya * plat.kp * sin(plat.konaya + pi / 2)
##------------------------------------------------------------------------
pygame.draw.line(SCREEN, ORANGE, (madyax, madyay), (plat.rect.x, plat.rect.y))
platforms.update()
platforms.draw(SCREEN)
pygame.event.pump()
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
pygame.display.update()
pygame.time.wait(100)
Why does the code work when used outside a class and NOT when in? I simply can't find what I have done wrong.
Please don't ask me to read any Google documents or search on the Internet as I am posting after doing so and NOT finding an answer to my question. I am NOT an expert in math and would only like to know a solution to this problem. Please help.
Link to video is below
http://youtu.be/0oRDX246aj8

Categories