SlideShare a Scribd company logo
1 of 4
Download to read offline
Please fix pygame code so that the first "Enemy" bounces off the walls of the screen. Thank
You.
import pygame
import sys
import math
import random
def pixel_collision(mask1, rect1, mask2, rect2):
offset_x = rect2[0] - rect1[0]
offset_y = rect2[1] - rect1[1]
overlap = mask1.overlap(mask2, (offset_x, offset_y))
return overlap
class Sprite:
def __init__(self, image, x, y):
self.image = image
self.rectangle = image.get_rect()
self.rectangle.center = (x, y)
self.mask = pygame.mask.from_surface(image)
def set_position(self, new_position):
self.rectangle.center = new_position
def draw(self, screen):
screen.blit(self.image, self.rectangle)
def is_colliding(self, other_sprite):
return pixel_collision(self.mask, self.rectangle, other_sprite.mask, other_sprite.rectangle)
class Enemy(Sprite):
def __init__(self, image, width, height):
super().__init__(image, width, height)
self.rectangle.centerx = random.randint(0, width)
self.rectangle.centery = random.randint(0, height)
vx = random.uniform(-1, 1)
vy = random.uniform(-1, 1)
self.speed = (vx, vy)
def move(self):
self.rectangle.move_ip(self.speed)
def bounce(self, width, height):
if self.rectangle.left < 0 or self.rectangle.right > width:
self.speed = (-self.speed[0], self.speed[1])
if self.rectangle.top < 0 or self.rectangle.bottom > height:
self.speed = (self.speed[0], -self.speed[1])
class Enemy2(Sprite):
def __init__(self, image, width, height):
super().__init__(image, width, height)
self.speed = (0, 0)
self.acceleration = 0.1
def move(self, target_position):
dx = target_position[0] - self.rectangle.centerx
dy = target_position[1] - self.rectangle.centery
dist = math.sqrt(dx ** 2 + dy ** 2)
if dist != 0:
dx_norm = dx / dist
dy_norm = dy / dist
self.speed = (self.speed[0] + dx_norm * self.acceleration, self.speed[1] + dy_norm *
self.acceleration)
self.rectangle.move_ip(self.speed[0], self.speed[1])
class PowerUp(Sprite):
def __init__(self, image, width, height):
super().__init__(image, width, height)
def main():
pygame.init()
myfont = pygame.font.SysFont('monospace', 24)
width, height = 600, 400
screen = pygame.display.set_mode((width, height))
enemy1 = pygame.image.load("devil.png").convert_alpha()
enemy2 = pygame.image.load("ghost.png").convert_alpha()
enemy1_image = pygame.transform.smoothscale(enemy1, (50, 50))
enemy2_image = pygame.transform.smoothscale(enemy2, (50, 50))
enemy_sprites = []
enemy2_sprites = []
for i in range(5):
enemy_sprites.append(Enemy(enemy1_image, width, height))
for i in range(2):
enemy2_sprites.append(Enemy2(enemy2_image, width, height))
player_image = pygame.image.load("prayerhands.jpeg").convert_alpha()
player_image = pygame.transform.scale(player_image, (50, 50))
x, y = 0, 0
player_sprite = Sprite(player_image, x, y)
life = 3
powerup_image = pygame.image.load("life_powerup.jpeg").convert_alpha()
powerups = []
is_playing = True
clock = pygame.time.Clock()
while is_playing:
clock.tick(60)
if life <= 0:
is_playing = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_playing = False
pos = pygame.mouse.get_pos()
player_sprite.set_position(pos)
for enemy_sprite in enemy_sprites:
if player_sprite.is_colliding(enemy_sprite):
life -= 0.2
for powerup_sprite in powerups:
if player_sprite.is_colliding(powerup_sprite):
life += 1
powerups = [p for p in powerups if not player_sprite.is_colliding(p)]
for enemy_sprite in enemy_sprites:
enemy_sprite.move()
enemy_sprite.bounce(width, height)
for enemy2_sprite in enemy2_sprites:
enemy2_sprite.move(player_sprite.rectangle.center)
if random.random() < 0.01:
powerups.append(PowerUp(powerup_image, random.randint(0, width),
random.randint(0, height)))
screen.fill((255, 255, 255))
for enemy_sprite in enemy_sprites:
enemy_sprite.draw(screen)
for enemy2_sprite in enemy2_sprites:
enemy2_sprite.draw(screen)
for powerup_sprite in powerups:
powerup_sprite.draw(screen)
player_sprite.draw(screen)
text = "Life: " + str('%.1f' % life)
label = myfont.render(text, True, (0, 0, 0))
screen.blit(label, (20, 20))
pygame.display.update()
pygame.time.wait(2000)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()

More Related Content

Similar to Please fix pygame code so that the first Enemy bounces off the wal.pdf

Using the code below- I need help with the following 3 things- 1) Writ.pdf
Using the code below- I need help with the following 3 things- 1) Writ.pdfUsing the code below- I need help with the following 3 things- 1) Writ.pdf
Using the code below- I need help with the following 3 things- 1) Writ.pdfacteleshoppe
 
You are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdfYou are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdfsales223546
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfactexerode
 
Modify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdfModify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdfarorastores
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconftutorialsruby
 
Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"Fwdays
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScriptSam Cartwright
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212Mahmoud Samir Fayed
 
Particle Filter Tracking in Python
Particle Filter Tracking in PythonParticle Filter Tracking in Python
Particle Filter Tracking in PythonKohta Ishikawa
 

Similar to Please fix pygame code so that the first Enemy bounces off the wal.pdf (20)

Using the code below- I need help with the following 3 things- 1) Writ.pdf
Using the code below- I need help with the following 3 things- 1) Writ.pdfUsing the code below- I need help with the following 3 things- 1) Writ.pdf
Using the code below- I need help with the following 3 things- 1) Writ.pdf
 
You are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdfYou are task to add a yawning detection to the programme below;i.pdf
You are task to add a yawning detection to the programme below;i.pdf
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
 
Scmad Chapter07
Scmad Chapter07Scmad Chapter07
Scmad Chapter07
 
Modify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdfModify the following source code so that when the mouse is clicked w.pdf
Modify the following source code so that when the mouse is clicked w.pdf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
building_games_with_ruby_rubyconf
building_games_with_ruby_rubyconfbuilding_games_with_ruby_rubyconf
building_games_with_ruby_rubyconf
 
Of class1
Of class1Of class1
Of class1
 
Game dev 101 part 3
Game dev 101 part 3Game dev 101 part 3
Game dev 101 part 3
 
Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"Denis Sergienko "Pip install driven deep learning"
Denis Sergienko "Pip install driven deep learning"
 
Making Games in JavaScript
Making Games in JavaScriptMaking Games in JavaScript
Making Games in JavaScript
 
Factory in python
Factory in pythonFactory in python
Factory in python
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
Game age ppt
Game age pptGame age ppt
Game age ppt
 
The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212The Ring programming language version 1.10 book - Part 70 of 212
The Ring programming language version 1.10 book - Part 70 of 212
 
Particle Filter Tracking in Python
Particle Filter Tracking in PythonParticle Filter Tracking in Python
Particle Filter Tracking in Python
 
Real life XNA
Real life XNAReal life XNA
Real life XNA
 
Player x 0 y ga.docx
Player x 0 y ga.docxPlayer x 0 y ga.docx
Player x 0 y ga.docx
 
Pygame presentation
Pygame presentationPygame presentation
Pygame presentation
 
14709302.ppt
14709302.ppt14709302.ppt
14709302.ppt
 

More from amarnathmahajansport

Please ask experts to solve this in the correct way. 1. (20 point.pdf
Please ask experts to solve this in the correct way.  1. (20 point.pdfPlease ask experts to solve this in the correct way.  1. (20 point.pdf
Please ask experts to solve this in the correct way. 1. (20 point.pdfamarnathmahajansport
 
please answer this multiple choice question2.What major Department.pdf
please answer this multiple choice question2.What major Department.pdfplease answer this multiple choice question2.What major Department.pdf
please answer this multiple choice question2.What major Department.pdfamarnathmahajansport
 
please answer this multiple choice question4.This Technical Review.pdf
please answer this multiple choice question4.This Technical Review.pdfplease answer this multiple choice question4.This Technical Review.pdf
please answer this multiple choice question4.This Technical Review.pdfamarnathmahajansport
 
Please answer question in full 2.1 Security management function.pdf
Please answer question in full  2.1 Security management function.pdfPlease answer question in full  2.1 Security management function.pdf
Please answer question in full 2.1 Security management function.pdfamarnathmahajansport
 
Please answer these questions 150 words only 1) List four lines o.pdf
Please answer these questions 150 words only  1) List four lines o.pdfPlease answer these questions 150 words only  1) List four lines o.pdf
Please answer these questions 150 words only 1) List four lines o.pdfamarnathmahajansport
 
Please answer the 4 questions at the end please do all of them at th.pdf
Please answer the 4 questions at the end please do all of them at th.pdfPlease answer the 4 questions at the end please do all of them at th.pdf
Please answer the 4 questions at the end please do all of them at th.pdfamarnathmahajansport
 
Please answer the questions in orderExplain why a virus is co.pdf
Please answer the questions in orderExplain why a virus is co.pdfPlease answer the questions in orderExplain why a virus is co.pdf
Please answer the questions in orderExplain why a virus is co.pdfamarnathmahajansport
 
Please answer the questions in orderCompare and contrast Virus a.pdf
Please answer the questions in orderCompare and contrast Virus a.pdfPlease answer the questions in orderCompare and contrast Virus a.pdf
Please answer the questions in orderCompare and contrast Virus a.pdfamarnathmahajansport
 
Please answer the questions in ordarExplain the advantage for sur.pdf
Please answer the questions in ordarExplain the advantage for sur.pdfPlease answer the questions in ordarExplain the advantage for sur.pdf
Please answer the questions in ordarExplain the advantage for sur.pdfamarnathmahajansport
 
Please give a detailed summary of the article where I can write at l.pdf
Please give a detailed summary of the article where I can write at l.pdfPlease give a detailed summary of the article where I can write at l.pdf
Please give a detailed summary of the article where I can write at l.pdfamarnathmahajansport
 
Please answer the 4 questions at the end Causes and Outcomes of Co.pdf
Please answer the 4 questions at the end Causes and Outcomes of Co.pdfPlease answer the 4 questions at the end Causes and Outcomes of Co.pdf
Please answer the 4 questions at the end Causes and Outcomes of Co.pdfamarnathmahajansport
 
please help In multiple regression analysis, residuals (YY^) shou.pdf
please help  In multiple regression analysis, residuals (YY^) shou.pdfplease help  In multiple regression analysis, residuals (YY^) shou.pdf
please help In multiple regression analysis, residuals (YY^) shou.pdfamarnathmahajansport
 
please fill in the chart A company that uses job order c.pdf
please fill in the chart A company that uses job order c.pdfplease fill in the chart A company that uses job order c.pdf
please fill in the chart A company that uses job order c.pdfamarnathmahajansport
 
Please fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdfPlease fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdfamarnathmahajansport
 
Please explain fully each step and what inputs and the number of row.pdf
Please explain fully each step and what inputs and the number of row.pdfPlease explain fully each step and what inputs and the number of row.pdf
Please explain fully each step and what inputs and the number of row.pdfamarnathmahajansport
 
please explain how attaker crack 2DES and show your work. 3DES = Run.pdf
please explain how attaker crack 2DES and show your work. 3DES = Run.pdfplease explain how attaker crack 2DES and show your work. 3DES = Run.pdf
please explain how attaker crack 2DES and show your work. 3DES = Run.pdfamarnathmahajansport
 
Please explain answer choice 26. Small functionally disruptive hardw.pdf
Please explain answer choice 26. Small functionally disruptive hardw.pdfPlease explain answer choice 26. Small functionally disruptive hardw.pdf
Please explain answer choice 26. Small functionally disruptive hardw.pdfamarnathmahajansport
 
Please explain answer choice 15. Match each of the following counter.pdf
Please explain answer choice 15. Match each of the following counter.pdfPlease explain answer choice 15. Match each of the following counter.pdf
Please explain answer choice 15. Match each of the following counter.pdfamarnathmahajansport
 
Please draw an activity diagram using Enterprise. or draw using symb.pdf
Please draw an activity diagram using Enterprise. or draw using symb.pdfPlease draw an activity diagram using Enterprise. or draw using symb.pdf
Please draw an activity diagram using Enterprise. or draw using symb.pdfamarnathmahajansport
 

More from amarnathmahajansport (20)

Please ask experts to solve this in the correct way. 1. (20 point.pdf
Please ask experts to solve this in the correct way.  1. (20 point.pdfPlease ask experts to solve this in the correct way.  1. (20 point.pdf
Please ask experts to solve this in the correct way. 1. (20 point.pdf
 
please answer this multiple choice question2.What major Department.pdf
please answer this multiple choice question2.What major Department.pdfplease answer this multiple choice question2.What major Department.pdf
please answer this multiple choice question2.What major Department.pdf
 
please answer this multiple choice question4.This Technical Review.pdf
please answer this multiple choice question4.This Technical Review.pdfplease answer this multiple choice question4.This Technical Review.pdf
please answer this multiple choice question4.This Technical Review.pdf
 
Please answer question in full 2.1 Security management function.pdf
Please answer question in full  2.1 Security management function.pdfPlease answer question in full  2.1 Security management function.pdf
Please answer question in full 2.1 Security management function.pdf
 
Please answer these questions 150 words only 1) List four lines o.pdf
Please answer these questions 150 words only  1) List four lines o.pdfPlease answer these questions 150 words only  1) List four lines o.pdf
Please answer these questions 150 words only 1) List four lines o.pdf
 
Please answer the 4 questions at the end please do all of them at th.pdf
Please answer the 4 questions at the end please do all of them at th.pdfPlease answer the 4 questions at the end please do all of them at th.pdf
Please answer the 4 questions at the end please do all of them at th.pdf
 
Please answer the questions in orderExplain why a virus is co.pdf
Please answer the questions in orderExplain why a virus is co.pdfPlease answer the questions in orderExplain why a virus is co.pdf
Please answer the questions in orderExplain why a virus is co.pdf
 
Please answer the questions in orderCompare and contrast Virus a.pdf
Please answer the questions in orderCompare and contrast Virus a.pdfPlease answer the questions in orderCompare and contrast Virus a.pdf
Please answer the questions in orderCompare and contrast Virus a.pdf
 
Please answer the questions in ordarExplain the advantage for sur.pdf
Please answer the questions in ordarExplain the advantage for sur.pdfPlease answer the questions in ordarExplain the advantage for sur.pdf
Please answer the questions in ordarExplain the advantage for sur.pdf
 
Please give a detailed summary of the article where I can write at l.pdf
Please give a detailed summary of the article where I can write at l.pdfPlease give a detailed summary of the article where I can write at l.pdf
Please give a detailed summary of the article where I can write at l.pdf
 
Please answer the 4 questions at the end Causes and Outcomes of Co.pdf
Please answer the 4 questions at the end Causes and Outcomes of Co.pdfPlease answer the 4 questions at the end Causes and Outcomes of Co.pdf
Please answer the 4 questions at the end Causes and Outcomes of Co.pdf
 
please help In multiple regression analysis, residuals (YY^) shou.pdf
please help  In multiple regression analysis, residuals (YY^) shou.pdfplease help  In multiple regression analysis, residuals (YY^) shou.pdf
please help In multiple regression analysis, residuals (YY^) shou.pdf
 
please fill in the chart A company that uses job order c.pdf
please fill in the chart A company that uses job order c.pdfplease fill in the chart A company that uses job order c.pdf
please fill in the chart A company that uses job order c.pdf
 
Please fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdfPlease fill in the code to run the program based on the following in.pdf
Please fill in the code to run the program based on the following in.pdf
 
Please explain fully each step and what inputs and the number of row.pdf
Please explain fully each step and what inputs and the number of row.pdfPlease explain fully each step and what inputs and the number of row.pdf
Please explain fully each step and what inputs and the number of row.pdf
 
please explain how attaker crack 2DES and show your work. 3DES = Run.pdf
please explain how attaker crack 2DES and show your work. 3DES = Run.pdfplease explain how attaker crack 2DES and show your work. 3DES = Run.pdf
please explain how attaker crack 2DES and show your work. 3DES = Run.pdf
 
Please explain answer choice 26. Small functionally disruptive hardw.pdf
Please explain answer choice 26. Small functionally disruptive hardw.pdfPlease explain answer choice 26. Small functionally disruptive hardw.pdf
Please explain answer choice 26. Small functionally disruptive hardw.pdf
 
Please explain answer choice 15. Match each of the following counter.pdf
Please explain answer choice 15. Match each of the following counter.pdfPlease explain answer choice 15. Match each of the following counter.pdf
Please explain answer choice 15. Match each of the following counter.pdf
 
Please draw an activity diagram using Enterprise. or draw using symb.pdf
Please draw an activity diagram using Enterprise. or draw using symb.pdfPlease draw an activity diagram using Enterprise. or draw using symb.pdf
Please draw an activity diagram using Enterprise. or draw using symb.pdf
 
please do the extr.pdf
please do the extr.pdfplease do the extr.pdf
please do the extr.pdf
 

Recently uploaded

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 

Recently uploaded (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 

Please fix pygame code so that the first Enemy bounces off the wal.pdf

  • 1. Please fix pygame code so that the first "Enemy" bounces off the walls of the screen. Thank You. import pygame import sys import math import random def pixel_collision(mask1, rect1, mask2, rect2): offset_x = rect2[0] - rect1[0] offset_y = rect2[1] - rect1[1] overlap = mask1.overlap(mask2, (offset_x, offset_y)) return overlap class Sprite: def __init__(self, image, x, y): self.image = image self.rectangle = image.get_rect() self.rectangle.center = (x, y) self.mask = pygame.mask.from_surface(image) def set_position(self, new_position): self.rectangle.center = new_position def draw(self, screen): screen.blit(self.image, self.rectangle) def is_colliding(self, other_sprite): return pixel_collision(self.mask, self.rectangle, other_sprite.mask, other_sprite.rectangle) class Enemy(Sprite): def __init__(self, image, width, height): super().__init__(image, width, height) self.rectangle.centerx = random.randint(0, width) self.rectangle.centery = random.randint(0, height) vx = random.uniform(-1, 1) vy = random.uniform(-1, 1) self.speed = (vx, vy) def move(self): self.rectangle.move_ip(self.speed) def bounce(self, width, height):
  • 2. if self.rectangle.left < 0 or self.rectangle.right > width: self.speed = (-self.speed[0], self.speed[1]) if self.rectangle.top < 0 or self.rectangle.bottom > height: self.speed = (self.speed[0], -self.speed[1]) class Enemy2(Sprite): def __init__(self, image, width, height): super().__init__(image, width, height) self.speed = (0, 0) self.acceleration = 0.1 def move(self, target_position): dx = target_position[0] - self.rectangle.centerx dy = target_position[1] - self.rectangle.centery dist = math.sqrt(dx ** 2 + dy ** 2) if dist != 0: dx_norm = dx / dist dy_norm = dy / dist self.speed = (self.speed[0] + dx_norm * self.acceleration, self.speed[1] + dy_norm * self.acceleration) self.rectangle.move_ip(self.speed[0], self.speed[1]) class PowerUp(Sprite): def __init__(self, image, width, height): super().__init__(image, width, height) def main(): pygame.init() myfont = pygame.font.SysFont('monospace', 24) width, height = 600, 400 screen = pygame.display.set_mode((width, height)) enemy1 = pygame.image.load("devil.png").convert_alpha() enemy2 = pygame.image.load("ghost.png").convert_alpha() enemy1_image = pygame.transform.smoothscale(enemy1, (50, 50)) enemy2_image = pygame.transform.smoothscale(enemy2, (50, 50)) enemy_sprites = [] enemy2_sprites = [] for i in range(5): enemy_sprites.append(Enemy(enemy1_image, width, height)) for i in range(2):
  • 3. enemy2_sprites.append(Enemy2(enemy2_image, width, height)) player_image = pygame.image.load("prayerhands.jpeg").convert_alpha() player_image = pygame.transform.scale(player_image, (50, 50)) x, y = 0, 0 player_sprite = Sprite(player_image, x, y) life = 3 powerup_image = pygame.image.load("life_powerup.jpeg").convert_alpha() powerups = [] is_playing = True clock = pygame.time.Clock() while is_playing: clock.tick(60) if life <= 0: is_playing = False for event in pygame.event.get(): if event.type == pygame.QUIT: is_playing = False pos = pygame.mouse.get_pos() player_sprite.set_position(pos) for enemy_sprite in enemy_sprites: if player_sprite.is_colliding(enemy_sprite): life -= 0.2 for powerup_sprite in powerups: if player_sprite.is_colliding(powerup_sprite): life += 1 powerups = [p for p in powerups if not player_sprite.is_colliding(p)] for enemy_sprite in enemy_sprites: enemy_sprite.move() enemy_sprite.bounce(width, height) for enemy2_sprite in enemy2_sprites: enemy2_sprite.move(player_sprite.rectangle.center) if random.random() < 0.01: powerups.append(PowerUp(powerup_image, random.randint(0, width), random.randint(0, height))) screen.fill((255, 255, 255)) for enemy_sprite in enemy_sprites:
  • 4. enemy_sprite.draw(screen) for enemy2_sprite in enemy2_sprites: enemy2_sprite.draw(screen) for powerup_sprite in powerups: powerup_sprite.draw(screen) player_sprite.draw(screen) text = "Life: " + str('%.1f' % life) label = myfont.render(text, True, (0, 0, 0)) screen.blit(label, (20, 20)) pygame.display.update() pygame.time.wait(2000) pygame.quit() sys.exit() if __name__ == "__main__": main()